es6.js 4.5 MB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191151921519315194151951519615197151981519915200152011520215203152041520515206152071520815209152101521115212152131521415215152161521715218152191522015221152221522315224152251522615227152281522915230152311523215233152341523515236152371523815239152401524115242152431524415245152461524715248152491525015251152521525315254152551525615257152581525915260152611526215263152641526515266152671526815269152701527115272152731527415275152761527715278152791528015281152821528315284152851528615287152881528915290152911529215293152941529515296152971529815299153001530115302153031530415305153061530715308153091531015311153121531315314153151531615317153181531915320153211532215323153241532515326153271532815329153301533115332153331533415335153361533715338153391534015341153421534315344153451534615347153481534915350153511535215353153541535515356153571535815359153601536115362153631536415365153661536715368153691537015371153721537315374153751537615377153781537915380153811538215383153841538515386153871538815389153901539115392153931539415395153961539715398153991540015401154021540315404154051540615407154081540915410154111541215413154141541515416154171541815419154201542115422154231542415425154261542715428154291543015431154321543315434154351543615437154381543915440154411544215443154441544515446154471544815449154501545115452154531545415455154561545715458154591546015461154621546315464154651546615467154681546915470154711547215473154741547515476154771547815479154801548115482154831548415485154861548715488154891549015491154921549315494154951549615497154981549915500155011550215503155041550515506155071550815509155101551115512155131551415515155161551715518155191552015521155221552315524155251552615527155281552915530155311553215533155341553515536155371553815539155401554115542155431554415545155461554715548155491555015551155521555315554155551555615557155581555915560155611556215563155641556515566155671556815569155701557115572155731557415575155761557715578155791558015581155821558315584155851558615587155881558915590155911559215593155941559515596155971559815599156001560115602156031560415605156061560715608156091561015611156121561315614156151561615617156181561915620156211562215623156241562515626156271562815629156301563115632156331563415635156361563715638156391564015641156421564315644156451564615647156481564915650156511565215653156541565515656156571565815659156601566115662156631566415665156661566715668156691567015671156721567315674156751567615677156781567915680156811568215683156841568515686156871568815689156901569115692156931569415695156961569715698156991570015701157021570315704157051570615707157081570915710157111571215713157141571515716157171571815719157201572115722157231572415725157261572715728157291573015731157321573315734157351573615737157381573915740157411574215743157441574515746157471574815749157501575115752157531575415755157561575715758157591576015761157621576315764157651576615767157681576915770157711577215773157741577515776157771577815779157801578115782157831578415785157861578715788157891579015791157921579315794157951579615797157981579915800158011580215803158041580515806158071580815809158101581115812158131581415815158161581715818158191582015821158221582315824158251582615827158281582915830158311583215833158341583515836158371583815839158401584115842158431584415845158461584715848158491585015851158521585315854158551585615857158581585915860158611586215863158641586515866158671586815869158701587115872158731587415875158761587715878158791588015881158821588315884158851588615887158881588915890158911589215893158941589515896158971589815899159001590115902159031590415905159061590715908159091591015911159121591315914159151591615917159181591915920159211592215923159241592515926159271592815929159301593115932159331593415935159361593715938159391594015941159421594315944159451594615947159481594915950159511595215953159541595515956159571595815959159601596115962159631596415965159661596715968159691597015971159721597315974159751597615977159781597915980159811598215983159841598515986159871598815989159901599115992159931599415995159961599715998159991600016001160021600316004160051600616007160081600916010160111601216013160141601516016160171601816019160201602116022160231602416025160261602716028160291603016031160321603316034160351603616037160381603916040160411604216043160441604516046160471604816049160501605116052160531605416055160561605716058160591606016061160621606316064160651606616067160681606916070160711607216073160741607516076160771607816079160801608116082160831608416085160861608716088160891609016091160921609316094160951609616097160981609916100161011610216103161041610516106161071610816109161101611116112161131611416115161161611716118161191612016121161221612316124161251612616127161281612916130161311613216133161341613516136161371613816139161401614116142161431614416145161461614716148161491615016151161521615316154161551615616157161581615916160161611616216163161641616516166161671616816169161701617116172161731617416175161761617716178161791618016181161821618316184161851618616187161881618916190161911619216193161941619516196161971619816199162001620116202162031620416205162061620716208162091621016211162121621316214162151621616217162181621916220162211622216223162241622516226162271622816229162301623116232162331623416235162361623716238162391624016241162421624316244162451624616247162481624916250162511625216253162541625516256162571625816259162601626116262162631626416265162661626716268162691627016271162721627316274162751627616277162781627916280162811628216283162841628516286162871628816289162901629116292162931629416295162961629716298162991630016301163021630316304163051630616307163081630916310163111631216313163141631516316163171631816319163201632116322163231632416325163261632716328163291633016331163321633316334163351633616337163381633916340163411634216343163441634516346163471634816349163501635116352163531635416355163561635716358163591636016361163621636316364163651636616367163681636916370163711637216373163741637516376163771637816379163801638116382163831638416385163861638716388163891639016391163921639316394163951639616397163981639916400164011640216403164041640516406164071640816409164101641116412164131641416415164161641716418164191642016421164221642316424164251642616427164281642916430164311643216433164341643516436164371643816439164401644116442164431644416445164461644716448164491645016451164521645316454164551645616457164581645916460164611646216463164641646516466164671646816469164701647116472164731647416475164761647716478164791648016481164821648316484164851648616487164881648916490164911649216493164941649516496164971649816499165001650116502165031650416505165061650716508165091651016511165121651316514165151651616517165181651916520165211652216523165241652516526165271652816529165301653116532165331653416535165361653716538165391654016541165421654316544165451654616547165481654916550165511655216553165541655516556165571655816559165601656116562165631656416565165661656716568165691657016571165721657316574165751657616577165781657916580165811658216583165841658516586165871658816589165901659116592165931659416595165961659716598165991660016601166021660316604166051660616607166081660916610166111661216613166141661516616166171661816619166201662116622166231662416625166261662716628166291663016631166321663316634166351663616637166381663916640166411664216643166441664516646166471664816649166501665116652166531665416655166561665716658166591666016661166621666316664166651666616667166681666916670166711667216673166741667516676166771667816679166801668116682166831668416685166861668716688166891669016691166921669316694166951669616697166981669916700167011670216703167041670516706167071670816709167101671116712167131671416715167161671716718167191672016721167221672316724167251672616727167281672916730167311673216733167341673516736167371673816739167401674116742167431674416745167461674716748167491675016751167521675316754167551675616757167581675916760167611676216763167641676516766167671676816769167701677116772167731677416775167761677716778167791678016781167821678316784167851678616787167881678916790167911679216793167941679516796167971679816799168001680116802168031680416805168061680716808168091681016811168121681316814168151681616817168181681916820168211682216823168241682516826168271682816829168301683116832168331683416835168361683716838168391684016841168421684316844168451684616847168481684916850168511685216853168541685516856168571685816859168601686116862168631686416865168661686716868168691687016871168721687316874168751687616877168781687916880168811688216883168841688516886168871688816889168901689116892168931689416895168961689716898168991690016901169021690316904169051690616907169081690916910169111691216913169141691516916169171691816919169201692116922169231692416925169261692716928169291693016931169321693316934169351693616937169381693916940169411694216943169441694516946169471694816949169501695116952169531695416955169561695716958169591696016961169621696316964169651696616967169681696916970169711697216973169741697516976169771697816979169801698116982169831698416985169861698716988169891699016991169921699316994169951699616997169981699917000170011700217003170041700517006170071700817009170101701117012170131701417015170161701717018170191702017021170221702317024170251702617027170281702917030170311703217033170341703517036170371703817039170401704117042170431704417045170461704717048170491705017051170521705317054170551705617057170581705917060170611706217063170641706517066170671706817069170701707117072170731707417075170761707717078170791708017081170821708317084170851708617087170881708917090170911709217093170941709517096170971709817099171001710117102171031710417105171061710717108171091711017111171121711317114171151711617117171181711917120171211712217123171241712517126171271712817129171301713117132171331713417135171361713717138171391714017141171421714317144171451714617147171481714917150171511715217153171541715517156171571715817159171601716117162171631716417165171661716717168171691717017171171721717317174171751717617177171781717917180171811718217183171841718517186171871718817189171901719117192171931719417195171961719717198171991720017201172021720317204172051720617207172081720917210172111721217213172141721517216172171721817219172201722117222172231722417225172261722717228172291723017231172321723317234172351723617237172381723917240172411724217243172441724517246172471724817249172501725117252172531725417255172561725717258172591726017261172621726317264172651726617267172681726917270172711727217273172741727517276172771727817279172801728117282172831728417285172861728717288172891729017291172921729317294172951729617297172981729917300173011730217303173041730517306173071730817309173101731117312173131731417315173161731717318173191732017321173221732317324173251732617327173281732917330173311733217333173341733517336173371733817339173401734117342173431734417345173461734717348173491735017351173521735317354173551735617357173581735917360173611736217363173641736517366173671736817369173701737117372173731737417375173761737717378173791738017381173821738317384173851738617387173881738917390173911739217393173941739517396173971739817399174001740117402174031740417405174061740717408174091741017411174121741317414174151741617417174181741917420174211742217423174241742517426174271742817429174301743117432174331743417435174361743717438174391744017441174421744317444174451744617447174481744917450174511745217453174541745517456174571745817459174601746117462174631746417465174661746717468174691747017471174721747317474174751747617477174781747917480174811748217483174841748517486174871748817489174901749117492174931749417495174961749717498174991750017501175021750317504175051750617507175081750917510175111751217513175141751517516175171751817519175201752117522175231752417525175261752717528175291753017531175321753317534175351753617537175381753917540175411754217543175441754517546175471754817549175501755117552175531755417555175561755717558175591756017561175621756317564175651756617567175681756917570175711757217573175741757517576175771757817579175801758117582175831758417585175861758717588175891759017591175921759317594175951759617597175981759917600176011760217603176041760517606176071760817609176101761117612176131761417615176161761717618176191762017621176221762317624176251762617627176281762917630176311763217633176341763517636176371763817639176401764117642176431764417645176461764717648176491765017651176521765317654176551765617657176581765917660176611766217663176641766517666176671766817669176701767117672176731767417675176761767717678176791768017681176821768317684176851768617687176881768917690176911769217693176941769517696176971769817699177001770117702177031770417705177061770717708177091771017711177121771317714177151771617717177181771917720177211772217723177241772517726177271772817729177301773117732177331773417735177361773717738177391774017741177421774317744177451774617747177481774917750177511775217753177541775517756177571775817759177601776117762177631776417765177661776717768177691777017771177721777317774177751777617777177781777917780177811778217783177841778517786177871778817789177901779117792177931779417795177961779717798177991780017801178021780317804178051780617807178081780917810178111781217813178141781517816178171781817819178201782117822178231782417825178261782717828178291783017831178321783317834178351783617837178381783917840178411784217843178441784517846178471784817849178501785117852178531785417855178561785717858178591786017861178621786317864178651786617867178681786917870178711787217873178741787517876178771787817879178801788117882178831788417885178861788717888178891789017891178921789317894178951789617897178981789917900179011790217903179041790517906179071790817909179101791117912179131791417915179161791717918179191792017921179221792317924179251792617927179281792917930179311793217933179341793517936179371793817939179401794117942179431794417945179461794717948179491795017951179521795317954179551795617957179581795917960179611796217963179641796517966179671796817969179701797117972179731797417975179761797717978179791798017981179821798317984179851798617987179881798917990179911799217993179941799517996179971799817999180001800118002180031800418005180061800718008180091801018011180121801318014180151801618017180181801918020180211802218023180241802518026180271802818029180301803118032180331803418035180361803718038180391804018041180421804318044180451804618047180481804918050180511805218053180541805518056180571805818059180601806118062180631806418065180661806718068180691807018071180721807318074180751807618077180781807918080180811808218083180841808518086180871808818089180901809118092180931809418095180961809718098180991810018101181021810318104181051810618107181081810918110181111811218113181141811518116181171811818119181201812118122181231812418125181261812718128181291813018131181321813318134181351813618137181381813918140181411814218143181441814518146181471814818149181501815118152181531815418155181561815718158181591816018161181621816318164181651816618167181681816918170181711817218173181741817518176181771817818179181801818118182181831818418185181861818718188181891819018191181921819318194181951819618197181981819918200182011820218203182041820518206182071820818209182101821118212182131821418215182161821718218182191822018221182221822318224182251822618227182281822918230182311823218233182341823518236182371823818239182401824118242182431824418245182461824718248182491825018251182521825318254182551825618257182581825918260182611826218263182641826518266182671826818269182701827118272182731827418275182761827718278182791828018281182821828318284182851828618287182881828918290182911829218293182941829518296182971829818299183001830118302183031830418305183061830718308183091831018311183121831318314183151831618317183181831918320183211832218323183241832518326183271832818329183301833118332183331833418335183361833718338183391834018341183421834318344183451834618347183481834918350183511835218353183541835518356183571835818359183601836118362183631836418365183661836718368183691837018371183721837318374183751837618377183781837918380183811838218383183841838518386183871838818389183901839118392183931839418395183961839718398183991840018401184021840318404184051840618407184081840918410184111841218413184141841518416184171841818419184201842118422184231842418425184261842718428184291843018431184321843318434184351843618437184381843918440184411844218443184441844518446184471844818449184501845118452184531845418455184561845718458184591846018461184621846318464184651846618467184681846918470184711847218473184741847518476184771847818479184801848118482184831848418485184861848718488184891849018491184921849318494184951849618497184981849918500185011850218503185041850518506185071850818509185101851118512185131851418515185161851718518185191852018521185221852318524185251852618527185281852918530185311853218533185341853518536185371853818539185401854118542185431854418545185461854718548185491855018551185521855318554185551855618557185581855918560185611856218563185641856518566185671856818569185701857118572185731857418575185761857718578185791858018581185821858318584185851858618587185881858918590185911859218593185941859518596185971859818599186001860118602186031860418605186061860718608186091861018611186121861318614186151861618617186181861918620186211862218623186241862518626186271862818629186301863118632186331863418635186361863718638186391864018641186421864318644186451864618647186481864918650186511865218653186541865518656186571865818659186601866118662186631866418665186661866718668186691867018671186721867318674186751867618677186781867918680186811868218683186841868518686186871868818689186901869118692186931869418695186961869718698186991870018701187021870318704187051870618707187081870918710187111871218713187141871518716187171871818719187201872118722187231872418725187261872718728187291873018731187321873318734187351873618737187381873918740187411874218743187441874518746187471874818749187501875118752187531875418755187561875718758187591876018761187621876318764187651876618767187681876918770187711877218773187741877518776187771877818779187801878118782187831878418785187861878718788187891879018791187921879318794187951879618797187981879918800188011880218803188041880518806188071880818809188101881118812188131881418815188161881718818188191882018821188221882318824188251882618827188281882918830188311883218833188341883518836188371883818839188401884118842188431884418845188461884718848188491885018851188521885318854188551885618857188581885918860188611886218863188641886518866188671886818869188701887118872188731887418875188761887718878188791888018881188821888318884188851888618887188881888918890188911889218893188941889518896188971889818899189001890118902189031890418905189061890718908189091891018911189121891318914189151891618917189181891918920189211892218923189241892518926189271892818929189301893118932189331893418935189361893718938189391894018941189421894318944189451894618947189481894918950189511895218953189541895518956189571895818959189601896118962189631896418965189661896718968189691897018971189721897318974189751897618977189781897918980189811898218983189841898518986189871898818989189901899118992189931899418995189961899718998189991900019001190021900319004190051900619007190081900919010190111901219013190141901519016190171901819019190201902119022190231902419025190261902719028190291903019031190321903319034190351903619037190381903919040190411904219043190441904519046190471904819049190501905119052190531905419055190561905719058190591906019061190621906319064190651906619067190681906919070190711907219073190741907519076190771907819079190801908119082190831908419085190861908719088190891909019091190921909319094190951909619097190981909919100191011910219103191041910519106191071910819109191101911119112191131911419115191161911719118191191912019121191221912319124191251912619127191281912919130191311913219133191341913519136191371913819139191401914119142191431914419145191461914719148191491915019151191521915319154191551915619157191581915919160191611916219163191641916519166191671916819169191701917119172191731917419175191761917719178191791918019181191821918319184191851918619187191881918919190191911919219193191941919519196191971919819199192001920119202192031920419205192061920719208192091921019211192121921319214192151921619217192181921919220192211922219223192241922519226192271922819229192301923119232192331923419235192361923719238192391924019241192421924319244192451924619247192481924919250192511925219253192541925519256192571925819259192601926119262192631926419265192661926719268192691927019271192721927319274192751927619277192781927919280192811928219283192841928519286192871928819289192901929119292192931929419295192961929719298192991930019301193021930319304193051930619307193081930919310193111931219313193141931519316193171931819319193201932119322193231932419325193261932719328193291933019331193321933319334193351933619337193381933919340193411934219343193441934519346193471934819349193501935119352193531935419355193561935719358193591936019361193621936319364193651936619367193681936919370193711937219373193741937519376193771937819379193801938119382193831938419385193861938719388193891939019391193921939319394193951939619397193981939919400194011940219403194041940519406194071940819409194101941119412194131941419415194161941719418194191942019421194221942319424194251942619427194281942919430194311943219433194341943519436194371943819439194401944119442194431944419445194461944719448194491945019451194521945319454194551945619457194581945919460194611946219463194641946519466194671946819469194701947119472194731947419475194761947719478194791948019481194821948319484194851948619487194881948919490194911949219493194941949519496194971949819499195001950119502195031950419505195061950719508195091951019511195121951319514195151951619517195181951919520195211952219523195241952519526195271952819529195301953119532195331953419535195361953719538195391954019541195421954319544195451954619547195481954919550195511955219553195541955519556195571955819559195601956119562195631956419565195661956719568195691957019571195721957319574195751957619577195781957919580195811958219583195841958519586195871958819589195901959119592195931959419595195961959719598195991960019601196021960319604196051960619607196081960919610196111961219613196141961519616196171961819619196201962119622196231962419625196261962719628196291963019631196321963319634196351963619637196381963919640196411964219643196441964519646196471964819649196501965119652196531965419655196561965719658196591966019661196621966319664196651966619667196681966919670196711967219673196741967519676196771967819679196801968119682196831968419685196861968719688196891969019691196921969319694196951969619697196981969919700197011970219703197041970519706197071970819709197101971119712197131971419715197161971719718197191972019721197221972319724197251972619727197281972919730197311973219733197341973519736197371973819739197401974119742197431974419745197461974719748197491975019751197521975319754197551975619757197581975919760197611976219763197641976519766197671976819769197701977119772197731977419775197761977719778197791978019781197821978319784197851978619787197881978919790197911979219793197941979519796197971979819799198001980119802198031980419805198061980719808198091981019811198121981319814198151981619817198181981919820198211982219823198241982519826198271982819829198301983119832198331983419835198361983719838198391984019841198421984319844198451984619847198481984919850198511985219853198541985519856198571985819859198601986119862198631986419865198661986719868198691987019871198721987319874198751987619877198781987919880198811988219883198841988519886198871988819889198901989119892198931989419895198961989719898198991990019901199021990319904199051990619907199081990919910199111991219913199141991519916199171991819919199201992119922199231992419925199261992719928199291993019931199321993319934199351993619937199381993919940199411994219943199441994519946199471994819949199501995119952199531995419955199561995719958199591996019961199621996319964199651996619967199681996919970199711997219973199741997519976199771997819979199801998119982199831998419985199861998719988199891999019991199921999319994199951999619997199981999920000200012000220003200042000520006200072000820009200102001120012200132001420015200162001720018200192002020021200222002320024200252002620027200282002920030200312003220033200342003520036200372003820039200402004120042200432004420045200462004720048200492005020051200522005320054200552005620057200582005920060200612006220063200642006520066200672006820069200702007120072200732007420075200762007720078200792008020081200822008320084200852008620087200882008920090200912009220093200942009520096200972009820099201002010120102201032010420105201062010720108201092011020111201122011320114201152011620117201182011920120201212012220123201242012520126201272012820129201302013120132201332013420135201362013720138201392014020141201422014320144201452014620147201482014920150201512015220153201542015520156201572015820159201602016120162201632016420165201662016720168201692017020171201722017320174201752017620177201782017920180201812018220183201842018520186201872018820189201902019120192201932019420195201962019720198201992020020201202022020320204202052020620207202082020920210202112021220213202142021520216202172021820219202202022120222202232022420225202262022720228202292023020231202322023320234202352023620237202382023920240202412024220243202442024520246202472024820249202502025120252202532025420255202562025720258202592026020261202622026320264202652026620267202682026920270202712027220273202742027520276202772027820279202802028120282202832028420285202862028720288202892029020291202922029320294202952029620297202982029920300203012030220303203042030520306203072030820309203102031120312203132031420315203162031720318203192032020321203222032320324203252032620327203282032920330203312033220333203342033520336203372033820339203402034120342203432034420345203462034720348203492035020351203522035320354203552035620357203582035920360203612036220363203642036520366203672036820369203702037120372203732037420375203762037720378203792038020381203822038320384203852038620387203882038920390203912039220393203942039520396203972039820399204002040120402204032040420405204062040720408204092041020411204122041320414204152041620417204182041920420204212042220423204242042520426204272042820429204302043120432204332043420435204362043720438204392044020441204422044320444204452044620447204482044920450204512045220453204542045520456204572045820459204602046120462204632046420465204662046720468204692047020471204722047320474204752047620477204782047920480204812048220483204842048520486204872048820489204902049120492204932049420495204962049720498204992050020501205022050320504205052050620507205082050920510205112051220513205142051520516205172051820519205202052120522205232052420525205262052720528205292053020531205322053320534205352053620537205382053920540205412054220543205442054520546205472054820549205502055120552205532055420555205562055720558205592056020561205622056320564205652056620567205682056920570205712057220573205742057520576205772057820579205802058120582205832058420585205862058720588205892059020591205922059320594205952059620597205982059920600206012060220603206042060520606206072060820609206102061120612206132061420615206162061720618206192062020621206222062320624206252062620627206282062920630206312063220633206342063520636206372063820639206402064120642206432064420645206462064720648206492065020651206522065320654206552065620657206582065920660206612066220663206642066520666206672066820669206702067120672206732067420675206762067720678206792068020681206822068320684206852068620687206882068920690206912069220693206942069520696206972069820699207002070120702207032070420705207062070720708207092071020711207122071320714207152071620717207182071920720207212072220723207242072520726207272072820729207302073120732207332073420735207362073720738207392074020741207422074320744207452074620747207482074920750207512075220753207542075520756207572075820759207602076120762207632076420765207662076720768207692077020771207722077320774207752077620777207782077920780207812078220783207842078520786207872078820789207902079120792207932079420795207962079720798207992080020801208022080320804208052080620807208082080920810208112081220813208142081520816208172081820819208202082120822208232082420825208262082720828208292083020831208322083320834208352083620837208382083920840208412084220843208442084520846208472084820849208502085120852208532085420855208562085720858208592086020861208622086320864208652086620867208682086920870208712087220873208742087520876208772087820879208802088120882208832088420885208862088720888208892089020891208922089320894208952089620897208982089920900209012090220903209042090520906209072090820909209102091120912209132091420915209162091720918209192092020921209222092320924209252092620927209282092920930209312093220933209342093520936209372093820939209402094120942209432094420945209462094720948209492095020951209522095320954209552095620957209582095920960209612096220963209642096520966209672096820969209702097120972209732097420975209762097720978209792098020981209822098320984209852098620987209882098920990209912099220993209942099520996209972099820999210002100121002210032100421005210062100721008210092101021011210122101321014210152101621017210182101921020210212102221023210242102521026210272102821029210302103121032210332103421035210362103721038210392104021041210422104321044210452104621047210482104921050210512105221053210542105521056210572105821059210602106121062210632106421065210662106721068210692107021071210722107321074210752107621077210782107921080210812108221083210842108521086210872108821089210902109121092210932109421095210962109721098210992110021101211022110321104211052110621107211082110921110211112111221113211142111521116211172111821119211202112121122211232112421125211262112721128211292113021131211322113321134211352113621137211382113921140211412114221143211442114521146211472114821149211502115121152211532115421155211562115721158211592116021161211622116321164211652116621167211682116921170211712117221173211742117521176211772117821179211802118121182211832118421185211862118721188211892119021191211922119321194211952119621197211982119921200212012120221203212042120521206212072120821209212102121121212212132121421215212162121721218212192122021221212222122321224212252122621227212282122921230212312123221233212342123521236212372123821239212402124121242212432124421245212462124721248212492125021251212522125321254212552125621257212582125921260212612126221263212642126521266212672126821269212702127121272212732127421275212762127721278212792128021281212822128321284212852128621287212882128921290212912129221293212942129521296212972129821299213002130121302213032130421305213062130721308213092131021311213122131321314213152131621317213182131921320213212132221323213242132521326213272132821329213302133121332213332133421335213362133721338213392134021341213422134321344213452134621347213482134921350213512135221353213542135521356213572135821359213602136121362213632136421365213662136721368213692137021371213722137321374213752137621377213782137921380213812138221383213842138521386213872138821389213902139121392213932139421395213962139721398213992140021401214022140321404214052140621407214082140921410214112141221413214142141521416214172141821419214202142121422214232142421425214262142721428214292143021431214322143321434214352143621437214382143921440214412144221443214442144521446214472144821449214502145121452214532145421455214562145721458214592146021461214622146321464214652146621467214682146921470214712147221473214742147521476214772147821479214802148121482214832148421485214862148721488214892149021491214922149321494214952149621497214982149921500215012150221503215042150521506215072150821509215102151121512215132151421515215162151721518215192152021521215222152321524215252152621527215282152921530215312153221533215342153521536215372153821539215402154121542215432154421545215462154721548215492155021551215522155321554215552155621557215582155921560215612156221563215642156521566215672156821569215702157121572215732157421575215762157721578215792158021581215822158321584215852158621587215882158921590215912159221593215942159521596215972159821599216002160121602216032160421605216062160721608216092161021611216122161321614216152161621617216182161921620216212162221623216242162521626216272162821629216302163121632216332163421635216362163721638216392164021641216422164321644216452164621647216482164921650216512165221653216542165521656216572165821659216602166121662216632166421665216662166721668216692167021671216722167321674216752167621677216782167921680216812168221683216842168521686216872168821689216902169121692216932169421695216962169721698216992170021701217022170321704217052170621707217082170921710217112171221713217142171521716217172171821719217202172121722217232172421725217262172721728217292173021731217322173321734217352173621737217382173921740217412174221743217442174521746217472174821749217502175121752217532175421755217562175721758217592176021761217622176321764217652176621767217682176921770217712177221773217742177521776217772177821779217802178121782217832178421785217862178721788217892179021791217922179321794217952179621797217982179921800218012180221803218042180521806218072180821809218102181121812218132181421815218162181721818218192182021821218222182321824218252182621827218282182921830218312183221833218342183521836218372183821839218402184121842218432184421845218462184721848218492185021851218522185321854218552185621857218582185921860218612186221863218642186521866218672186821869218702187121872218732187421875218762187721878218792188021881218822188321884218852188621887218882188921890218912189221893218942189521896218972189821899219002190121902219032190421905219062190721908219092191021911219122191321914219152191621917219182191921920219212192221923219242192521926219272192821929219302193121932219332193421935219362193721938219392194021941219422194321944219452194621947219482194921950219512195221953219542195521956219572195821959219602196121962219632196421965219662196721968219692197021971219722197321974219752197621977219782197921980219812198221983219842198521986219872198821989219902199121992219932199421995219962199721998219992200022001220022200322004220052200622007220082200922010220112201222013220142201522016220172201822019220202202122022220232202422025220262202722028220292203022031220322203322034220352203622037220382203922040220412204222043220442204522046220472204822049220502205122052220532205422055220562205722058220592206022061220622206322064220652206622067220682206922070220712207222073220742207522076220772207822079220802208122082220832208422085220862208722088220892209022091220922209322094220952209622097220982209922100221012210222103221042210522106221072210822109221102211122112221132211422115221162211722118221192212022121221222212322124221252212622127221282212922130221312213222133221342213522136221372213822139221402214122142221432214422145221462214722148221492215022151221522215322154221552215622157221582215922160221612216222163221642216522166221672216822169221702217122172221732217422175221762217722178221792218022181221822218322184221852218622187221882218922190221912219222193221942219522196221972219822199222002220122202222032220422205222062220722208222092221022211222122221322214222152221622217222182221922220222212222222223222242222522226222272222822229222302223122232222332223422235222362223722238222392224022241222422224322244222452224622247222482224922250222512225222253222542225522256222572225822259222602226122262222632226422265222662226722268222692227022271222722227322274222752227622277222782227922280222812228222283222842228522286222872228822289222902229122292222932229422295222962229722298222992230022301223022230322304223052230622307223082230922310223112231222313223142231522316223172231822319223202232122322223232232422325223262232722328223292233022331223322233322334223352233622337223382233922340223412234222343223442234522346223472234822349223502235122352223532235422355223562235722358223592236022361223622236322364223652236622367223682236922370223712237222373223742237522376223772237822379223802238122382223832238422385223862238722388223892239022391223922239322394223952239622397223982239922400224012240222403224042240522406224072240822409224102241122412224132241422415224162241722418224192242022421224222242322424224252242622427224282242922430224312243222433224342243522436224372243822439224402244122442224432244422445224462244722448224492245022451224522245322454224552245622457224582245922460224612246222463224642246522466224672246822469224702247122472224732247422475224762247722478224792248022481224822248322484224852248622487224882248922490224912249222493224942249522496224972249822499225002250122502225032250422505225062250722508225092251022511225122251322514225152251622517225182251922520225212252222523225242252522526225272252822529225302253122532225332253422535225362253722538225392254022541225422254322544225452254622547225482254922550225512255222553225542255522556225572255822559225602256122562225632256422565225662256722568225692257022571225722257322574225752257622577225782257922580225812258222583225842258522586225872258822589225902259122592225932259422595225962259722598225992260022601226022260322604226052260622607226082260922610226112261222613226142261522616226172261822619226202262122622226232262422625226262262722628226292263022631226322263322634226352263622637226382263922640226412264222643226442264522646226472264822649226502265122652226532265422655226562265722658226592266022661226622266322664226652266622667226682266922670226712267222673226742267522676226772267822679226802268122682226832268422685226862268722688226892269022691226922269322694226952269622697226982269922700227012270222703227042270522706227072270822709227102271122712227132271422715227162271722718227192272022721227222272322724227252272622727227282272922730227312273222733227342273522736227372273822739227402274122742227432274422745227462274722748227492275022751227522275322754227552275622757227582275922760227612276222763227642276522766227672276822769227702277122772227732277422775227762277722778227792278022781227822278322784227852278622787227882278922790227912279222793227942279522796227972279822799228002280122802228032280422805228062280722808228092281022811228122281322814228152281622817228182281922820228212282222823228242282522826228272282822829228302283122832228332283422835228362283722838228392284022841228422284322844228452284622847228482284922850228512285222853228542285522856228572285822859228602286122862228632286422865228662286722868228692287022871228722287322874228752287622877228782287922880228812288222883228842288522886228872288822889228902289122892228932289422895228962289722898228992290022901229022290322904229052290622907229082290922910229112291222913229142291522916229172291822919229202292122922229232292422925229262292722928229292293022931229322293322934229352293622937229382293922940229412294222943229442294522946229472294822949229502295122952229532295422955229562295722958229592296022961229622296322964229652296622967229682296922970229712297222973229742297522976229772297822979229802298122982229832298422985229862298722988229892299022991229922299322994229952299622997229982299923000230012300223003230042300523006230072300823009230102301123012230132301423015230162301723018230192302023021230222302323024230252302623027230282302923030230312303223033230342303523036230372303823039230402304123042230432304423045230462304723048230492305023051230522305323054230552305623057230582305923060230612306223063230642306523066230672306823069230702307123072230732307423075230762307723078230792308023081230822308323084230852308623087230882308923090230912309223093230942309523096230972309823099231002310123102231032310423105231062310723108231092311023111231122311323114231152311623117231182311923120231212312223123231242312523126231272312823129231302313123132231332313423135231362313723138231392314023141231422314323144231452314623147231482314923150231512315223153231542315523156231572315823159231602316123162231632316423165231662316723168231692317023171231722317323174231752317623177231782317923180231812318223183231842318523186231872318823189231902319123192231932319423195231962319723198231992320023201232022320323204232052320623207232082320923210232112321223213232142321523216232172321823219232202322123222232232322423225232262322723228232292323023231232322323323234232352323623237232382323923240232412324223243232442324523246232472324823249232502325123252232532325423255232562325723258232592326023261232622326323264232652326623267232682326923270232712327223273232742327523276232772327823279232802328123282232832328423285232862328723288232892329023291232922329323294232952329623297232982329923300233012330223303233042330523306233072330823309233102331123312233132331423315233162331723318233192332023321233222332323324233252332623327233282332923330233312333223333233342333523336233372333823339233402334123342233432334423345233462334723348233492335023351233522335323354233552335623357233582335923360233612336223363233642336523366233672336823369233702337123372233732337423375233762337723378233792338023381233822338323384233852338623387233882338923390233912339223393233942339523396233972339823399234002340123402234032340423405234062340723408234092341023411234122341323414234152341623417234182341923420234212342223423234242342523426234272342823429234302343123432234332343423435234362343723438234392344023441234422344323444234452344623447234482344923450234512345223453234542345523456234572345823459234602346123462234632346423465234662346723468234692347023471234722347323474234752347623477234782347923480234812348223483234842348523486234872348823489234902349123492234932349423495234962349723498234992350023501235022350323504235052350623507235082350923510235112351223513235142351523516235172351823519235202352123522235232352423525235262352723528235292353023531235322353323534235352353623537235382353923540235412354223543235442354523546235472354823549235502355123552235532355423555235562355723558235592356023561235622356323564235652356623567235682356923570235712357223573235742357523576235772357823579235802358123582235832358423585235862358723588235892359023591235922359323594235952359623597235982359923600236012360223603236042360523606236072360823609236102361123612236132361423615236162361723618236192362023621236222362323624236252362623627236282362923630236312363223633236342363523636236372363823639236402364123642236432364423645236462364723648236492365023651236522365323654236552365623657236582365923660236612366223663236642366523666236672366823669236702367123672236732367423675236762367723678236792368023681236822368323684236852368623687236882368923690236912369223693236942369523696236972369823699237002370123702237032370423705237062370723708237092371023711237122371323714237152371623717237182371923720237212372223723237242372523726237272372823729237302373123732237332373423735237362373723738237392374023741237422374323744237452374623747237482374923750237512375223753237542375523756237572375823759237602376123762237632376423765237662376723768237692377023771237722377323774237752377623777237782377923780237812378223783237842378523786237872378823789237902379123792237932379423795237962379723798237992380023801238022380323804238052380623807238082380923810238112381223813238142381523816238172381823819238202382123822238232382423825238262382723828238292383023831238322383323834238352383623837238382383923840238412384223843238442384523846238472384823849238502385123852238532385423855238562385723858238592386023861238622386323864238652386623867238682386923870238712387223873238742387523876238772387823879238802388123882238832388423885238862388723888238892389023891238922389323894238952389623897238982389923900239012390223903239042390523906239072390823909239102391123912239132391423915239162391723918239192392023921239222392323924239252392623927239282392923930239312393223933239342393523936239372393823939239402394123942239432394423945239462394723948239492395023951239522395323954239552395623957239582395923960239612396223963239642396523966239672396823969239702397123972239732397423975239762397723978239792398023981239822398323984239852398623987239882398923990239912399223993239942399523996239972399823999240002400124002240032400424005240062400724008240092401024011240122401324014240152401624017240182401924020240212402224023240242402524026240272402824029240302403124032240332403424035240362403724038240392404024041240422404324044240452404624047240482404924050240512405224053240542405524056240572405824059240602406124062240632406424065240662406724068240692407024071240722407324074240752407624077240782407924080240812408224083240842408524086240872408824089240902409124092240932409424095240962409724098240992410024101241022410324104241052410624107241082410924110241112411224113241142411524116241172411824119241202412124122241232412424125241262412724128241292413024131241322413324134241352413624137241382413924140241412414224143241442414524146241472414824149241502415124152241532415424155241562415724158241592416024161241622416324164241652416624167241682416924170241712417224173241742417524176241772417824179241802418124182241832418424185241862418724188241892419024191241922419324194241952419624197241982419924200242012420224203242042420524206242072420824209242102421124212242132421424215242162421724218242192422024221242222422324224242252422624227242282422924230242312423224233242342423524236242372423824239242402424124242242432424424245242462424724248242492425024251242522425324254242552425624257242582425924260242612426224263242642426524266242672426824269242702427124272242732427424275242762427724278242792428024281242822428324284242852428624287242882428924290242912429224293242942429524296242972429824299243002430124302243032430424305243062430724308243092431024311243122431324314243152431624317243182431924320243212432224323243242432524326243272432824329243302433124332243332433424335243362433724338243392434024341243422434324344243452434624347243482434924350243512435224353243542435524356243572435824359243602436124362243632436424365243662436724368243692437024371243722437324374243752437624377243782437924380243812438224383243842438524386243872438824389243902439124392243932439424395243962439724398243992440024401244022440324404244052440624407244082440924410244112441224413244142441524416244172441824419244202442124422244232442424425244262442724428244292443024431244322443324434244352443624437244382443924440244412444224443244442444524446244472444824449244502445124452244532445424455244562445724458244592446024461244622446324464244652446624467244682446924470244712447224473244742447524476244772447824479244802448124482244832448424485244862448724488244892449024491244922449324494244952449624497244982449924500245012450224503245042450524506245072450824509245102451124512245132451424515245162451724518245192452024521245222452324524245252452624527245282452924530245312453224533245342453524536245372453824539245402454124542245432454424545245462454724548245492455024551245522455324554245552455624557245582455924560245612456224563245642456524566245672456824569245702457124572245732457424575245762457724578245792458024581245822458324584245852458624587245882458924590245912459224593245942459524596245972459824599246002460124602246032460424605246062460724608246092461024611246122461324614246152461624617246182461924620246212462224623246242462524626246272462824629246302463124632246332463424635246362463724638246392464024641246422464324644246452464624647246482464924650246512465224653246542465524656246572465824659246602466124662246632466424665246662466724668246692467024671246722467324674246752467624677246782467924680246812468224683246842468524686246872468824689246902469124692246932469424695246962469724698246992470024701247022470324704247052470624707247082470924710247112471224713247142471524716247172471824719247202472124722247232472424725247262472724728247292473024731247322473324734247352473624737247382473924740247412474224743247442474524746247472474824749247502475124752247532475424755247562475724758247592476024761247622476324764247652476624767247682476924770247712477224773247742477524776247772477824779247802478124782247832478424785247862478724788247892479024791247922479324794247952479624797247982479924800248012480224803248042480524806248072480824809248102481124812248132481424815248162481724818248192482024821248222482324824248252482624827248282482924830248312483224833248342483524836248372483824839248402484124842248432484424845248462484724848248492485024851248522485324854248552485624857248582485924860248612486224863248642486524866248672486824869248702487124872248732487424875248762487724878248792488024881248822488324884248852488624887248882488924890248912489224893248942489524896248972489824899249002490124902249032490424905249062490724908249092491024911249122491324914249152491624917249182491924920249212492224923249242492524926249272492824929249302493124932249332493424935249362493724938249392494024941249422494324944249452494624947249482494924950249512495224953249542495524956249572495824959249602496124962249632496424965249662496724968249692497024971249722497324974249752497624977249782497924980249812498224983249842498524986249872498824989249902499124992249932499424995249962499724998249992500025001250022500325004250052500625007250082500925010250112501225013250142501525016250172501825019250202502125022250232502425025250262502725028250292503025031250322503325034250352503625037250382503925040250412504225043250442504525046250472504825049250502505125052250532505425055250562505725058250592506025061250622506325064250652506625067250682506925070250712507225073250742507525076250772507825079250802508125082250832508425085250862508725088250892509025091250922509325094250952509625097250982509925100251012510225103251042510525106251072510825109251102511125112251132511425115251162511725118251192512025121251222512325124251252512625127251282512925130251312513225133251342513525136251372513825139251402514125142251432514425145251462514725148251492515025151251522515325154251552515625157251582515925160251612516225163251642516525166251672516825169251702517125172251732517425175251762517725178251792518025181251822518325184251852518625187251882518925190251912519225193251942519525196251972519825199252002520125202252032520425205252062520725208252092521025211252122521325214252152521625217252182521925220252212522225223252242522525226252272522825229252302523125232252332523425235252362523725238252392524025241252422524325244252452524625247252482524925250252512525225253252542525525256252572525825259252602526125262252632526425265252662526725268252692527025271252722527325274252752527625277252782527925280252812528225283252842528525286252872528825289252902529125292252932529425295252962529725298252992530025301253022530325304253052530625307253082530925310253112531225313253142531525316253172531825319253202532125322253232532425325253262532725328253292533025331253322533325334253352533625337253382533925340253412534225343253442534525346253472534825349253502535125352253532535425355253562535725358253592536025361253622536325364253652536625367253682536925370253712537225373253742537525376253772537825379253802538125382253832538425385253862538725388253892539025391253922539325394253952539625397253982539925400254012540225403254042540525406254072540825409254102541125412254132541425415254162541725418254192542025421254222542325424254252542625427254282542925430254312543225433254342543525436254372543825439254402544125442254432544425445254462544725448254492545025451254522545325454254552545625457254582545925460254612546225463254642546525466254672546825469254702547125472254732547425475254762547725478254792548025481254822548325484254852548625487254882548925490254912549225493254942549525496254972549825499255002550125502255032550425505255062550725508255092551025511255122551325514255152551625517255182551925520255212552225523255242552525526255272552825529255302553125532255332553425535255362553725538255392554025541255422554325544255452554625547255482554925550255512555225553255542555525556255572555825559255602556125562255632556425565255662556725568255692557025571255722557325574255752557625577255782557925580255812558225583255842558525586255872558825589255902559125592255932559425595255962559725598255992560025601256022560325604256052560625607256082560925610256112561225613256142561525616256172561825619256202562125622256232562425625256262562725628256292563025631256322563325634256352563625637256382563925640256412564225643256442564525646256472564825649256502565125652256532565425655256562565725658256592566025661256622566325664256652566625667256682566925670256712567225673256742567525676256772567825679256802568125682256832568425685256862568725688256892569025691256922569325694256952569625697256982569925700257012570225703257042570525706257072570825709257102571125712257132571425715257162571725718257192572025721257222572325724257252572625727257282572925730257312573225733257342573525736257372573825739257402574125742257432574425745257462574725748257492575025751257522575325754257552575625757257582575925760257612576225763257642576525766257672576825769257702577125772257732577425775257762577725778257792578025781257822578325784257852578625787257882578925790257912579225793257942579525796257972579825799258002580125802258032580425805258062580725808258092581025811258122581325814258152581625817258182581925820258212582225823258242582525826258272582825829258302583125832258332583425835258362583725838258392584025841258422584325844258452584625847258482584925850258512585225853258542585525856258572585825859258602586125862258632586425865258662586725868258692587025871258722587325874258752587625877258782587925880258812588225883258842588525886258872588825889258902589125892258932589425895258962589725898258992590025901259022590325904259052590625907259082590925910259112591225913259142591525916259172591825919259202592125922259232592425925259262592725928259292593025931259322593325934259352593625937259382593925940259412594225943259442594525946259472594825949259502595125952259532595425955259562595725958259592596025961259622596325964259652596625967259682596925970259712597225973259742597525976259772597825979259802598125982259832598425985259862598725988259892599025991259922599325994259952599625997259982599926000260012600226003260042600526006260072600826009260102601126012260132601426015260162601726018260192602026021260222602326024260252602626027260282602926030260312603226033260342603526036260372603826039260402604126042260432604426045260462604726048260492605026051260522605326054260552605626057260582605926060260612606226063260642606526066260672606826069260702607126072260732607426075260762607726078260792608026081260822608326084260852608626087260882608926090260912609226093260942609526096260972609826099261002610126102261032610426105261062610726108261092611026111261122611326114261152611626117261182611926120261212612226123261242612526126261272612826129261302613126132261332613426135261362613726138261392614026141261422614326144261452614626147261482614926150261512615226153261542615526156261572615826159261602616126162261632616426165261662616726168261692617026171261722617326174261752617626177261782617926180261812618226183261842618526186261872618826189261902619126192261932619426195261962619726198261992620026201262022620326204262052620626207262082620926210262112621226213262142621526216262172621826219262202622126222262232622426225262262622726228262292623026231262322623326234262352623626237262382623926240262412624226243262442624526246262472624826249262502625126252262532625426255262562625726258262592626026261262622626326264262652626626267262682626926270262712627226273262742627526276262772627826279262802628126282262832628426285262862628726288262892629026291262922629326294262952629626297262982629926300263012630226303263042630526306263072630826309263102631126312263132631426315263162631726318263192632026321263222632326324263252632626327263282632926330263312633226333263342633526336263372633826339263402634126342263432634426345263462634726348263492635026351263522635326354263552635626357263582635926360263612636226363263642636526366263672636826369263702637126372263732637426375263762637726378263792638026381263822638326384263852638626387263882638926390263912639226393263942639526396263972639826399264002640126402264032640426405264062640726408264092641026411264122641326414264152641626417264182641926420264212642226423264242642526426264272642826429264302643126432264332643426435264362643726438264392644026441264422644326444264452644626447264482644926450264512645226453264542645526456264572645826459264602646126462264632646426465264662646726468264692647026471264722647326474264752647626477264782647926480264812648226483264842648526486264872648826489264902649126492264932649426495264962649726498264992650026501265022650326504265052650626507265082650926510265112651226513265142651526516265172651826519265202652126522265232652426525265262652726528265292653026531265322653326534265352653626537265382653926540265412654226543265442654526546265472654826549265502655126552265532655426555265562655726558265592656026561265622656326564265652656626567265682656926570265712657226573265742657526576265772657826579265802658126582265832658426585265862658726588265892659026591265922659326594265952659626597265982659926600266012660226603266042660526606266072660826609266102661126612266132661426615266162661726618266192662026621266222662326624266252662626627266282662926630266312663226633266342663526636266372663826639266402664126642266432664426645266462664726648266492665026651266522665326654266552665626657266582665926660266612666226663266642666526666266672666826669266702667126672266732667426675266762667726678266792668026681266822668326684266852668626687266882668926690266912669226693266942669526696266972669826699267002670126702267032670426705267062670726708267092671026711267122671326714267152671626717267182671926720267212672226723267242672526726267272672826729267302673126732267332673426735267362673726738267392674026741267422674326744267452674626747267482674926750267512675226753267542675526756267572675826759267602676126762267632676426765267662676726768267692677026771267722677326774267752677626777267782677926780267812678226783267842678526786267872678826789267902679126792267932679426795267962679726798267992680026801268022680326804268052680626807268082680926810268112681226813268142681526816268172681826819268202682126822268232682426825268262682726828268292683026831268322683326834268352683626837268382683926840268412684226843268442684526846268472684826849268502685126852268532685426855268562685726858268592686026861268622686326864268652686626867268682686926870268712687226873268742687526876268772687826879268802688126882268832688426885268862688726888268892689026891268922689326894268952689626897268982689926900269012690226903269042690526906269072690826909269102691126912269132691426915269162691726918269192692026921269222692326924269252692626927269282692926930269312693226933269342693526936269372693826939269402694126942269432694426945269462694726948269492695026951269522695326954269552695626957269582695926960269612696226963269642696526966269672696826969269702697126972269732697426975269762697726978269792698026981269822698326984269852698626987269882698926990269912699226993269942699526996269972699826999270002700127002270032700427005270062700727008270092701027011270122701327014270152701627017270182701927020270212702227023270242702527026270272702827029270302703127032270332703427035270362703727038270392704027041270422704327044270452704627047270482704927050270512705227053270542705527056270572705827059270602706127062270632706427065270662706727068270692707027071270722707327074270752707627077270782707927080270812708227083270842708527086270872708827089270902709127092270932709427095270962709727098270992710027101271022710327104271052710627107271082710927110271112711227113271142711527116271172711827119271202712127122271232712427125271262712727128271292713027131271322713327134271352713627137271382713927140271412714227143271442714527146271472714827149271502715127152271532715427155271562715727158271592716027161271622716327164271652716627167271682716927170271712717227173271742717527176271772717827179271802718127182271832718427185271862718727188271892719027191271922719327194271952719627197271982719927200272012720227203272042720527206272072720827209272102721127212272132721427215272162721727218272192722027221272222722327224272252722627227272282722927230272312723227233272342723527236272372723827239272402724127242272432724427245272462724727248272492725027251272522725327254272552725627257272582725927260272612726227263272642726527266272672726827269272702727127272272732727427275272762727727278272792728027281272822728327284272852728627287272882728927290272912729227293272942729527296272972729827299273002730127302273032730427305273062730727308273092731027311273122731327314273152731627317273182731927320273212732227323273242732527326273272732827329273302733127332273332733427335273362733727338273392734027341273422734327344273452734627347273482734927350273512735227353273542735527356273572735827359273602736127362273632736427365273662736727368273692737027371273722737327374273752737627377273782737927380273812738227383273842738527386273872738827389273902739127392273932739427395273962739727398273992740027401274022740327404274052740627407274082740927410274112741227413274142741527416274172741827419274202742127422274232742427425274262742727428274292743027431274322743327434274352743627437274382743927440274412744227443274442744527446274472744827449274502745127452274532745427455274562745727458274592746027461274622746327464274652746627467274682746927470274712747227473274742747527476274772747827479274802748127482274832748427485274862748727488274892749027491274922749327494274952749627497274982749927500275012750227503275042750527506275072750827509275102751127512275132751427515275162751727518275192752027521275222752327524275252752627527275282752927530275312753227533275342753527536275372753827539275402754127542275432754427545275462754727548275492755027551275522755327554275552755627557275582755927560275612756227563275642756527566275672756827569275702757127572275732757427575275762757727578275792758027581275822758327584275852758627587275882758927590275912759227593275942759527596275972759827599276002760127602276032760427605276062760727608276092761027611276122761327614276152761627617276182761927620276212762227623276242762527626276272762827629276302763127632276332763427635276362763727638276392764027641276422764327644276452764627647276482764927650276512765227653276542765527656276572765827659276602766127662276632766427665276662766727668276692767027671276722767327674276752767627677276782767927680276812768227683276842768527686276872768827689276902769127692276932769427695276962769727698276992770027701277022770327704277052770627707277082770927710277112771227713277142771527716277172771827719277202772127722277232772427725277262772727728277292773027731277322773327734277352773627737277382773927740277412774227743277442774527746277472774827749277502775127752277532775427755277562775727758277592776027761277622776327764277652776627767277682776927770277712777227773277742777527776277772777827779277802778127782277832778427785277862778727788277892779027791277922779327794277952779627797277982779927800278012780227803278042780527806278072780827809278102781127812278132781427815278162781727818278192782027821278222782327824278252782627827278282782927830278312783227833278342783527836278372783827839278402784127842278432784427845278462784727848278492785027851278522785327854278552785627857278582785927860278612786227863278642786527866278672786827869278702787127872278732787427875278762787727878278792788027881278822788327884278852788627887278882788927890278912789227893278942789527896278972789827899279002790127902279032790427905279062790727908279092791027911279122791327914279152791627917279182791927920279212792227923279242792527926279272792827929279302793127932279332793427935279362793727938279392794027941279422794327944279452794627947279482794927950279512795227953279542795527956279572795827959279602796127962279632796427965279662796727968279692797027971279722797327974279752797627977279782797927980279812798227983279842798527986279872798827989279902799127992279932799427995279962799727998279992800028001280022800328004280052800628007280082800928010280112801228013280142801528016280172801828019280202802128022280232802428025280262802728028280292803028031280322803328034280352803628037280382803928040280412804228043280442804528046280472804828049280502805128052280532805428055280562805728058280592806028061280622806328064280652806628067280682806928070280712807228073280742807528076280772807828079280802808128082280832808428085280862808728088280892809028091280922809328094280952809628097280982809928100281012810228103281042810528106281072810828109281102811128112281132811428115281162811728118281192812028121281222812328124281252812628127281282812928130281312813228133281342813528136281372813828139281402814128142281432814428145281462814728148281492815028151281522815328154281552815628157281582815928160281612816228163281642816528166281672816828169281702817128172281732817428175281762817728178281792818028181281822818328184281852818628187281882818928190281912819228193281942819528196281972819828199282002820128202282032820428205282062820728208282092821028211282122821328214282152821628217282182821928220282212822228223282242822528226282272822828229282302823128232282332823428235282362823728238282392824028241282422824328244282452824628247282482824928250282512825228253282542825528256282572825828259282602826128262282632826428265282662826728268282692827028271282722827328274282752827628277282782827928280282812828228283282842828528286282872828828289282902829128292282932829428295282962829728298282992830028301283022830328304283052830628307283082830928310283112831228313283142831528316283172831828319283202832128322283232832428325283262832728328283292833028331283322833328334283352833628337283382833928340283412834228343283442834528346283472834828349283502835128352283532835428355283562835728358283592836028361283622836328364283652836628367283682836928370283712837228373283742837528376283772837828379283802838128382283832838428385283862838728388283892839028391283922839328394283952839628397283982839928400284012840228403284042840528406284072840828409284102841128412284132841428415284162841728418284192842028421284222842328424284252842628427284282842928430284312843228433284342843528436284372843828439284402844128442284432844428445284462844728448284492845028451284522845328454284552845628457284582845928460284612846228463284642846528466284672846828469284702847128472284732847428475284762847728478284792848028481284822848328484284852848628487284882848928490284912849228493284942849528496284972849828499285002850128502285032850428505285062850728508285092851028511285122851328514285152851628517285182851928520285212852228523285242852528526285272852828529285302853128532285332853428535285362853728538285392854028541285422854328544285452854628547285482854928550285512855228553285542855528556285572855828559285602856128562285632856428565285662856728568285692857028571285722857328574285752857628577285782857928580285812858228583285842858528586285872858828589285902859128592285932859428595285962859728598285992860028601286022860328604286052860628607286082860928610286112861228613286142861528616286172861828619286202862128622286232862428625286262862728628286292863028631286322863328634286352863628637286382863928640286412864228643286442864528646286472864828649286502865128652286532865428655286562865728658286592866028661286622866328664286652866628667286682866928670286712867228673286742867528676286772867828679286802868128682286832868428685286862868728688286892869028691286922869328694286952869628697286982869928700287012870228703287042870528706287072870828709287102871128712287132871428715287162871728718287192872028721287222872328724287252872628727287282872928730287312873228733287342873528736287372873828739287402874128742287432874428745287462874728748287492875028751287522875328754287552875628757287582875928760287612876228763287642876528766287672876828769287702877128772287732877428775287762877728778287792878028781287822878328784287852878628787287882878928790287912879228793287942879528796287972879828799288002880128802288032880428805288062880728808288092881028811288122881328814288152881628817288182881928820288212882228823288242882528826288272882828829288302883128832288332883428835288362883728838288392884028841288422884328844288452884628847288482884928850288512885228853288542885528856288572885828859288602886128862288632886428865288662886728868288692887028871288722887328874288752887628877288782887928880288812888228883288842888528886288872888828889288902889128892288932889428895288962889728898288992890028901289022890328904289052890628907289082890928910289112891228913289142891528916289172891828919289202892128922289232892428925289262892728928289292893028931289322893328934289352893628937289382893928940289412894228943289442894528946289472894828949289502895128952289532895428955289562895728958289592896028961289622896328964289652896628967289682896928970289712897228973289742897528976289772897828979289802898128982289832898428985289862898728988289892899028991289922899328994289952899628997289982899929000290012900229003290042900529006290072900829009290102901129012290132901429015290162901729018290192902029021290222902329024290252902629027290282902929030290312903229033290342903529036290372903829039290402904129042290432904429045290462904729048290492905029051290522905329054290552905629057290582905929060290612906229063290642906529066290672906829069290702907129072290732907429075290762907729078290792908029081290822908329084290852908629087290882908929090290912909229093290942909529096290972909829099291002910129102291032910429105291062910729108291092911029111291122911329114291152911629117291182911929120291212912229123291242912529126291272912829129291302913129132291332913429135291362913729138291392914029141291422914329144291452914629147291482914929150291512915229153291542915529156291572915829159291602916129162291632916429165291662916729168291692917029171291722917329174291752917629177291782917929180291812918229183291842918529186291872918829189291902919129192291932919429195291962919729198291992920029201292022920329204292052920629207292082920929210292112921229213292142921529216292172921829219292202922129222292232922429225292262922729228292292923029231292322923329234292352923629237292382923929240292412924229243292442924529246292472924829249292502925129252292532925429255292562925729258292592926029261292622926329264292652926629267292682926929270292712927229273292742927529276292772927829279292802928129282292832928429285292862928729288292892929029291292922929329294292952929629297292982929929300293012930229303293042930529306293072930829309293102931129312293132931429315293162931729318293192932029321293222932329324293252932629327293282932929330293312933229333293342933529336293372933829339293402934129342293432934429345293462934729348293492935029351293522935329354293552935629357293582935929360293612936229363293642936529366293672936829369293702937129372293732937429375293762937729378293792938029381293822938329384293852938629387293882938929390293912939229393293942939529396293972939829399294002940129402294032940429405294062940729408294092941029411294122941329414294152941629417294182941929420294212942229423294242942529426294272942829429294302943129432294332943429435294362943729438294392944029441294422944329444294452944629447294482944929450294512945229453294542945529456294572945829459294602946129462294632946429465294662946729468294692947029471294722947329474294752947629477294782947929480294812948229483294842948529486294872948829489294902949129492294932949429495294962949729498294992950029501295022950329504295052950629507295082950929510295112951229513295142951529516295172951829519295202952129522295232952429525295262952729528295292953029531295322953329534295352953629537295382953929540295412954229543295442954529546295472954829549295502955129552295532955429555295562955729558295592956029561295622956329564295652956629567295682956929570295712957229573295742957529576295772957829579295802958129582295832958429585295862958729588295892959029591295922959329594295952959629597295982959929600296012960229603296042960529606296072960829609296102961129612296132961429615296162961729618296192962029621296222962329624296252962629627296282962929630296312963229633296342963529636296372963829639296402964129642296432964429645296462964729648296492965029651296522965329654296552965629657296582965929660296612966229663296642966529666296672966829669296702967129672296732967429675296762967729678296792968029681296822968329684296852968629687296882968929690296912969229693296942969529696296972969829699297002970129702297032970429705297062970729708297092971029711297122971329714297152971629717297182971929720297212972229723297242972529726297272972829729297302973129732297332973429735297362973729738297392974029741297422974329744297452974629747297482974929750297512975229753297542975529756297572975829759297602976129762297632976429765297662976729768297692977029771297722977329774297752977629777297782977929780297812978229783297842978529786297872978829789297902979129792297932979429795297962979729798297992980029801298022980329804298052980629807298082980929810298112981229813298142981529816298172981829819298202982129822298232982429825298262982729828298292983029831298322983329834298352983629837298382983929840298412984229843298442984529846298472984829849298502985129852298532985429855298562985729858298592986029861298622986329864298652986629867298682986929870298712987229873298742987529876298772987829879298802988129882298832988429885298862988729888298892989029891298922989329894298952989629897298982989929900299012990229903299042990529906299072990829909299102991129912299132991429915299162991729918299192992029921299222992329924299252992629927299282992929930299312993229933299342993529936299372993829939299402994129942299432994429945299462994729948299492995029951299522995329954299552995629957299582995929960299612996229963299642996529966299672996829969299702997129972299732997429975299762997729978299792998029981299822998329984299852998629987299882998929990299912999229993299942999529996299972999829999300003000130002300033000430005300063000730008300093001030011300123001330014300153001630017300183001930020300213002230023300243002530026300273002830029300303003130032300333003430035300363003730038300393004030041300423004330044300453004630047300483004930050300513005230053300543005530056300573005830059300603006130062300633006430065300663006730068300693007030071300723007330074300753007630077300783007930080300813008230083300843008530086300873008830089300903009130092300933009430095300963009730098300993010030101301023010330104301053010630107301083010930110301113011230113301143011530116301173011830119301203012130122301233012430125301263012730128301293013030131301323013330134301353013630137301383013930140301413014230143301443014530146301473014830149301503015130152301533015430155301563015730158301593016030161301623016330164301653016630167301683016930170301713017230173301743017530176301773017830179301803018130182301833018430185301863018730188301893019030191301923019330194301953019630197301983019930200302013020230203302043020530206302073020830209302103021130212302133021430215302163021730218302193022030221302223022330224302253022630227302283022930230302313023230233302343023530236302373023830239302403024130242302433024430245302463024730248302493025030251302523025330254302553025630257302583025930260302613026230263302643026530266302673026830269302703027130272302733027430275302763027730278302793028030281302823028330284302853028630287302883028930290302913029230293302943029530296302973029830299303003030130302303033030430305303063030730308303093031030311303123031330314303153031630317303183031930320303213032230323303243032530326303273032830329303303033130332303333033430335303363033730338303393034030341303423034330344303453034630347303483034930350303513035230353303543035530356303573035830359303603036130362303633036430365303663036730368303693037030371303723037330374303753037630377303783037930380303813038230383303843038530386303873038830389303903039130392303933039430395303963039730398303993040030401304023040330404304053040630407304083040930410304113041230413304143041530416304173041830419304203042130422304233042430425304263042730428304293043030431304323043330434304353043630437304383043930440304413044230443304443044530446304473044830449304503045130452304533045430455304563045730458304593046030461304623046330464304653046630467304683046930470304713047230473304743047530476304773047830479304803048130482304833048430485304863048730488304893049030491304923049330494304953049630497304983049930500305013050230503305043050530506305073050830509305103051130512305133051430515305163051730518305193052030521305223052330524305253052630527305283052930530305313053230533305343053530536305373053830539305403054130542305433054430545305463054730548305493055030551305523055330554305553055630557305583055930560305613056230563305643056530566305673056830569305703057130572305733057430575305763057730578305793058030581305823058330584305853058630587305883058930590305913059230593305943059530596305973059830599306003060130602306033060430605306063060730608306093061030611306123061330614306153061630617306183061930620306213062230623306243062530626306273062830629306303063130632306333063430635306363063730638306393064030641306423064330644306453064630647306483064930650306513065230653306543065530656306573065830659306603066130662306633066430665306663066730668306693067030671306723067330674306753067630677306783067930680306813068230683306843068530686306873068830689306903069130692306933069430695306963069730698306993070030701307023070330704307053070630707307083070930710307113071230713307143071530716307173071830719307203072130722307233072430725307263072730728307293073030731307323073330734307353073630737307383073930740307413074230743307443074530746307473074830749307503075130752307533075430755307563075730758307593076030761307623076330764307653076630767307683076930770307713077230773307743077530776307773077830779307803078130782307833078430785307863078730788307893079030791307923079330794307953079630797307983079930800308013080230803308043080530806308073080830809308103081130812308133081430815308163081730818308193082030821308223082330824308253082630827308283082930830308313083230833308343083530836308373083830839308403084130842308433084430845308463084730848308493085030851308523085330854308553085630857308583085930860308613086230863308643086530866308673086830869308703087130872308733087430875308763087730878308793088030881308823088330884308853088630887308883088930890308913089230893308943089530896308973089830899309003090130902309033090430905309063090730908309093091030911309123091330914309153091630917309183091930920309213092230923309243092530926309273092830929309303093130932309333093430935309363093730938309393094030941309423094330944309453094630947309483094930950309513095230953309543095530956309573095830959309603096130962309633096430965309663096730968309693097030971309723097330974309753097630977309783097930980309813098230983309843098530986309873098830989309903099130992309933099430995309963099730998309993100031001310023100331004310053100631007310083100931010310113101231013310143101531016310173101831019310203102131022310233102431025310263102731028310293103031031310323103331034310353103631037310383103931040310413104231043310443104531046310473104831049310503105131052310533105431055310563105731058310593106031061310623106331064310653106631067310683106931070310713107231073310743107531076310773107831079310803108131082310833108431085310863108731088310893109031091310923109331094310953109631097310983109931100311013110231103311043110531106311073110831109311103111131112311133111431115311163111731118311193112031121311223112331124311253112631127311283112931130311313113231133311343113531136311373113831139311403114131142311433114431145311463114731148311493115031151311523115331154311553115631157311583115931160311613116231163311643116531166311673116831169311703117131172311733117431175311763117731178311793118031181311823118331184311853118631187311883118931190311913119231193311943119531196311973119831199312003120131202312033120431205312063120731208312093121031211312123121331214312153121631217312183121931220312213122231223312243122531226312273122831229312303123131232312333123431235312363123731238312393124031241312423124331244312453124631247312483124931250312513125231253312543125531256312573125831259312603126131262312633126431265312663126731268312693127031271312723127331274312753127631277312783127931280312813128231283312843128531286312873128831289312903129131292312933129431295312963129731298312993130031301313023130331304313053130631307313083130931310313113131231313313143131531316313173131831319313203132131322313233132431325313263132731328313293133031331313323133331334313353133631337313383133931340313413134231343313443134531346313473134831349313503135131352313533135431355313563135731358313593136031361313623136331364313653136631367313683136931370313713137231373313743137531376313773137831379313803138131382313833138431385313863138731388313893139031391313923139331394313953139631397313983139931400314013140231403314043140531406314073140831409314103141131412314133141431415314163141731418314193142031421314223142331424314253142631427314283142931430314313143231433314343143531436314373143831439314403144131442314433144431445314463144731448314493145031451314523145331454314553145631457314583145931460314613146231463314643146531466314673146831469314703147131472314733147431475314763147731478314793148031481314823148331484314853148631487314883148931490314913149231493314943149531496314973149831499315003150131502315033150431505315063150731508315093151031511315123151331514315153151631517315183151931520315213152231523315243152531526315273152831529315303153131532315333153431535315363153731538315393154031541315423154331544315453154631547315483154931550315513155231553315543155531556315573155831559315603156131562315633156431565315663156731568315693157031571315723157331574315753157631577315783157931580315813158231583315843158531586315873158831589315903159131592315933159431595315963159731598315993160031601316023160331604316053160631607316083160931610316113161231613316143161531616316173161831619316203162131622316233162431625316263162731628316293163031631316323163331634316353163631637316383163931640316413164231643316443164531646316473164831649316503165131652316533165431655316563165731658316593166031661316623166331664316653166631667316683166931670316713167231673316743167531676316773167831679316803168131682316833168431685316863168731688316893169031691316923169331694316953169631697316983169931700317013170231703317043170531706317073170831709317103171131712317133171431715317163171731718317193172031721317223172331724317253172631727317283172931730317313173231733317343173531736317373173831739317403174131742317433174431745317463174731748317493175031751317523175331754317553175631757317583175931760317613176231763317643176531766317673176831769317703177131772317733177431775317763177731778317793178031781317823178331784317853178631787317883178931790317913179231793317943179531796317973179831799318003180131802318033180431805318063180731808318093181031811318123181331814318153181631817318183181931820318213182231823318243182531826318273182831829318303183131832318333183431835318363183731838318393184031841318423184331844318453184631847318483184931850318513185231853318543185531856318573185831859318603186131862318633186431865318663186731868318693187031871318723187331874318753187631877318783187931880318813188231883318843188531886318873188831889318903189131892318933189431895318963189731898318993190031901319023190331904319053190631907319083190931910319113191231913319143191531916319173191831919319203192131922319233192431925319263192731928319293193031931319323193331934319353193631937319383193931940319413194231943319443194531946319473194831949319503195131952319533195431955319563195731958319593196031961319623196331964319653196631967319683196931970319713197231973319743197531976319773197831979319803198131982319833198431985319863198731988319893199031991319923199331994319953199631997319983199932000320013200232003320043200532006320073200832009320103201132012320133201432015320163201732018320193202032021320223202332024320253202632027320283202932030320313203232033320343203532036320373203832039320403204132042320433204432045320463204732048320493205032051320523205332054320553205632057320583205932060320613206232063320643206532066320673206832069320703207132072320733207432075320763207732078320793208032081320823208332084320853208632087320883208932090320913209232093320943209532096320973209832099321003210132102321033210432105321063210732108321093211032111321123211332114321153211632117321183211932120321213212232123321243212532126321273212832129321303213132132321333213432135321363213732138321393214032141321423214332144321453214632147321483214932150321513215232153321543215532156321573215832159321603216132162321633216432165321663216732168321693217032171321723217332174321753217632177321783217932180321813218232183321843218532186321873218832189321903219132192321933219432195321963219732198321993220032201322023220332204322053220632207322083220932210322113221232213322143221532216322173221832219322203222132222322233222432225322263222732228322293223032231322323223332234322353223632237322383223932240322413224232243322443224532246322473224832249322503225132252322533225432255322563225732258322593226032261322623226332264322653226632267322683226932270322713227232273322743227532276322773227832279322803228132282322833228432285322863228732288322893229032291322923229332294322953229632297322983229932300323013230232303323043230532306323073230832309323103231132312323133231432315323163231732318323193232032321323223232332324323253232632327323283232932330323313233232333323343233532336323373233832339323403234132342323433234432345323463234732348323493235032351323523235332354323553235632357323583235932360323613236232363323643236532366323673236832369323703237132372323733237432375323763237732378323793238032381323823238332384323853238632387323883238932390323913239232393323943239532396323973239832399324003240132402324033240432405324063240732408324093241032411324123241332414324153241632417324183241932420324213242232423324243242532426324273242832429324303243132432324333243432435324363243732438324393244032441324423244332444324453244632447324483244932450324513245232453324543245532456324573245832459324603246132462324633246432465324663246732468324693247032471324723247332474324753247632477324783247932480324813248232483324843248532486324873248832489324903249132492324933249432495324963249732498324993250032501325023250332504325053250632507325083250932510325113251232513325143251532516325173251832519325203252132522325233252432525325263252732528325293253032531325323253332534325353253632537325383253932540325413254232543325443254532546325473254832549325503255132552325533255432555325563255732558325593256032561325623256332564325653256632567325683256932570325713257232573325743257532576325773257832579325803258132582325833258432585325863258732588325893259032591325923259332594325953259632597325983259932600326013260232603326043260532606326073260832609326103261132612326133261432615326163261732618326193262032621326223262332624326253262632627326283262932630326313263232633326343263532636326373263832639326403264132642326433264432645326463264732648326493265032651326523265332654326553265632657326583265932660326613266232663326643266532666326673266832669326703267132672326733267432675326763267732678326793268032681326823268332684326853268632687326883268932690326913269232693326943269532696326973269832699327003270132702327033270432705327063270732708327093271032711327123271332714327153271632717327183271932720327213272232723327243272532726327273272832729327303273132732327333273432735327363273732738327393274032741327423274332744327453274632747327483274932750327513275232753327543275532756327573275832759327603276132762327633276432765327663276732768327693277032771327723277332774327753277632777327783277932780327813278232783327843278532786327873278832789327903279132792327933279432795327963279732798327993280032801328023280332804328053280632807328083280932810328113281232813328143281532816328173281832819328203282132822328233282432825328263282732828328293283032831328323283332834328353283632837328383283932840328413284232843328443284532846328473284832849328503285132852328533285432855328563285732858328593286032861328623286332864328653286632867328683286932870328713287232873328743287532876328773287832879328803288132882328833288432885328863288732888328893289032891328923289332894328953289632897328983289932900329013290232903329043290532906329073290832909329103291132912329133291432915329163291732918329193292032921329223292332924329253292632927329283292932930329313293232933329343293532936329373293832939329403294132942329433294432945329463294732948329493295032951329523295332954329553295632957329583295932960329613296232963329643296532966329673296832969329703297132972329733297432975329763297732978329793298032981329823298332984329853298632987329883298932990329913299232993329943299532996329973299832999330003300133002330033300433005330063300733008330093301033011330123301333014330153301633017330183301933020330213302233023330243302533026330273302833029330303303133032330333303433035330363303733038330393304033041330423304333044330453304633047330483304933050330513305233053330543305533056330573305833059330603306133062330633306433065330663306733068330693307033071330723307333074330753307633077330783307933080330813308233083330843308533086330873308833089330903309133092330933309433095330963309733098330993310033101331023310333104331053310633107331083310933110331113311233113331143311533116331173311833119331203312133122331233312433125331263312733128331293313033131331323313333134331353313633137331383313933140331413314233143331443314533146331473314833149331503315133152331533315433155331563315733158331593316033161331623316333164331653316633167331683316933170331713317233173331743317533176331773317833179331803318133182331833318433185331863318733188331893319033191331923319333194331953319633197331983319933200332013320233203332043320533206332073320833209332103321133212332133321433215332163321733218332193322033221332223322333224332253322633227332283322933230332313323233233332343323533236332373323833239332403324133242332433324433245332463324733248332493325033251332523325333254332553325633257332583325933260332613326233263332643326533266332673326833269332703327133272332733327433275332763327733278332793328033281332823328333284332853328633287332883328933290332913329233293332943329533296332973329833299333003330133302333033330433305333063330733308333093331033311333123331333314333153331633317333183331933320333213332233323333243332533326333273332833329333303333133332333333333433335333363333733338333393334033341333423334333344333453334633347333483334933350333513335233353333543335533356333573335833359333603336133362333633336433365333663336733368333693337033371333723337333374333753337633377333783337933380333813338233383333843338533386333873338833389333903339133392333933339433395333963339733398333993340033401334023340333404334053340633407334083340933410334113341233413334143341533416334173341833419334203342133422334233342433425334263342733428334293343033431334323343333434334353343633437334383343933440334413344233443334443344533446334473344833449334503345133452334533345433455334563345733458334593346033461334623346333464334653346633467334683346933470334713347233473334743347533476334773347833479334803348133482334833348433485334863348733488334893349033491334923349333494334953349633497334983349933500335013350233503335043350533506335073350833509335103351133512335133351433515335163351733518335193352033521335223352333524335253352633527335283352933530335313353233533335343353533536335373353833539335403354133542335433354433545335463354733548335493355033551335523355333554335553355633557335583355933560335613356233563335643356533566335673356833569335703357133572335733357433575335763357733578335793358033581335823358333584335853358633587335883358933590335913359233593335943359533596335973359833599336003360133602336033360433605336063360733608336093361033611336123361333614336153361633617336183361933620336213362233623336243362533626336273362833629336303363133632336333363433635336363363733638336393364033641336423364333644336453364633647336483364933650336513365233653336543365533656336573365833659336603366133662336633366433665336663366733668336693367033671336723367333674336753367633677336783367933680336813368233683336843368533686336873368833689336903369133692336933369433695336963369733698336993370033701337023370333704337053370633707337083370933710337113371233713337143371533716337173371833719337203372133722337233372433725337263372733728337293373033731337323373333734337353373633737337383373933740337413374233743337443374533746337473374833749337503375133752337533375433755337563375733758337593376033761337623376333764337653376633767337683376933770337713377233773337743377533776337773377833779337803378133782337833378433785337863378733788337893379033791337923379333794337953379633797337983379933800338013380233803338043380533806338073380833809338103381133812338133381433815338163381733818338193382033821338223382333824338253382633827338283382933830338313383233833338343383533836338373383833839338403384133842338433384433845338463384733848338493385033851338523385333854338553385633857338583385933860338613386233863338643386533866338673386833869338703387133872338733387433875338763387733878338793388033881338823388333884338853388633887338883388933890338913389233893338943389533896338973389833899339003390133902339033390433905339063390733908339093391033911339123391333914339153391633917339183391933920339213392233923339243392533926339273392833929339303393133932339333393433935339363393733938339393394033941339423394333944339453394633947339483394933950339513395233953339543395533956339573395833959339603396133962339633396433965339663396733968339693397033971339723397333974339753397633977339783397933980339813398233983339843398533986339873398833989339903399133992339933399433995339963399733998339993400034001340023400334004340053400634007340083400934010340113401234013340143401534016340173401834019340203402134022340233402434025340263402734028340293403034031340323403334034340353403634037340383403934040340413404234043340443404534046340473404834049340503405134052340533405434055340563405734058340593406034061340623406334064340653406634067340683406934070340713407234073340743407534076340773407834079340803408134082340833408434085340863408734088340893409034091340923409334094340953409634097340983409934100341013410234103341043410534106341073410834109341103411134112341133411434115341163411734118341193412034121341223412334124341253412634127341283412934130341313413234133341343413534136341373413834139341403414134142341433414434145341463414734148341493415034151341523415334154341553415634157341583415934160341613416234163341643416534166341673416834169341703417134172341733417434175341763417734178341793418034181341823418334184341853418634187341883418934190341913419234193341943419534196341973419834199342003420134202342033420434205342063420734208342093421034211342123421334214342153421634217342183421934220342213422234223342243422534226342273422834229342303423134232342333423434235342363423734238342393424034241342423424334244342453424634247342483424934250342513425234253342543425534256342573425834259342603426134262342633426434265342663426734268342693427034271342723427334274342753427634277342783427934280342813428234283342843428534286342873428834289342903429134292342933429434295342963429734298342993430034301343023430334304343053430634307343083430934310343113431234313343143431534316343173431834319343203432134322343233432434325343263432734328343293433034331343323433334334343353433634337343383433934340343413434234343343443434534346343473434834349343503435134352343533435434355343563435734358343593436034361343623436334364343653436634367343683436934370343713437234373343743437534376343773437834379343803438134382343833438434385343863438734388343893439034391343923439334394343953439634397343983439934400344013440234403344043440534406344073440834409344103441134412344133441434415344163441734418344193442034421344223442334424344253442634427344283442934430344313443234433344343443534436344373443834439344403444134442344433444434445344463444734448344493445034451344523445334454344553445634457344583445934460344613446234463344643446534466344673446834469344703447134472344733447434475344763447734478344793448034481344823448334484344853448634487344883448934490344913449234493344943449534496344973449834499345003450134502345033450434505345063450734508345093451034511345123451334514345153451634517345183451934520345213452234523345243452534526345273452834529345303453134532345333453434535345363453734538345393454034541345423454334544345453454634547345483454934550345513455234553345543455534556345573455834559345603456134562345633456434565345663456734568345693457034571345723457334574345753457634577345783457934580345813458234583345843458534586345873458834589345903459134592345933459434595345963459734598345993460034601346023460334604346053460634607346083460934610346113461234613346143461534616346173461834619346203462134622346233462434625346263462734628346293463034631346323463334634346353463634637346383463934640346413464234643346443464534646346473464834649346503465134652346533465434655346563465734658346593466034661346623466334664346653466634667346683466934670346713467234673346743467534676346773467834679346803468134682346833468434685346863468734688346893469034691346923469334694346953469634697346983469934700347013470234703347043470534706347073470834709347103471134712347133471434715347163471734718347193472034721347223472334724347253472634727347283472934730347313473234733347343473534736347373473834739347403474134742347433474434745347463474734748347493475034751347523475334754347553475634757347583475934760347613476234763347643476534766347673476834769347703477134772347733477434775347763477734778347793478034781347823478334784347853478634787347883478934790347913479234793347943479534796347973479834799348003480134802348033480434805348063480734808348093481034811348123481334814348153481634817348183481934820348213482234823348243482534826348273482834829348303483134832348333483434835348363483734838348393484034841348423484334844348453484634847348483484934850348513485234853348543485534856348573485834859348603486134862348633486434865348663486734868348693487034871348723487334874348753487634877348783487934880348813488234883348843488534886348873488834889348903489134892348933489434895348963489734898348993490034901349023490334904349053490634907349083490934910349113491234913349143491534916349173491834919349203492134922349233492434925349263492734928349293493034931349323493334934349353493634937349383493934940349413494234943349443494534946349473494834949349503495134952349533495434955349563495734958349593496034961349623496334964349653496634967349683496934970349713497234973349743497534976349773497834979349803498134982349833498434985349863498734988349893499034991349923499334994349953499634997349983499935000350013500235003350043500535006350073500835009350103501135012350133501435015350163501735018350193502035021350223502335024350253502635027350283502935030350313503235033350343503535036350373503835039350403504135042350433504435045350463504735048350493505035051350523505335054350553505635057350583505935060350613506235063350643506535066350673506835069350703507135072350733507435075350763507735078350793508035081350823508335084350853508635087350883508935090350913509235093350943509535096350973509835099351003510135102351033510435105351063510735108351093511035111351123511335114351153511635117351183511935120351213512235123351243512535126351273512835129351303513135132351333513435135351363513735138351393514035141351423514335144351453514635147351483514935150351513515235153351543515535156351573515835159351603516135162351633516435165351663516735168351693517035171351723517335174351753517635177351783517935180351813518235183351843518535186351873518835189351903519135192351933519435195351963519735198351993520035201352023520335204352053520635207352083520935210352113521235213352143521535216352173521835219352203522135222352233522435225352263522735228352293523035231352323523335234352353523635237352383523935240352413524235243352443524535246352473524835249352503525135252352533525435255352563525735258352593526035261352623526335264352653526635267352683526935270352713527235273352743527535276352773527835279352803528135282352833528435285352863528735288352893529035291352923529335294352953529635297352983529935300353013530235303353043530535306353073530835309353103531135312353133531435315353163531735318353193532035321353223532335324353253532635327353283532935330353313533235333353343533535336353373533835339353403534135342353433534435345353463534735348353493535035351353523535335354353553535635357353583535935360353613536235363353643536535366353673536835369353703537135372353733537435375353763537735378353793538035381353823538335384353853538635387353883538935390353913539235393353943539535396353973539835399354003540135402354033540435405354063540735408354093541035411354123541335414354153541635417354183541935420354213542235423354243542535426354273542835429354303543135432354333543435435354363543735438354393544035441354423544335444354453544635447354483544935450354513545235453354543545535456354573545835459354603546135462354633546435465354663546735468354693547035471354723547335474354753547635477354783547935480354813548235483354843548535486354873548835489354903549135492354933549435495354963549735498354993550035501355023550335504355053550635507355083550935510355113551235513355143551535516355173551835519355203552135522355233552435525355263552735528355293553035531355323553335534355353553635537355383553935540355413554235543355443554535546355473554835549355503555135552355533555435555355563555735558355593556035561355623556335564355653556635567355683556935570355713557235573355743557535576355773557835579355803558135582355833558435585355863558735588355893559035591355923559335594355953559635597355983559935600356013560235603356043560535606356073560835609356103561135612356133561435615356163561735618356193562035621356223562335624356253562635627356283562935630356313563235633356343563535636356373563835639356403564135642356433564435645356463564735648356493565035651356523565335654356553565635657356583565935660356613566235663356643566535666356673566835669356703567135672356733567435675356763567735678356793568035681356823568335684356853568635687356883568935690356913569235693356943569535696356973569835699357003570135702357033570435705357063570735708357093571035711357123571335714357153571635717357183571935720357213572235723357243572535726357273572835729357303573135732357333573435735357363573735738357393574035741357423574335744357453574635747357483574935750357513575235753357543575535756357573575835759357603576135762357633576435765357663576735768357693577035771357723577335774357753577635777357783577935780357813578235783357843578535786357873578835789357903579135792357933579435795357963579735798357993580035801358023580335804358053580635807358083580935810358113581235813358143581535816358173581835819358203582135822358233582435825358263582735828358293583035831358323583335834358353583635837358383583935840358413584235843358443584535846358473584835849358503585135852358533585435855358563585735858358593586035861358623586335864358653586635867358683586935870358713587235873358743587535876358773587835879358803588135882358833588435885358863588735888358893589035891358923589335894358953589635897358983589935900359013590235903359043590535906359073590835909359103591135912359133591435915359163591735918359193592035921359223592335924359253592635927359283592935930359313593235933359343593535936359373593835939359403594135942359433594435945359463594735948359493595035951359523595335954359553595635957359583595935960359613596235963359643596535966359673596835969359703597135972359733597435975359763597735978359793598035981359823598335984359853598635987359883598935990359913599235993359943599535996359973599835999360003600136002360033600436005360063600736008360093601036011360123601336014360153601636017360183601936020360213602236023360243602536026360273602836029360303603136032360333603436035360363603736038360393604036041360423604336044360453604636047360483604936050360513605236053360543605536056360573605836059360603606136062360633606436065360663606736068360693607036071360723607336074360753607636077360783607936080360813608236083360843608536086360873608836089360903609136092360933609436095360963609736098360993610036101361023610336104361053610636107361083610936110361113611236113361143611536116361173611836119361203612136122361233612436125361263612736128361293613036131361323613336134361353613636137361383613936140361413614236143361443614536146361473614836149361503615136152361533615436155361563615736158361593616036161361623616336164361653616636167361683616936170361713617236173361743617536176361773617836179361803618136182361833618436185361863618736188361893619036191361923619336194361953619636197361983619936200362013620236203362043620536206362073620836209362103621136212362133621436215362163621736218362193622036221362223622336224362253622636227362283622936230362313623236233362343623536236362373623836239362403624136242362433624436245362463624736248362493625036251362523625336254362553625636257362583625936260362613626236263362643626536266362673626836269362703627136272362733627436275362763627736278362793628036281362823628336284362853628636287362883628936290362913629236293362943629536296362973629836299363003630136302363033630436305363063630736308363093631036311363123631336314363153631636317363183631936320363213632236323363243632536326363273632836329363303633136332363333633436335363363633736338363393634036341363423634336344363453634636347363483634936350363513635236353363543635536356363573635836359363603636136362363633636436365363663636736368363693637036371363723637336374363753637636377363783637936380363813638236383363843638536386363873638836389363903639136392363933639436395363963639736398363993640036401364023640336404364053640636407364083640936410364113641236413364143641536416364173641836419364203642136422364233642436425364263642736428364293643036431364323643336434364353643636437364383643936440364413644236443364443644536446364473644836449364503645136452364533645436455364563645736458364593646036461364623646336464364653646636467364683646936470364713647236473364743647536476364773647836479364803648136482364833648436485364863648736488364893649036491364923649336494364953649636497364983649936500365013650236503365043650536506365073650836509365103651136512365133651436515365163651736518365193652036521365223652336524365253652636527365283652936530365313653236533365343653536536365373653836539365403654136542365433654436545365463654736548365493655036551365523655336554365553655636557365583655936560365613656236563365643656536566365673656836569365703657136572365733657436575365763657736578365793658036581365823658336584365853658636587365883658936590365913659236593365943659536596365973659836599366003660136602366033660436605366063660736608366093661036611366123661336614366153661636617366183661936620366213662236623366243662536626366273662836629366303663136632366333663436635366363663736638366393664036641366423664336644366453664636647366483664936650366513665236653366543665536656366573665836659366603666136662366633666436665366663666736668366693667036671366723667336674366753667636677366783667936680366813668236683366843668536686366873668836689366903669136692366933669436695366963669736698366993670036701367023670336704367053670636707367083670936710367113671236713367143671536716367173671836719367203672136722367233672436725367263672736728367293673036731367323673336734367353673636737367383673936740367413674236743367443674536746367473674836749367503675136752367533675436755367563675736758367593676036761367623676336764367653676636767367683676936770367713677236773367743677536776367773677836779367803678136782367833678436785367863678736788367893679036791367923679336794367953679636797367983679936800368013680236803368043680536806368073680836809368103681136812368133681436815368163681736818368193682036821368223682336824368253682636827368283682936830368313683236833368343683536836368373683836839368403684136842368433684436845368463684736848368493685036851368523685336854368553685636857368583685936860368613686236863368643686536866368673686836869368703687136872368733687436875368763687736878368793688036881368823688336884368853688636887368883688936890368913689236893368943689536896368973689836899369003690136902369033690436905369063690736908369093691036911369123691336914369153691636917369183691936920369213692236923369243692536926369273692836929369303693136932369333693436935369363693736938369393694036941369423694336944369453694636947369483694936950369513695236953369543695536956369573695836959369603696136962369633696436965369663696736968369693697036971369723697336974369753697636977369783697936980369813698236983369843698536986369873698836989369903699136992369933699436995369963699736998369993700037001370023700337004370053700637007370083700937010370113701237013370143701537016370173701837019370203702137022370233702437025370263702737028370293703037031370323703337034370353703637037370383703937040370413704237043370443704537046370473704837049370503705137052370533705437055370563705737058370593706037061370623706337064370653706637067370683706937070370713707237073370743707537076370773707837079370803708137082370833708437085370863708737088370893709037091370923709337094370953709637097370983709937100371013710237103371043710537106371073710837109371103711137112371133711437115371163711737118371193712037121371223712337124371253712637127371283712937130371313713237133371343713537136371373713837139371403714137142371433714437145371463714737148371493715037151371523715337154371553715637157371583715937160371613716237163371643716537166371673716837169371703717137172371733717437175371763717737178371793718037181371823718337184371853718637187371883718937190371913719237193371943719537196371973719837199372003720137202372033720437205372063720737208372093721037211372123721337214372153721637217372183721937220372213722237223372243722537226372273722837229372303723137232372333723437235372363723737238372393724037241372423724337244372453724637247372483724937250372513725237253372543725537256372573725837259372603726137262372633726437265372663726737268372693727037271372723727337274372753727637277372783727937280372813728237283372843728537286372873728837289372903729137292372933729437295372963729737298372993730037301373023730337304373053730637307373083730937310373113731237313373143731537316373173731837319373203732137322373233732437325373263732737328373293733037331373323733337334373353733637337373383733937340373413734237343373443734537346373473734837349373503735137352373533735437355373563735737358373593736037361373623736337364373653736637367373683736937370373713737237373373743737537376373773737837379373803738137382373833738437385373863738737388373893739037391373923739337394373953739637397373983739937400374013740237403374043740537406374073740837409374103741137412374133741437415374163741737418374193742037421374223742337424374253742637427374283742937430374313743237433374343743537436374373743837439374403744137442374433744437445374463744737448374493745037451374523745337454374553745637457374583745937460374613746237463374643746537466374673746837469374703747137472374733747437475374763747737478374793748037481374823748337484374853748637487374883748937490374913749237493374943749537496374973749837499375003750137502375033750437505375063750737508375093751037511375123751337514375153751637517375183751937520375213752237523375243752537526375273752837529375303753137532375333753437535375363753737538375393754037541375423754337544375453754637547375483754937550375513755237553375543755537556375573755837559375603756137562375633756437565375663756737568375693757037571375723757337574375753757637577375783757937580375813758237583375843758537586375873758837589375903759137592375933759437595375963759737598375993760037601376023760337604376053760637607376083760937610376113761237613376143761537616376173761837619376203762137622376233762437625376263762737628376293763037631376323763337634376353763637637376383763937640376413764237643376443764537646376473764837649376503765137652376533765437655376563765737658376593766037661376623766337664376653766637667376683766937670376713767237673376743767537676376773767837679376803768137682376833768437685376863768737688376893769037691376923769337694376953769637697376983769937700377013770237703377043770537706377073770837709377103771137712377133771437715377163771737718377193772037721377223772337724377253772637727377283772937730377313773237733377343773537736377373773837739377403774137742377433774437745377463774737748377493775037751377523775337754377553775637757377583775937760377613776237763377643776537766377673776837769377703777137772377733777437775377763777737778377793778037781377823778337784377853778637787377883778937790377913779237793377943779537796377973779837799378003780137802378033780437805378063780737808378093781037811378123781337814378153781637817378183781937820378213782237823378243782537826378273782837829378303783137832378333783437835378363783737838378393784037841378423784337844378453784637847378483784937850378513785237853378543785537856378573785837859378603786137862378633786437865378663786737868378693787037871378723787337874378753787637877378783787937880378813788237883378843788537886378873788837889378903789137892378933789437895378963789737898378993790037901379023790337904379053790637907379083790937910379113791237913379143791537916379173791837919379203792137922379233792437925379263792737928379293793037931379323793337934379353793637937379383793937940379413794237943379443794537946379473794837949379503795137952379533795437955379563795737958379593796037961379623796337964379653796637967379683796937970379713797237973379743797537976379773797837979379803798137982379833798437985379863798737988379893799037991379923799337994379953799637997379983799938000380013800238003380043800538006380073800838009380103801138012380133801438015380163801738018380193802038021380223802338024380253802638027380283802938030380313803238033380343803538036380373803838039380403804138042380433804438045380463804738048380493805038051380523805338054380553805638057380583805938060380613806238063380643806538066380673806838069380703807138072380733807438075380763807738078380793808038081380823808338084380853808638087380883808938090380913809238093380943809538096380973809838099381003810138102381033810438105381063810738108381093811038111381123811338114381153811638117381183811938120381213812238123381243812538126381273812838129381303813138132381333813438135381363813738138381393814038141381423814338144381453814638147381483814938150381513815238153381543815538156381573815838159381603816138162381633816438165381663816738168381693817038171381723817338174381753817638177381783817938180381813818238183381843818538186381873818838189381903819138192381933819438195381963819738198381993820038201382023820338204382053820638207382083820938210382113821238213382143821538216382173821838219382203822138222382233822438225382263822738228382293823038231382323823338234382353823638237382383823938240382413824238243382443824538246382473824838249382503825138252382533825438255382563825738258382593826038261382623826338264382653826638267382683826938270382713827238273382743827538276382773827838279382803828138282382833828438285382863828738288382893829038291382923829338294382953829638297382983829938300383013830238303383043830538306383073830838309383103831138312383133831438315383163831738318383193832038321383223832338324383253832638327383283832938330383313833238333383343833538336383373833838339383403834138342383433834438345383463834738348383493835038351383523835338354383553835638357383583835938360383613836238363383643836538366383673836838369383703837138372383733837438375383763837738378383793838038381383823838338384383853838638387383883838938390383913839238393383943839538396383973839838399384003840138402384033840438405384063840738408384093841038411384123841338414384153841638417384183841938420384213842238423384243842538426384273842838429384303843138432384333843438435384363843738438384393844038441384423844338444384453844638447384483844938450384513845238453384543845538456384573845838459384603846138462384633846438465384663846738468384693847038471384723847338474384753847638477384783847938480384813848238483384843848538486384873848838489384903849138492384933849438495384963849738498384993850038501385023850338504385053850638507385083850938510385113851238513385143851538516385173851838519385203852138522385233852438525385263852738528385293853038531385323853338534385353853638537385383853938540385413854238543385443854538546385473854838549385503855138552385533855438555385563855738558385593856038561385623856338564385653856638567385683856938570385713857238573385743857538576385773857838579385803858138582385833858438585385863858738588385893859038591385923859338594385953859638597385983859938600386013860238603386043860538606386073860838609386103861138612386133861438615386163861738618386193862038621386223862338624386253862638627386283862938630386313863238633386343863538636386373863838639386403864138642386433864438645386463864738648386493865038651386523865338654386553865638657386583865938660386613866238663386643866538666386673866838669386703867138672386733867438675386763867738678386793868038681386823868338684386853868638687386883868938690386913869238693386943869538696386973869838699387003870138702387033870438705387063870738708387093871038711387123871338714387153871638717387183871938720387213872238723387243872538726387273872838729387303873138732387333873438735387363873738738387393874038741387423874338744387453874638747387483874938750387513875238753387543875538756387573875838759387603876138762387633876438765387663876738768387693877038771387723877338774387753877638777387783877938780387813878238783387843878538786387873878838789387903879138792387933879438795387963879738798387993880038801388023880338804388053880638807388083880938810388113881238813388143881538816388173881838819388203882138822388233882438825388263882738828388293883038831388323883338834388353883638837388383883938840388413884238843388443884538846388473884838849388503885138852388533885438855388563885738858388593886038861388623886338864388653886638867388683886938870388713887238873388743887538876388773887838879388803888138882388833888438885388863888738888388893889038891388923889338894388953889638897388983889938900389013890238903389043890538906389073890838909389103891138912389133891438915389163891738918389193892038921389223892338924389253892638927389283892938930389313893238933389343893538936389373893838939389403894138942389433894438945389463894738948389493895038951389523895338954389553895638957389583895938960389613896238963389643896538966389673896838969389703897138972389733897438975389763897738978389793898038981389823898338984389853898638987389883898938990389913899238993389943899538996389973899838999390003900139002390033900439005390063900739008390093901039011390123901339014390153901639017390183901939020390213902239023390243902539026390273902839029390303903139032390333903439035390363903739038390393904039041390423904339044390453904639047390483904939050390513905239053390543905539056390573905839059390603906139062390633906439065390663906739068390693907039071390723907339074390753907639077390783907939080390813908239083390843908539086390873908839089390903909139092390933909439095390963909739098390993910039101391023910339104391053910639107391083910939110391113911239113391143911539116391173911839119391203912139122391233912439125391263912739128391293913039131391323913339134391353913639137391383913939140391413914239143391443914539146391473914839149391503915139152391533915439155391563915739158391593916039161391623916339164391653916639167391683916939170391713917239173391743917539176391773917839179391803918139182391833918439185391863918739188391893919039191391923919339194391953919639197391983919939200392013920239203392043920539206392073920839209392103921139212392133921439215392163921739218392193922039221392223922339224392253922639227392283922939230392313923239233392343923539236392373923839239392403924139242392433924439245392463924739248392493925039251392523925339254392553925639257392583925939260392613926239263392643926539266392673926839269392703927139272392733927439275392763927739278392793928039281392823928339284392853928639287392883928939290392913929239293392943929539296392973929839299393003930139302393033930439305393063930739308393093931039311393123931339314393153931639317393183931939320393213932239323393243932539326393273932839329393303933139332393333933439335393363933739338393393934039341393423934339344393453934639347393483934939350393513935239353393543935539356393573935839359393603936139362393633936439365393663936739368393693937039371393723937339374393753937639377393783937939380393813938239383393843938539386393873938839389393903939139392393933939439395393963939739398393993940039401394023940339404394053940639407394083940939410394113941239413394143941539416394173941839419394203942139422394233942439425394263942739428394293943039431394323943339434394353943639437394383943939440394413944239443394443944539446394473944839449394503945139452394533945439455394563945739458394593946039461394623946339464394653946639467394683946939470394713947239473394743947539476394773947839479394803948139482394833948439485394863948739488394893949039491394923949339494394953949639497394983949939500395013950239503395043950539506395073950839509395103951139512395133951439515395163951739518395193952039521395223952339524395253952639527395283952939530395313953239533395343953539536395373953839539395403954139542395433954439545395463954739548395493955039551395523955339554395553955639557395583955939560395613956239563395643956539566395673956839569395703957139572395733957439575395763957739578395793958039581395823958339584395853958639587395883958939590395913959239593395943959539596395973959839599396003960139602396033960439605396063960739608396093961039611396123961339614396153961639617396183961939620396213962239623396243962539626396273962839629396303963139632396333963439635396363963739638396393964039641396423964339644396453964639647396483964939650396513965239653396543965539656396573965839659396603966139662396633966439665396663966739668396693967039671396723967339674396753967639677396783967939680396813968239683396843968539686396873968839689396903969139692396933969439695396963969739698396993970039701397023970339704397053970639707397083970939710397113971239713397143971539716397173971839719397203972139722397233972439725397263972739728397293973039731397323973339734397353973639737397383973939740397413974239743397443974539746397473974839749397503975139752397533975439755397563975739758397593976039761397623976339764397653976639767397683976939770397713977239773397743977539776397773977839779397803978139782397833978439785397863978739788397893979039791397923979339794397953979639797397983979939800398013980239803398043980539806398073980839809398103981139812398133981439815398163981739818398193982039821398223982339824398253982639827398283982939830398313983239833398343983539836398373983839839398403984139842398433984439845398463984739848398493985039851398523985339854398553985639857398583985939860398613986239863398643986539866398673986839869398703987139872398733987439875398763987739878398793988039881398823988339884398853988639887398883988939890398913989239893398943989539896398973989839899399003990139902399033990439905399063990739908399093991039911399123991339914399153991639917399183991939920399213992239923399243992539926399273992839929399303993139932399333993439935399363993739938399393994039941399423994339944399453994639947399483994939950399513995239953399543995539956399573995839959399603996139962399633996439965399663996739968399693997039971399723997339974399753997639977399783997939980399813998239983399843998539986399873998839989399903999139992399933999439995399963999739998399994000040001400024000340004400054000640007400084000940010400114001240013400144001540016400174001840019400204002140022400234002440025400264002740028400294003040031400324003340034400354003640037400384003940040400414004240043400444004540046400474004840049400504005140052400534005440055400564005740058400594006040061400624006340064400654006640067400684006940070400714007240073400744007540076400774007840079400804008140082400834008440085400864008740088400894009040091400924009340094400954009640097400984009940100401014010240103401044010540106401074010840109401104011140112401134011440115401164011740118401194012040121401224012340124401254012640127401284012940130401314013240133401344013540136401374013840139401404014140142401434014440145401464014740148401494015040151401524015340154401554015640157401584015940160401614016240163401644016540166401674016840169401704017140172401734017440175401764017740178401794018040181401824018340184401854018640187401884018940190401914019240193401944019540196401974019840199402004020140202402034020440205402064020740208402094021040211402124021340214402154021640217402184021940220402214022240223402244022540226402274022840229402304023140232402334023440235402364023740238402394024040241402424024340244402454024640247402484024940250402514025240253402544025540256402574025840259402604026140262402634026440265402664026740268402694027040271402724027340274402754027640277402784027940280402814028240283402844028540286402874028840289402904029140292402934029440295402964029740298402994030040301403024030340304403054030640307403084030940310403114031240313403144031540316403174031840319403204032140322403234032440325403264032740328403294033040331403324033340334403354033640337403384033940340403414034240343403444034540346403474034840349403504035140352403534035440355403564035740358403594036040361403624036340364403654036640367403684036940370403714037240373403744037540376403774037840379403804038140382403834038440385403864038740388403894039040391403924039340394403954039640397403984039940400404014040240403404044040540406404074040840409404104041140412404134041440415404164041740418404194042040421404224042340424404254042640427404284042940430404314043240433404344043540436404374043840439404404044140442404434044440445404464044740448404494045040451404524045340454404554045640457404584045940460404614046240463404644046540466404674046840469404704047140472404734047440475404764047740478404794048040481404824048340484404854048640487404884048940490404914049240493404944049540496404974049840499405004050140502405034050440505405064050740508405094051040511405124051340514405154051640517405184051940520405214052240523405244052540526405274052840529405304053140532405334053440535405364053740538405394054040541405424054340544405454054640547405484054940550405514055240553405544055540556405574055840559405604056140562405634056440565405664056740568405694057040571405724057340574405754057640577405784057940580405814058240583405844058540586405874058840589405904059140592405934059440595405964059740598405994060040601406024060340604406054060640607406084060940610406114061240613406144061540616406174061840619406204062140622406234062440625406264062740628406294063040631406324063340634406354063640637406384063940640406414064240643406444064540646406474064840649406504065140652406534065440655406564065740658406594066040661406624066340664406654066640667406684066940670406714067240673406744067540676406774067840679406804068140682406834068440685406864068740688406894069040691406924069340694406954069640697406984069940700407014070240703407044070540706407074070840709407104071140712407134071440715407164071740718407194072040721407224072340724407254072640727407284072940730407314073240733407344073540736407374073840739407404074140742407434074440745407464074740748407494075040751407524075340754407554075640757407584075940760407614076240763407644076540766407674076840769407704077140772407734077440775407764077740778407794078040781407824078340784407854078640787407884078940790407914079240793407944079540796407974079840799408004080140802408034080440805408064080740808408094081040811408124081340814408154081640817408184081940820408214082240823408244082540826408274082840829408304083140832408334083440835408364083740838408394084040841408424084340844408454084640847408484084940850408514085240853408544085540856408574085840859408604086140862408634086440865408664086740868408694087040871408724087340874408754087640877408784087940880408814088240883408844088540886408874088840889408904089140892408934089440895408964089740898408994090040901409024090340904409054090640907409084090940910409114091240913409144091540916409174091840919409204092140922409234092440925409264092740928409294093040931409324093340934409354093640937409384093940940409414094240943409444094540946409474094840949409504095140952409534095440955409564095740958409594096040961409624096340964409654096640967409684096940970409714097240973409744097540976409774097840979409804098140982409834098440985409864098740988409894099040991409924099340994409954099640997409984099941000410014100241003410044100541006410074100841009410104101141012410134101441015410164101741018410194102041021410224102341024410254102641027410284102941030410314103241033410344103541036410374103841039410404104141042410434104441045410464104741048410494105041051410524105341054410554105641057410584105941060410614106241063410644106541066410674106841069410704107141072410734107441075410764107741078410794108041081410824108341084410854108641087410884108941090410914109241093410944109541096410974109841099411004110141102411034110441105411064110741108411094111041111411124111341114411154111641117411184111941120411214112241123411244112541126411274112841129411304113141132411334113441135411364113741138411394114041141411424114341144411454114641147411484114941150411514115241153411544115541156411574115841159411604116141162411634116441165411664116741168411694117041171411724117341174411754117641177411784117941180411814118241183411844118541186411874118841189411904119141192411934119441195411964119741198411994120041201412024120341204412054120641207412084120941210412114121241213412144121541216412174121841219412204122141222412234122441225412264122741228412294123041231412324123341234412354123641237412384123941240412414124241243412444124541246412474124841249412504125141252412534125441255412564125741258412594126041261412624126341264412654126641267412684126941270412714127241273412744127541276412774127841279412804128141282412834128441285412864128741288412894129041291412924129341294412954129641297412984129941300413014130241303413044130541306413074130841309413104131141312413134131441315413164131741318413194132041321413224132341324413254132641327413284132941330413314133241333413344133541336413374133841339413404134141342413434134441345413464134741348413494135041351413524135341354413554135641357413584135941360413614136241363413644136541366413674136841369413704137141372413734137441375413764137741378413794138041381413824138341384413854138641387413884138941390413914139241393413944139541396413974139841399414004140141402414034140441405414064140741408414094141041411414124141341414414154141641417414184141941420414214142241423414244142541426414274142841429414304143141432414334143441435414364143741438414394144041441414424144341444414454144641447414484144941450414514145241453414544145541456414574145841459414604146141462414634146441465414664146741468414694147041471414724147341474414754147641477414784147941480414814148241483414844148541486414874148841489414904149141492414934149441495414964149741498414994150041501415024150341504415054150641507415084150941510415114151241513415144151541516415174151841519415204152141522415234152441525415264152741528415294153041531415324153341534415354153641537415384153941540415414154241543415444154541546415474154841549415504155141552415534155441555415564155741558415594156041561415624156341564415654156641567415684156941570415714157241573415744157541576415774157841579415804158141582415834158441585415864158741588415894159041591415924159341594415954159641597415984159941600416014160241603416044160541606416074160841609416104161141612416134161441615416164161741618416194162041621416224162341624416254162641627416284162941630416314163241633416344163541636416374163841639416404164141642416434164441645416464164741648416494165041651416524165341654416554165641657416584165941660416614166241663416644166541666416674166841669416704167141672416734167441675416764167741678416794168041681416824168341684416854168641687416884168941690416914169241693416944169541696416974169841699417004170141702417034170441705417064170741708417094171041711417124171341714417154171641717417184171941720417214172241723417244172541726417274172841729417304173141732417334173441735417364173741738417394174041741417424174341744417454174641747417484174941750417514175241753417544175541756417574175841759417604176141762417634176441765417664176741768417694177041771417724177341774417754177641777417784177941780417814178241783417844178541786417874178841789417904179141792417934179441795417964179741798417994180041801418024180341804418054180641807418084180941810418114181241813418144181541816418174181841819418204182141822418234182441825418264182741828418294183041831418324183341834418354183641837418384183941840418414184241843418444184541846418474184841849418504185141852418534185441855418564185741858418594186041861418624186341864418654186641867418684186941870418714187241873418744187541876418774187841879418804188141882418834188441885418864188741888418894189041891418924189341894418954189641897418984189941900419014190241903419044190541906419074190841909419104191141912419134191441915419164191741918419194192041921419224192341924419254192641927419284192941930419314193241933419344193541936419374193841939419404194141942419434194441945419464194741948419494195041951419524195341954419554195641957419584195941960419614196241963419644196541966419674196841969419704197141972419734197441975419764197741978419794198041981419824198341984419854198641987419884198941990419914199241993419944199541996419974199841999420004200142002420034200442005420064200742008420094201042011420124201342014420154201642017420184201942020420214202242023420244202542026420274202842029420304203142032420334203442035420364203742038420394204042041420424204342044420454204642047420484204942050420514205242053420544205542056420574205842059420604206142062420634206442065420664206742068420694207042071420724207342074420754207642077420784207942080420814208242083420844208542086420874208842089420904209142092420934209442095420964209742098420994210042101421024210342104421054210642107421084210942110421114211242113421144211542116421174211842119421204212142122421234212442125421264212742128421294213042131421324213342134421354213642137421384213942140421414214242143421444214542146421474214842149421504215142152421534215442155421564215742158421594216042161421624216342164421654216642167421684216942170421714217242173421744217542176421774217842179421804218142182421834218442185421864218742188421894219042191421924219342194421954219642197421984219942200422014220242203422044220542206422074220842209422104221142212422134221442215422164221742218422194222042221422224222342224422254222642227422284222942230422314223242233422344223542236422374223842239422404224142242422434224442245422464224742248422494225042251422524225342254422554225642257422584225942260422614226242263422644226542266422674226842269422704227142272422734227442275422764227742278422794228042281422824228342284422854228642287422884228942290422914229242293422944229542296422974229842299423004230142302423034230442305423064230742308423094231042311423124231342314423154231642317423184231942320423214232242323423244232542326423274232842329423304233142332423334233442335423364233742338423394234042341423424234342344423454234642347423484234942350423514235242353423544235542356423574235842359423604236142362423634236442365423664236742368423694237042371423724237342374423754237642377423784237942380423814238242383423844238542386423874238842389423904239142392423934239442395423964239742398423994240042401424024240342404424054240642407424084240942410424114241242413424144241542416424174241842419424204242142422424234242442425424264242742428424294243042431424324243342434424354243642437424384243942440424414244242443424444244542446424474244842449424504245142452424534245442455424564245742458424594246042461424624246342464424654246642467424684246942470424714247242473424744247542476424774247842479424804248142482424834248442485424864248742488424894249042491424924249342494424954249642497424984249942500425014250242503425044250542506425074250842509425104251142512425134251442515425164251742518425194252042521425224252342524425254252642527425284252942530425314253242533425344253542536425374253842539425404254142542425434254442545425464254742548425494255042551425524255342554425554255642557425584255942560425614256242563425644256542566425674256842569425704257142572425734257442575425764257742578425794258042581425824258342584425854258642587425884258942590425914259242593425944259542596425974259842599426004260142602426034260442605426064260742608426094261042611426124261342614426154261642617426184261942620426214262242623426244262542626426274262842629426304263142632426334263442635426364263742638426394264042641426424264342644426454264642647426484264942650426514265242653426544265542656426574265842659426604266142662426634266442665426664266742668426694267042671426724267342674426754267642677426784267942680426814268242683426844268542686426874268842689426904269142692426934269442695426964269742698426994270042701427024270342704427054270642707427084270942710427114271242713427144271542716427174271842719427204272142722427234272442725427264272742728427294273042731427324273342734427354273642737427384273942740427414274242743427444274542746427474274842749427504275142752427534275442755427564275742758427594276042761427624276342764427654276642767427684276942770427714277242773427744277542776427774277842779427804278142782427834278442785427864278742788427894279042791427924279342794427954279642797427984279942800428014280242803428044280542806428074280842809428104281142812428134281442815428164281742818428194282042821428224282342824428254282642827428284282942830428314283242833428344283542836428374283842839428404284142842428434284442845428464284742848428494285042851428524285342854428554285642857428584285942860428614286242863428644286542866428674286842869428704287142872428734287442875428764287742878428794288042881428824288342884428854288642887428884288942890428914289242893428944289542896428974289842899429004290142902429034290442905429064290742908429094291042911429124291342914429154291642917429184291942920429214292242923429244292542926429274292842929429304293142932429334293442935429364293742938429394294042941429424294342944429454294642947429484294942950429514295242953429544295542956429574295842959429604296142962429634296442965429664296742968429694297042971429724297342974429754297642977429784297942980429814298242983429844298542986429874298842989429904299142992429934299442995429964299742998429994300043001430024300343004430054300643007430084300943010430114301243013430144301543016430174301843019430204302143022430234302443025430264302743028430294303043031430324303343034430354303643037430384303943040430414304243043430444304543046430474304843049430504305143052430534305443055430564305743058430594306043061430624306343064430654306643067430684306943070430714307243073430744307543076430774307843079430804308143082430834308443085430864308743088430894309043091430924309343094430954309643097430984309943100431014310243103431044310543106431074310843109431104311143112431134311443115431164311743118431194312043121431224312343124431254312643127431284312943130431314313243133431344313543136431374313843139431404314143142431434314443145431464314743148431494315043151431524315343154431554315643157431584315943160431614316243163431644316543166431674316843169431704317143172431734317443175431764317743178431794318043181431824318343184431854318643187431884318943190431914319243193431944319543196431974319843199432004320143202432034320443205432064320743208432094321043211432124321343214432154321643217432184321943220432214322243223432244322543226432274322843229432304323143232432334323443235432364323743238432394324043241432424324343244432454324643247432484324943250432514325243253432544325543256432574325843259432604326143262432634326443265432664326743268432694327043271432724327343274432754327643277432784327943280432814328243283432844328543286432874328843289432904329143292432934329443295432964329743298432994330043301433024330343304433054330643307433084330943310433114331243313433144331543316433174331843319433204332143322433234332443325433264332743328433294333043331433324333343334433354333643337433384333943340433414334243343433444334543346433474334843349433504335143352433534335443355433564335743358433594336043361433624336343364433654336643367433684336943370433714337243373433744337543376433774337843379433804338143382433834338443385433864338743388433894339043391433924339343394433954339643397433984339943400434014340243403434044340543406434074340843409434104341143412434134341443415434164341743418434194342043421434224342343424434254342643427434284342943430434314343243433434344343543436434374343843439434404344143442434434344443445434464344743448434494345043451434524345343454434554345643457434584345943460434614346243463434644346543466434674346843469434704347143472434734347443475434764347743478434794348043481434824348343484434854348643487434884348943490434914349243493434944349543496434974349843499435004350143502435034350443505435064350743508435094351043511435124351343514435154351643517435184351943520435214352243523435244352543526435274352843529435304353143532435334353443535435364353743538435394354043541435424354343544435454354643547435484354943550435514355243553435544355543556435574355843559435604356143562435634356443565435664356743568435694357043571435724357343574435754357643577435784357943580435814358243583435844358543586435874358843589435904359143592435934359443595435964359743598435994360043601436024360343604436054360643607436084360943610436114361243613436144361543616436174361843619436204362143622436234362443625436264362743628436294363043631436324363343634436354363643637436384363943640436414364243643436444364543646436474364843649436504365143652436534365443655436564365743658436594366043661436624366343664436654366643667436684366943670436714367243673436744367543676436774367843679436804368143682436834368443685436864368743688436894369043691436924369343694436954369643697436984369943700437014370243703437044370543706437074370843709437104371143712437134371443715437164371743718437194372043721437224372343724437254372643727437284372943730437314373243733437344373543736437374373843739437404374143742437434374443745437464374743748437494375043751437524375343754437554375643757437584375943760437614376243763437644376543766437674376843769437704377143772437734377443775437764377743778437794378043781437824378343784437854378643787437884378943790437914379243793437944379543796437974379843799438004380143802438034380443805438064380743808438094381043811438124381343814438154381643817438184381943820438214382243823438244382543826438274382843829438304383143832438334383443835438364383743838438394384043841438424384343844438454384643847438484384943850438514385243853438544385543856438574385843859438604386143862438634386443865438664386743868438694387043871438724387343874438754387643877438784387943880438814388243883438844388543886438874388843889438904389143892438934389443895438964389743898438994390043901439024390343904439054390643907439084390943910439114391243913439144391543916439174391843919439204392143922439234392443925439264392743928439294393043931439324393343934439354393643937439384393943940439414394243943439444394543946439474394843949439504395143952439534395443955439564395743958439594396043961439624396343964439654396643967439684396943970439714397243973439744397543976439774397843979439804398143982439834398443985439864398743988439894399043991439924399343994439954399643997439984399944000440014400244003440044400544006440074400844009440104401144012440134401444015440164401744018440194402044021440224402344024440254402644027440284402944030440314403244033440344403544036440374403844039440404404144042440434404444045440464404744048440494405044051440524405344054440554405644057440584405944060440614406244063440644406544066440674406844069440704407144072440734407444075440764407744078440794408044081440824408344084440854408644087440884408944090440914409244093440944409544096440974409844099441004410144102441034410444105441064410744108441094411044111441124411344114441154411644117441184411944120441214412244123441244412544126441274412844129441304413144132441334413444135441364413744138441394414044141441424414344144441454414644147441484414944150441514415244153441544415544156441574415844159441604416144162441634416444165441664416744168441694417044171441724417344174441754417644177441784417944180441814418244183441844418544186441874418844189441904419144192441934419444195441964419744198441994420044201442024420344204442054420644207442084420944210442114421244213442144421544216442174421844219442204422144222442234422444225442264422744228442294423044231442324423344234442354423644237442384423944240442414424244243442444424544246442474424844249442504425144252442534425444255442564425744258442594426044261442624426344264442654426644267442684426944270442714427244273442744427544276442774427844279442804428144282442834428444285442864428744288442894429044291442924429344294442954429644297442984429944300443014430244303443044430544306443074430844309443104431144312443134431444315443164431744318443194432044321443224432344324443254432644327443284432944330443314433244333443344433544336443374433844339443404434144342443434434444345443464434744348443494435044351443524435344354443554435644357443584435944360443614436244363443644436544366443674436844369443704437144372443734437444375443764437744378443794438044381443824438344384443854438644387443884438944390443914439244393443944439544396443974439844399444004440144402444034440444405444064440744408444094441044411444124441344414444154441644417444184441944420444214442244423444244442544426444274442844429444304443144432444334443444435444364443744438444394444044441444424444344444444454444644447444484444944450444514445244453444544445544456444574445844459444604446144462444634446444465444664446744468444694447044471444724447344474444754447644477444784447944480444814448244483444844448544486444874448844489444904449144492444934449444495444964449744498444994450044501445024450344504445054450644507445084450944510445114451244513445144451544516445174451844519445204452144522445234452444525445264452744528445294453044531445324453344534445354453644537445384453944540445414454244543445444454544546445474454844549445504455144552445534455444555445564455744558445594456044561445624456344564445654456644567445684456944570445714457244573445744457544576445774457844579445804458144582445834458444585445864458744588445894459044591445924459344594445954459644597445984459944600446014460244603446044460544606446074460844609446104461144612446134461444615446164461744618446194462044621446224462344624446254462644627446284462944630446314463244633446344463544636446374463844639446404464144642446434464444645446464464744648446494465044651446524465344654446554465644657446584465944660446614466244663446644466544666446674466844669446704467144672446734467444675446764467744678446794468044681446824468344684446854468644687446884468944690446914469244693446944469544696446974469844699447004470144702447034470444705447064470744708447094471044711447124471344714447154471644717447184471944720447214472244723447244472544726447274472844729447304473144732447334473444735447364473744738447394474044741447424474344744447454474644747447484474944750447514475244753447544475544756447574475844759447604476144762447634476444765447664476744768447694477044771447724477344774447754477644777447784477944780447814478244783447844478544786447874478844789447904479144792447934479444795447964479744798447994480044801448024480344804448054480644807448084480944810448114481244813448144481544816448174481844819448204482144822448234482444825448264482744828448294483044831448324483344834448354483644837448384483944840448414484244843448444484544846448474484844849448504485144852448534485444855448564485744858448594486044861448624486344864448654486644867448684486944870448714487244873448744487544876448774487844879448804488144882448834488444885448864488744888448894489044891448924489344894448954489644897448984489944900449014490244903449044490544906449074490844909449104491144912449134491444915449164491744918449194492044921449224492344924449254492644927449284492944930449314493244933449344493544936449374493844939449404494144942449434494444945449464494744948449494495044951449524495344954449554495644957449584495944960449614496244963449644496544966449674496844969449704497144972449734497444975449764497744978449794498044981449824498344984449854498644987449884498944990449914499244993449944499544996449974499844999450004500145002450034500445005450064500745008450094501045011450124501345014450154501645017450184501945020450214502245023450244502545026450274502845029450304503145032450334503445035450364503745038450394504045041450424504345044450454504645047450484504945050450514505245053450544505545056450574505845059450604506145062450634506445065450664506745068450694507045071450724507345074450754507645077450784507945080450814508245083450844508545086450874508845089450904509145092450934509445095450964509745098450994510045101451024510345104451054510645107451084510945110451114511245113451144511545116451174511845119451204512145122451234512445125451264512745128451294513045131451324513345134451354513645137451384513945140451414514245143451444514545146451474514845149451504515145152451534515445155451564515745158451594516045161451624516345164451654516645167451684516945170451714517245173451744517545176451774517845179451804518145182451834518445185451864518745188451894519045191451924519345194451954519645197451984519945200452014520245203452044520545206452074520845209452104521145212452134521445215452164521745218452194522045221452224522345224452254522645227452284522945230452314523245233452344523545236452374523845239452404524145242452434524445245452464524745248452494525045251452524525345254452554525645257452584525945260452614526245263452644526545266452674526845269452704527145272452734527445275452764527745278452794528045281452824528345284452854528645287452884528945290452914529245293452944529545296452974529845299453004530145302453034530445305453064530745308453094531045311453124531345314453154531645317453184531945320453214532245323453244532545326453274532845329453304533145332453334533445335453364533745338453394534045341453424534345344453454534645347453484534945350453514535245353453544535545356453574535845359453604536145362453634536445365453664536745368453694537045371453724537345374453754537645377453784537945380453814538245383453844538545386453874538845389453904539145392453934539445395453964539745398453994540045401454024540345404454054540645407454084540945410454114541245413454144541545416454174541845419454204542145422454234542445425454264542745428454294543045431454324543345434454354543645437454384543945440454414544245443454444544545446454474544845449454504545145452454534545445455454564545745458454594546045461454624546345464454654546645467454684546945470454714547245473454744547545476454774547845479454804548145482454834548445485454864548745488454894549045491454924549345494454954549645497454984549945500455014550245503455044550545506455074550845509455104551145512455134551445515455164551745518455194552045521455224552345524455254552645527455284552945530455314553245533455344553545536455374553845539455404554145542455434554445545455464554745548455494555045551455524555345554455554555645557455584555945560455614556245563455644556545566455674556845569455704557145572455734557445575455764557745578455794558045581455824558345584455854558645587455884558945590455914559245593455944559545596455974559845599456004560145602456034560445605456064560745608456094561045611456124561345614456154561645617456184561945620456214562245623456244562545626456274562845629456304563145632456334563445635456364563745638456394564045641456424564345644456454564645647456484564945650456514565245653456544565545656456574565845659456604566145662456634566445665456664566745668456694567045671456724567345674456754567645677456784567945680456814568245683456844568545686456874568845689456904569145692456934569445695456964569745698456994570045701457024570345704457054570645707457084570945710457114571245713457144571545716457174571845719457204572145722457234572445725457264572745728457294573045731457324573345734457354573645737457384573945740457414574245743457444574545746457474574845749457504575145752457534575445755457564575745758457594576045761457624576345764457654576645767457684576945770457714577245773457744577545776457774577845779457804578145782457834578445785457864578745788457894579045791457924579345794457954579645797457984579945800458014580245803458044580545806458074580845809458104581145812458134581445815458164581745818458194582045821458224582345824458254582645827458284582945830458314583245833458344583545836458374583845839458404584145842458434584445845458464584745848458494585045851458524585345854458554585645857458584585945860458614586245863458644586545866458674586845869458704587145872458734587445875458764587745878458794588045881458824588345884458854588645887458884588945890458914589245893458944589545896458974589845899459004590145902459034590445905459064590745908459094591045911459124591345914459154591645917459184591945920459214592245923459244592545926459274592845929459304593145932459334593445935459364593745938459394594045941459424594345944459454594645947459484594945950459514595245953459544595545956459574595845959459604596145962459634596445965459664596745968459694597045971459724597345974459754597645977459784597945980459814598245983459844598545986459874598845989459904599145992459934599445995459964599745998459994600046001460024600346004460054600646007460084600946010460114601246013460144601546016460174601846019460204602146022460234602446025460264602746028460294603046031460324603346034460354603646037460384603946040460414604246043460444604546046460474604846049460504605146052460534605446055460564605746058460594606046061460624606346064460654606646067460684606946070460714607246073460744607546076460774607846079460804608146082460834608446085460864608746088460894609046091460924609346094460954609646097460984609946100461014610246103461044610546106461074610846109461104611146112461134611446115461164611746118461194612046121461224612346124461254612646127461284612946130461314613246133461344613546136461374613846139461404614146142461434614446145461464614746148461494615046151461524615346154461554615646157461584615946160461614616246163461644616546166461674616846169461704617146172461734617446175461764617746178461794618046181461824618346184461854618646187461884618946190461914619246193461944619546196461974619846199462004620146202462034620446205462064620746208462094621046211462124621346214462154621646217462184621946220462214622246223462244622546226462274622846229462304623146232462334623446235462364623746238462394624046241462424624346244462454624646247462484624946250462514625246253462544625546256462574625846259462604626146262462634626446265462664626746268462694627046271462724627346274462754627646277462784627946280462814628246283462844628546286462874628846289462904629146292462934629446295462964629746298462994630046301463024630346304463054630646307463084630946310463114631246313463144631546316463174631846319463204632146322463234632446325463264632746328463294633046331463324633346334463354633646337463384633946340463414634246343463444634546346463474634846349463504635146352463534635446355463564635746358463594636046361463624636346364463654636646367463684636946370463714637246373463744637546376463774637846379463804638146382463834638446385463864638746388463894639046391463924639346394463954639646397463984639946400464014640246403464044640546406464074640846409464104641146412464134641446415464164641746418464194642046421464224642346424464254642646427464284642946430464314643246433464344643546436464374643846439464404644146442464434644446445464464644746448464494645046451464524645346454464554645646457464584645946460464614646246463464644646546466464674646846469464704647146472464734647446475464764647746478464794648046481464824648346484464854648646487464884648946490464914649246493464944649546496464974649846499465004650146502465034650446505465064650746508465094651046511465124651346514465154651646517465184651946520465214652246523465244652546526465274652846529465304653146532465334653446535465364653746538465394654046541465424654346544465454654646547465484654946550465514655246553465544655546556465574655846559465604656146562465634656446565465664656746568465694657046571465724657346574465754657646577465784657946580465814658246583465844658546586465874658846589465904659146592465934659446595465964659746598465994660046601466024660346604466054660646607466084660946610466114661246613466144661546616466174661846619466204662146622466234662446625466264662746628466294663046631466324663346634466354663646637466384663946640466414664246643466444664546646466474664846649466504665146652466534665446655466564665746658466594666046661466624666346664466654666646667466684666946670466714667246673466744667546676466774667846679466804668146682466834668446685466864668746688466894669046691466924669346694466954669646697466984669946700467014670246703467044670546706467074670846709467104671146712467134671446715467164671746718467194672046721467224672346724467254672646727467284672946730467314673246733467344673546736467374673846739467404674146742467434674446745467464674746748467494675046751467524675346754467554675646757467584675946760467614676246763467644676546766467674676846769467704677146772467734677446775467764677746778467794678046781467824678346784467854678646787467884678946790467914679246793467944679546796467974679846799468004680146802468034680446805468064680746808468094681046811468124681346814468154681646817468184681946820468214682246823468244682546826468274682846829468304683146832468334683446835468364683746838468394684046841468424684346844468454684646847468484684946850468514685246853468544685546856468574685846859468604686146862468634686446865468664686746868468694687046871468724687346874468754687646877468784687946880468814688246883468844688546886468874688846889468904689146892468934689446895468964689746898468994690046901469024690346904469054690646907469084690946910469114691246913469144691546916469174691846919469204692146922469234692446925469264692746928469294693046931469324693346934469354693646937469384693946940469414694246943469444694546946469474694846949469504695146952469534695446955469564695746958469594696046961469624696346964469654696646967469684696946970469714697246973469744697546976469774697846979469804698146982469834698446985469864698746988469894699046991469924699346994469954699646997469984699947000470014700247003470044700547006470074700847009470104701147012470134701447015470164701747018470194702047021470224702347024470254702647027470284702947030470314703247033470344703547036470374703847039470404704147042470434704447045470464704747048470494705047051470524705347054470554705647057470584705947060470614706247063470644706547066470674706847069470704707147072470734707447075470764707747078470794708047081470824708347084470854708647087470884708947090470914709247093470944709547096470974709847099471004710147102471034710447105471064710747108471094711047111471124711347114471154711647117471184711947120471214712247123471244712547126471274712847129471304713147132471334713447135471364713747138471394714047141471424714347144471454714647147471484714947150471514715247153471544715547156471574715847159471604716147162471634716447165471664716747168471694717047171471724717347174471754717647177471784717947180471814718247183471844718547186471874718847189471904719147192471934719447195471964719747198471994720047201472024720347204472054720647207472084720947210472114721247213472144721547216472174721847219472204722147222472234722447225472264722747228472294723047231472324723347234472354723647237472384723947240472414724247243472444724547246472474724847249472504725147252472534725447255472564725747258472594726047261472624726347264472654726647267472684726947270472714727247273472744727547276472774727847279472804728147282472834728447285472864728747288472894729047291472924729347294472954729647297472984729947300473014730247303473044730547306473074730847309473104731147312473134731447315473164731747318473194732047321473224732347324473254732647327473284732947330473314733247333473344733547336473374733847339473404734147342473434734447345473464734747348473494735047351473524735347354473554735647357473584735947360473614736247363473644736547366473674736847369473704737147372473734737447375473764737747378473794738047381473824738347384473854738647387473884738947390473914739247393473944739547396473974739847399474004740147402474034740447405474064740747408474094741047411474124741347414474154741647417474184741947420474214742247423474244742547426474274742847429474304743147432474334743447435474364743747438474394744047441474424744347444474454744647447474484744947450474514745247453474544745547456474574745847459474604746147462474634746447465474664746747468474694747047471474724747347474474754747647477474784747947480474814748247483474844748547486474874748847489474904749147492474934749447495474964749747498474994750047501475024750347504475054750647507475084750947510475114751247513475144751547516475174751847519475204752147522475234752447525475264752747528475294753047531475324753347534475354753647537475384753947540475414754247543475444754547546475474754847549475504755147552475534755447555475564755747558475594756047561475624756347564475654756647567475684756947570475714757247573475744757547576475774757847579475804758147582475834758447585475864758747588475894759047591475924759347594475954759647597475984759947600476014760247603476044760547606476074760847609476104761147612476134761447615476164761747618476194762047621476224762347624476254762647627476284762947630476314763247633476344763547636476374763847639476404764147642476434764447645476464764747648476494765047651476524765347654476554765647657476584765947660476614766247663476644766547666476674766847669476704767147672476734767447675476764767747678476794768047681476824768347684476854768647687476884768947690476914769247693476944769547696476974769847699477004770147702477034770447705477064770747708477094771047711477124771347714477154771647717477184771947720477214772247723477244772547726477274772847729477304773147732477334773447735477364773747738477394774047741477424774347744477454774647747477484774947750477514775247753477544775547756477574775847759477604776147762477634776447765477664776747768477694777047771477724777347774477754777647777477784777947780477814778247783477844778547786477874778847789477904779147792477934779447795477964779747798477994780047801478024780347804478054780647807478084780947810478114781247813478144781547816478174781847819478204782147822478234782447825478264782747828478294783047831478324783347834478354783647837478384783947840478414784247843478444784547846478474784847849478504785147852478534785447855478564785747858478594786047861478624786347864478654786647867478684786947870478714787247873478744787547876478774787847879478804788147882478834788447885478864788747888478894789047891478924789347894478954789647897478984789947900479014790247903479044790547906479074790847909479104791147912479134791447915479164791747918479194792047921479224792347924479254792647927479284792947930479314793247933479344793547936479374793847939479404794147942479434794447945479464794747948479494795047951479524795347954479554795647957479584795947960479614796247963479644796547966479674796847969479704797147972479734797447975479764797747978479794798047981479824798347984479854798647987479884798947990479914799247993479944799547996479974799847999480004800148002480034800448005480064800748008480094801048011480124801348014480154801648017480184801948020480214802248023480244802548026480274802848029480304803148032480334803448035480364803748038480394804048041480424804348044480454804648047480484804948050480514805248053480544805548056480574805848059480604806148062480634806448065480664806748068480694807048071480724807348074480754807648077480784807948080480814808248083480844808548086480874808848089480904809148092480934809448095480964809748098480994810048101481024810348104481054810648107481084810948110481114811248113481144811548116481174811848119481204812148122481234812448125481264812748128481294813048131481324813348134481354813648137481384813948140481414814248143481444814548146481474814848149481504815148152481534815448155481564815748158481594816048161481624816348164481654816648167481684816948170481714817248173481744817548176481774817848179481804818148182481834818448185481864818748188481894819048191481924819348194481954819648197481984819948200482014820248203482044820548206482074820848209482104821148212482134821448215482164821748218482194822048221482224822348224482254822648227482284822948230482314823248233482344823548236482374823848239482404824148242482434824448245482464824748248482494825048251482524825348254482554825648257482584825948260482614826248263482644826548266482674826848269482704827148272482734827448275482764827748278482794828048281482824828348284482854828648287482884828948290482914829248293482944829548296482974829848299483004830148302483034830448305483064830748308483094831048311483124831348314483154831648317483184831948320483214832248323483244832548326483274832848329483304833148332483334833448335483364833748338483394834048341483424834348344483454834648347483484834948350483514835248353483544835548356483574835848359483604836148362483634836448365483664836748368483694837048371483724837348374483754837648377483784837948380483814838248383483844838548386483874838848389483904839148392483934839448395483964839748398483994840048401484024840348404484054840648407484084840948410484114841248413484144841548416484174841848419484204842148422484234842448425484264842748428484294843048431484324843348434484354843648437484384843948440484414844248443484444844548446484474844848449484504845148452484534845448455484564845748458484594846048461484624846348464484654846648467484684846948470484714847248473484744847548476484774847848479484804848148482484834848448485484864848748488484894849048491484924849348494484954849648497484984849948500485014850248503485044850548506485074850848509485104851148512485134851448515485164851748518485194852048521485224852348524485254852648527485284852948530485314853248533485344853548536485374853848539485404854148542485434854448545485464854748548485494855048551485524855348554485554855648557485584855948560485614856248563485644856548566485674856848569485704857148572485734857448575485764857748578485794858048581485824858348584485854858648587485884858948590485914859248593485944859548596485974859848599486004860148602486034860448605486064860748608486094861048611486124861348614486154861648617486184861948620486214862248623486244862548626486274862848629486304863148632486334863448635486364863748638486394864048641486424864348644486454864648647486484864948650486514865248653486544865548656486574865848659486604866148662486634866448665486664866748668486694867048671486724867348674486754867648677486784867948680486814868248683486844868548686486874868848689486904869148692486934869448695486964869748698486994870048701487024870348704487054870648707487084870948710487114871248713487144871548716487174871848719487204872148722487234872448725487264872748728487294873048731487324873348734487354873648737487384873948740487414874248743487444874548746487474874848749487504875148752487534875448755487564875748758487594876048761487624876348764487654876648767487684876948770487714877248773487744877548776487774877848779487804878148782487834878448785487864878748788487894879048791487924879348794487954879648797487984879948800488014880248803488044880548806488074880848809488104881148812488134881448815488164881748818488194882048821488224882348824488254882648827488284882948830488314883248833488344883548836488374883848839488404884148842488434884448845488464884748848488494885048851488524885348854488554885648857488584885948860488614886248863488644886548866488674886848869488704887148872488734887448875488764887748878488794888048881488824888348884488854888648887488884888948890488914889248893488944889548896488974889848899489004890148902489034890448905489064890748908489094891048911489124891348914489154891648917489184891948920489214892248923489244892548926489274892848929489304893148932489334893448935489364893748938489394894048941489424894348944489454894648947489484894948950489514895248953489544895548956489574895848959489604896148962489634896448965489664896748968489694897048971489724897348974489754897648977489784897948980489814898248983489844898548986489874898848989489904899148992489934899448995489964899748998489994900049001490024900349004490054900649007490084900949010490114901249013490144901549016490174901849019490204902149022490234902449025490264902749028490294903049031490324903349034490354903649037490384903949040490414904249043490444904549046490474904849049490504905149052490534905449055490564905749058490594906049061490624906349064490654906649067490684906949070490714907249073490744907549076490774907849079490804908149082490834908449085490864908749088490894909049091490924909349094490954909649097490984909949100491014910249103491044910549106491074910849109491104911149112491134911449115491164911749118491194912049121491224912349124491254912649127491284912949130491314913249133491344913549136491374913849139491404914149142491434914449145491464914749148491494915049151491524915349154491554915649157491584915949160491614916249163491644916549166491674916849169491704917149172491734917449175491764917749178491794918049181491824918349184491854918649187491884918949190491914919249193491944919549196491974919849199492004920149202492034920449205492064920749208492094921049211492124921349214492154921649217492184921949220492214922249223492244922549226492274922849229492304923149232492334923449235492364923749238492394924049241492424924349244492454924649247492484924949250492514925249253492544925549256492574925849259492604926149262492634926449265492664926749268492694927049271492724927349274492754927649277492784927949280492814928249283492844928549286492874928849289492904929149292492934929449295492964929749298492994930049301493024930349304493054930649307493084930949310493114931249313493144931549316493174931849319493204932149322493234932449325493264932749328493294933049331493324933349334493354933649337493384933949340493414934249343493444934549346493474934849349493504935149352493534935449355493564935749358493594936049361493624936349364493654936649367493684936949370493714937249373493744937549376493774937849379493804938149382493834938449385493864938749388493894939049391493924939349394493954939649397493984939949400494014940249403494044940549406494074940849409494104941149412494134941449415494164941749418494194942049421494224942349424494254942649427494284942949430494314943249433494344943549436494374943849439494404944149442494434944449445494464944749448494494945049451494524945349454494554945649457494584945949460494614946249463494644946549466494674946849469494704947149472494734947449475494764947749478494794948049481494824948349484494854948649487494884948949490494914949249493494944949549496494974949849499495004950149502495034950449505495064950749508495094951049511495124951349514495154951649517495184951949520495214952249523495244952549526495274952849529495304953149532495334953449535495364953749538495394954049541495424954349544495454954649547495484954949550495514955249553495544955549556495574955849559495604956149562495634956449565495664956749568495694957049571495724957349574495754957649577495784957949580495814958249583495844958549586495874958849589495904959149592495934959449595495964959749598495994960049601496024960349604496054960649607496084960949610496114961249613496144961549616496174961849619496204962149622496234962449625496264962749628496294963049631496324963349634496354963649637496384963949640496414964249643496444964549646496474964849649496504965149652496534965449655496564965749658496594966049661496624966349664496654966649667496684966949670496714967249673496744967549676496774967849679496804968149682496834968449685496864968749688496894969049691496924969349694496954969649697496984969949700497014970249703497044970549706497074970849709497104971149712497134971449715497164971749718497194972049721497224972349724497254972649727497284972949730497314973249733497344973549736497374973849739497404974149742497434974449745497464974749748497494975049751497524975349754497554975649757497584975949760497614976249763497644976549766497674976849769497704977149772497734977449775497764977749778497794978049781497824978349784497854978649787497884978949790497914979249793497944979549796497974979849799498004980149802498034980449805498064980749808498094981049811498124981349814498154981649817498184981949820498214982249823498244982549826498274982849829498304983149832498334983449835498364983749838498394984049841498424984349844498454984649847498484984949850498514985249853498544985549856498574985849859498604986149862498634986449865498664986749868498694987049871498724987349874498754987649877498784987949880498814988249883498844988549886498874988849889498904989149892498934989449895498964989749898498994990049901499024990349904499054990649907499084990949910499114991249913499144991549916499174991849919499204992149922499234992449925499264992749928499294993049931499324993349934499354993649937499384993949940499414994249943499444994549946499474994849949499504995149952499534995449955499564995749958499594996049961499624996349964499654996649967499684996949970499714997249973499744997549976499774997849979499804998149982499834998449985499864998749988499894999049991499924999349994499954999649997499984999950000500015000250003500045000550006500075000850009500105001150012500135001450015500165001750018500195002050021500225002350024500255002650027500285002950030500315003250033500345003550036500375003850039500405004150042500435004450045500465004750048500495005050051500525005350054500555005650057500585005950060500615006250063500645006550066500675006850069500705007150072500735007450075500765007750078500795008050081500825008350084500855008650087500885008950090500915009250093500945009550096500975009850099501005010150102501035010450105501065010750108501095011050111501125011350114501155011650117501185011950120501215012250123501245012550126501275012850129501305013150132501335013450135501365013750138501395014050141501425014350144501455014650147501485014950150501515015250153501545015550156501575015850159501605016150162501635016450165501665016750168501695017050171501725017350174501755017650177501785017950180501815018250183501845018550186501875018850189501905019150192501935019450195501965019750198501995020050201502025020350204502055020650207502085020950210502115021250213502145021550216502175021850219502205022150222502235022450225502265022750228502295023050231502325023350234502355023650237502385023950240502415024250243502445024550246502475024850249502505025150252502535025450255502565025750258502595026050261502625026350264502655026650267502685026950270502715027250273502745027550276502775027850279502805028150282502835028450285502865028750288502895029050291502925029350294502955029650297502985029950300503015030250303503045030550306503075030850309503105031150312503135031450315503165031750318503195032050321503225032350324503255032650327503285032950330503315033250333503345033550336503375033850339503405034150342503435034450345503465034750348503495035050351503525035350354503555035650357503585035950360503615036250363503645036550366503675036850369503705037150372503735037450375503765037750378503795038050381503825038350384503855038650387503885038950390503915039250393503945039550396503975039850399504005040150402504035040450405504065040750408504095041050411504125041350414504155041650417504185041950420504215042250423504245042550426504275042850429504305043150432504335043450435504365043750438504395044050441504425044350444504455044650447504485044950450504515045250453504545045550456504575045850459504605046150462504635046450465504665046750468504695047050471504725047350474504755047650477504785047950480504815048250483504845048550486504875048850489504905049150492504935049450495504965049750498504995050050501505025050350504505055050650507505085050950510505115051250513505145051550516505175051850519505205052150522505235052450525505265052750528505295053050531505325053350534505355053650537505385053950540505415054250543505445054550546505475054850549505505055150552505535055450555505565055750558505595056050561505625056350564505655056650567505685056950570505715057250573505745057550576505775057850579505805058150582505835058450585505865058750588505895059050591505925059350594505955059650597505985059950600506015060250603506045060550606506075060850609506105061150612506135061450615506165061750618506195062050621506225062350624506255062650627506285062950630506315063250633506345063550636506375063850639506405064150642506435064450645506465064750648506495065050651506525065350654506555065650657506585065950660506615066250663506645066550666506675066850669506705067150672506735067450675506765067750678506795068050681506825068350684506855068650687506885068950690506915069250693506945069550696506975069850699507005070150702507035070450705507065070750708507095071050711507125071350714507155071650717507185071950720507215072250723507245072550726507275072850729507305073150732507335073450735507365073750738507395074050741507425074350744507455074650747507485074950750507515075250753507545075550756507575075850759507605076150762507635076450765507665076750768507695077050771507725077350774507755077650777507785077950780507815078250783507845078550786507875078850789507905079150792507935079450795507965079750798507995080050801508025080350804508055080650807508085080950810508115081250813508145081550816508175081850819508205082150822508235082450825508265082750828508295083050831508325083350834508355083650837508385083950840508415084250843508445084550846508475084850849508505085150852508535085450855508565085750858508595086050861508625086350864508655086650867508685086950870508715087250873508745087550876508775087850879508805088150882508835088450885508865088750888508895089050891508925089350894508955089650897508985089950900509015090250903509045090550906509075090850909509105091150912509135091450915509165091750918509195092050921509225092350924509255092650927509285092950930509315093250933509345093550936509375093850939509405094150942509435094450945509465094750948509495095050951509525095350954509555095650957509585095950960509615096250963509645096550966509675096850969509705097150972509735097450975509765097750978509795098050981509825098350984509855098650987509885098950990509915099250993509945099550996509975099850999510005100151002510035100451005510065100751008510095101051011510125101351014510155101651017510185101951020510215102251023510245102551026510275102851029510305103151032510335103451035510365103751038510395104051041510425104351044510455104651047510485104951050510515105251053510545105551056510575105851059510605106151062510635106451065510665106751068510695107051071510725107351074510755107651077510785107951080510815108251083510845108551086510875108851089510905109151092510935109451095510965109751098510995110051101511025110351104511055110651107511085110951110511115111251113511145111551116511175111851119511205112151122511235112451125511265112751128511295113051131511325113351134511355113651137511385113951140511415114251143511445114551146511475114851149511505115151152511535115451155511565115751158511595116051161511625116351164511655116651167511685116951170511715117251173511745117551176511775117851179511805118151182511835118451185511865118751188511895119051191511925119351194511955119651197511985119951200512015120251203512045120551206512075120851209512105121151212512135121451215512165121751218512195122051221512225122351224512255122651227512285122951230512315123251233512345123551236512375123851239512405124151242512435124451245512465124751248512495125051251512525125351254512555125651257512585125951260512615126251263512645126551266512675126851269512705127151272512735127451275512765127751278512795128051281512825128351284512855128651287512885128951290512915129251293512945129551296512975129851299513005130151302513035130451305513065130751308513095131051311513125131351314513155131651317513185131951320513215132251323513245132551326513275132851329513305133151332513335133451335513365133751338513395134051341513425134351344513455134651347513485134951350513515135251353513545135551356513575135851359513605136151362513635136451365513665136751368513695137051371513725137351374513755137651377513785137951380513815138251383513845138551386513875138851389513905139151392513935139451395513965139751398513995140051401514025140351404514055140651407514085140951410514115141251413514145141551416514175141851419514205142151422514235142451425514265142751428514295143051431514325143351434514355143651437514385143951440514415144251443514445144551446514475144851449514505145151452514535145451455514565145751458514595146051461514625146351464514655146651467514685146951470514715147251473514745147551476514775147851479514805148151482514835148451485514865148751488514895149051491514925149351494514955149651497514985149951500515015150251503515045150551506515075150851509515105151151512515135151451515515165151751518515195152051521515225152351524515255152651527515285152951530515315153251533515345153551536515375153851539515405154151542515435154451545515465154751548515495155051551515525155351554515555155651557515585155951560515615156251563515645156551566515675156851569515705157151572515735157451575515765157751578515795158051581515825158351584515855158651587515885158951590515915159251593515945159551596515975159851599516005160151602516035160451605516065160751608516095161051611516125161351614516155161651617516185161951620516215162251623516245162551626516275162851629516305163151632516335163451635516365163751638516395164051641516425164351644516455164651647516485164951650516515165251653516545165551656516575165851659516605166151662516635166451665516665166751668516695167051671516725167351674516755167651677516785167951680516815168251683516845168551686516875168851689516905169151692516935169451695516965169751698516995170051701517025170351704517055170651707517085170951710517115171251713517145171551716517175171851719517205172151722517235172451725517265172751728517295173051731517325173351734517355173651737517385173951740517415174251743517445174551746517475174851749517505175151752517535175451755517565175751758517595176051761517625176351764517655176651767517685176951770517715177251773517745177551776517775177851779517805178151782517835178451785517865178751788517895179051791517925179351794517955179651797517985179951800518015180251803518045180551806518075180851809518105181151812518135181451815518165181751818518195182051821518225182351824518255182651827518285182951830518315183251833518345183551836518375183851839518405184151842518435184451845518465184751848518495185051851518525185351854518555185651857518585185951860518615186251863518645186551866518675186851869518705187151872518735187451875518765187751878518795188051881518825188351884518855188651887518885188951890518915189251893518945189551896518975189851899519005190151902519035190451905519065190751908519095191051911519125191351914519155191651917519185191951920519215192251923519245192551926519275192851929519305193151932519335193451935519365193751938519395194051941519425194351944519455194651947519485194951950519515195251953519545195551956519575195851959519605196151962519635196451965519665196751968519695197051971519725197351974519755197651977519785197951980519815198251983519845198551986519875198851989519905199151992519935199451995519965199751998519995200052001520025200352004520055200652007520085200952010520115201252013520145201552016520175201852019520205202152022520235202452025520265202752028520295203052031520325203352034520355203652037520385203952040520415204252043520445204552046520475204852049520505205152052520535205452055520565205752058520595206052061520625206352064520655206652067520685206952070520715207252073520745207552076520775207852079520805208152082520835208452085520865208752088520895209052091520925209352094520955209652097520985209952100521015210252103521045210552106521075210852109521105211152112521135211452115521165211752118521195212052121521225212352124521255212652127521285212952130521315213252133521345213552136521375213852139521405214152142521435214452145521465214752148521495215052151521525215352154521555215652157521585215952160521615216252163521645216552166521675216852169521705217152172521735217452175521765217752178521795218052181521825218352184521855218652187521885218952190521915219252193521945219552196521975219852199522005220152202522035220452205522065220752208522095221052211522125221352214522155221652217522185221952220522215222252223522245222552226522275222852229522305223152232522335223452235522365223752238522395224052241522425224352244522455224652247522485224952250522515225252253522545225552256522575225852259522605226152262522635226452265522665226752268522695227052271522725227352274522755227652277522785227952280522815228252283522845228552286522875228852289522905229152292522935229452295522965229752298522995230052301523025230352304523055230652307523085230952310523115231252313523145231552316523175231852319523205232152322523235232452325523265232752328523295233052331523325233352334523355233652337523385233952340523415234252343523445234552346523475234852349523505235152352523535235452355523565235752358523595236052361523625236352364523655236652367523685236952370523715237252373523745237552376523775237852379523805238152382523835238452385523865238752388523895239052391523925239352394523955239652397523985239952400524015240252403524045240552406524075240852409524105241152412524135241452415524165241752418524195242052421524225242352424524255242652427524285242952430524315243252433524345243552436524375243852439524405244152442524435244452445524465244752448524495245052451524525245352454524555245652457524585245952460524615246252463524645246552466524675246852469524705247152472524735247452475524765247752478524795248052481524825248352484524855248652487524885248952490524915249252493524945249552496524975249852499525005250152502525035250452505525065250752508525095251052511525125251352514525155251652517525185251952520525215252252523525245252552526525275252852529525305253152532525335253452535525365253752538525395254052541525425254352544525455254652547525485254952550525515255252553525545255552556525575255852559525605256152562525635256452565525665256752568525695257052571525725257352574525755257652577525785257952580525815258252583525845258552586525875258852589525905259152592525935259452595525965259752598525995260052601526025260352604526055260652607526085260952610526115261252613526145261552616526175261852619526205262152622526235262452625526265262752628526295263052631526325263352634526355263652637526385263952640526415264252643526445264552646526475264852649526505265152652526535265452655526565265752658526595266052661526625266352664526655266652667526685266952670526715267252673526745267552676526775267852679526805268152682526835268452685526865268752688526895269052691526925269352694526955269652697526985269952700527015270252703527045270552706527075270852709527105271152712527135271452715527165271752718527195272052721527225272352724527255272652727527285272952730527315273252733527345273552736527375273852739527405274152742527435274452745527465274752748527495275052751527525275352754527555275652757527585275952760527615276252763527645276552766527675276852769527705277152772527735277452775527765277752778527795278052781527825278352784527855278652787527885278952790527915279252793527945279552796527975279852799528005280152802528035280452805528065280752808528095281052811528125281352814528155281652817528185281952820528215282252823528245282552826528275282852829528305283152832528335283452835528365283752838528395284052841528425284352844528455284652847528485284952850528515285252853528545285552856528575285852859528605286152862528635286452865528665286752868528695287052871528725287352874528755287652877528785287952880528815288252883528845288552886528875288852889528905289152892528935289452895528965289752898528995290052901529025290352904529055290652907529085290952910529115291252913529145291552916529175291852919529205292152922529235292452925529265292752928529295293052931529325293352934529355293652937529385293952940529415294252943529445294552946529475294852949529505295152952529535295452955529565295752958529595296052961529625296352964529655296652967529685296952970529715297252973529745297552976529775297852979529805298152982529835298452985529865298752988529895299052991529925299352994529955299652997529985299953000530015300253003530045300553006530075300853009530105301153012530135301453015530165301753018530195302053021530225302353024530255302653027530285302953030530315303253033530345303553036530375303853039530405304153042530435304453045530465304753048530495305053051530525305353054530555305653057530585305953060530615306253063530645306553066530675306853069530705307153072530735307453075530765307753078530795308053081530825308353084530855308653087530885308953090530915309253093530945309553096530975309853099531005310153102531035310453105531065310753108531095311053111531125311353114531155311653117531185311953120531215312253123531245312553126531275312853129531305313153132531335313453135531365313753138531395314053141531425314353144531455314653147531485314953150531515315253153531545315553156531575315853159531605316153162531635316453165531665316753168531695317053171531725317353174531755317653177531785317953180531815318253183531845318553186531875318853189531905319153192531935319453195531965319753198531995320053201532025320353204532055320653207532085320953210532115321253213532145321553216532175321853219532205322153222532235322453225532265322753228532295323053231532325323353234532355323653237532385323953240532415324253243532445324553246532475324853249532505325153252532535325453255532565325753258532595326053261532625326353264532655326653267532685326953270532715327253273532745327553276532775327853279532805328153282532835328453285532865328753288532895329053291532925329353294532955329653297532985329953300533015330253303533045330553306533075330853309533105331153312533135331453315533165331753318533195332053321533225332353324533255332653327533285332953330533315333253333533345333553336533375333853339533405334153342533435334453345533465334753348533495335053351533525335353354533555335653357533585335953360533615336253363533645336553366533675336853369533705337153372533735337453375533765337753378533795338053381533825338353384533855338653387533885338953390533915339253393533945339553396533975339853399534005340153402534035340453405534065340753408534095341053411534125341353414534155341653417534185341953420534215342253423534245342553426534275342853429534305343153432534335343453435534365343753438534395344053441534425344353444534455344653447534485344953450534515345253453534545345553456534575345853459534605346153462534635346453465534665346753468534695347053471534725347353474534755347653477534785347953480534815348253483534845348553486534875348853489534905349153492534935349453495534965349753498534995350053501535025350353504535055350653507535085350953510535115351253513535145351553516535175351853519535205352153522535235352453525535265352753528535295353053531535325353353534535355353653537535385353953540535415354253543535445354553546535475354853549535505355153552535535355453555535565355753558535595356053561535625356353564535655356653567535685356953570535715357253573535745357553576535775357853579535805358153582535835358453585535865358753588535895359053591535925359353594535955359653597535985359953600536015360253603536045360553606536075360853609536105361153612536135361453615536165361753618536195362053621536225362353624536255362653627536285362953630536315363253633536345363553636536375363853639536405364153642536435364453645536465364753648536495365053651536525365353654536555365653657536585365953660536615366253663536645366553666536675366853669536705367153672536735367453675536765367753678536795368053681536825368353684536855368653687536885368953690536915369253693536945369553696536975369853699537005370153702537035370453705537065370753708537095371053711537125371353714537155371653717537185371953720537215372253723537245372553726537275372853729537305373153732537335373453735537365373753738537395374053741537425374353744537455374653747537485374953750537515375253753537545375553756537575375853759537605376153762537635376453765537665376753768537695377053771537725377353774537755377653777537785377953780537815378253783537845378553786537875378853789537905379153792537935379453795537965379753798537995380053801538025380353804538055380653807538085380953810538115381253813538145381553816538175381853819538205382153822538235382453825538265382753828538295383053831538325383353834538355383653837538385383953840538415384253843538445384553846538475384853849538505385153852538535385453855538565385753858538595386053861538625386353864538655386653867538685386953870538715387253873538745387553876538775387853879538805388153882538835388453885538865388753888538895389053891538925389353894538955389653897538985389953900539015390253903539045390553906539075390853909539105391153912539135391453915539165391753918539195392053921539225392353924539255392653927539285392953930539315393253933539345393553936539375393853939539405394153942539435394453945539465394753948539495395053951539525395353954539555395653957539585395953960539615396253963539645396553966539675396853969539705397153972539735397453975539765397753978539795398053981539825398353984539855398653987539885398953990539915399253993539945399553996539975399853999540005400154002540035400454005540065400754008540095401054011540125401354014540155401654017540185401954020540215402254023540245402554026540275402854029540305403154032540335403454035540365403754038540395404054041540425404354044540455404654047540485404954050540515405254053540545405554056540575405854059540605406154062540635406454065540665406754068540695407054071540725407354074540755407654077540785407954080540815408254083540845408554086540875408854089540905409154092540935409454095540965409754098540995410054101541025410354104541055410654107541085410954110541115411254113541145411554116541175411854119541205412154122541235412454125541265412754128541295413054131541325413354134541355413654137541385413954140541415414254143541445414554146541475414854149541505415154152541535415454155541565415754158541595416054161541625416354164541655416654167541685416954170541715417254173541745417554176541775417854179541805418154182541835418454185541865418754188541895419054191541925419354194541955419654197541985419954200542015420254203542045420554206542075420854209542105421154212542135421454215542165421754218542195422054221542225422354224542255422654227542285422954230542315423254233542345423554236542375423854239542405424154242542435424454245542465424754248542495425054251542525425354254542555425654257542585425954260542615426254263542645426554266542675426854269542705427154272542735427454275542765427754278542795428054281542825428354284542855428654287542885428954290542915429254293542945429554296542975429854299543005430154302543035430454305543065430754308543095431054311543125431354314543155431654317543185431954320543215432254323543245432554326543275432854329543305433154332543335433454335543365433754338543395434054341543425434354344543455434654347543485434954350543515435254353543545435554356543575435854359543605436154362543635436454365543665436754368543695437054371543725437354374543755437654377543785437954380543815438254383543845438554386543875438854389543905439154392543935439454395543965439754398543995440054401544025440354404544055440654407544085440954410544115441254413544145441554416544175441854419544205442154422544235442454425544265442754428544295443054431544325443354434544355443654437544385443954440544415444254443544445444554446544475444854449544505445154452544535445454455544565445754458544595446054461544625446354464544655446654467544685446954470544715447254473544745447554476544775447854479544805448154482544835448454485544865448754488544895449054491544925449354494544955449654497544985449954500545015450254503545045450554506545075450854509545105451154512545135451454515545165451754518545195452054521545225452354524545255452654527545285452954530545315453254533545345453554536545375453854539545405454154542545435454454545545465454754548545495455054551545525455354554545555455654557545585455954560545615456254563545645456554566545675456854569545705457154572545735457454575545765457754578545795458054581545825458354584545855458654587545885458954590545915459254593545945459554596545975459854599546005460154602546035460454605546065460754608546095461054611546125461354614546155461654617546185461954620546215462254623546245462554626546275462854629546305463154632546335463454635546365463754638546395464054641546425464354644546455464654647546485464954650546515465254653546545465554656546575465854659546605466154662546635466454665546665466754668546695467054671546725467354674546755467654677546785467954680546815468254683546845468554686546875468854689546905469154692546935469454695546965469754698546995470054701547025470354704547055470654707547085470954710547115471254713547145471554716547175471854719547205472154722547235472454725547265472754728547295473054731547325473354734547355473654737547385473954740547415474254743547445474554746547475474854749547505475154752547535475454755547565475754758547595476054761547625476354764547655476654767547685476954770547715477254773547745477554776547775477854779547805478154782547835478454785547865478754788547895479054791547925479354794547955479654797547985479954800548015480254803548045480554806548075480854809548105481154812548135481454815548165481754818548195482054821548225482354824548255482654827548285482954830548315483254833548345483554836548375483854839548405484154842548435484454845548465484754848548495485054851548525485354854548555485654857548585485954860548615486254863548645486554866548675486854869548705487154872548735487454875548765487754878548795488054881548825488354884548855488654887548885488954890548915489254893548945489554896548975489854899549005490154902549035490454905549065490754908549095491054911549125491354914549155491654917549185491954920549215492254923549245492554926549275492854929549305493154932549335493454935549365493754938549395494054941549425494354944549455494654947549485494954950549515495254953549545495554956549575495854959549605496154962549635496454965549665496754968549695497054971549725497354974549755497654977549785497954980549815498254983549845498554986549875498854989549905499154992549935499454995549965499754998549995500055001550025500355004550055500655007550085500955010550115501255013550145501555016550175501855019550205502155022550235502455025550265502755028550295503055031550325503355034550355503655037550385503955040550415504255043550445504555046550475504855049550505505155052550535505455055550565505755058550595506055061550625506355064550655506655067550685506955070550715507255073550745507555076550775507855079550805508155082550835508455085550865508755088550895509055091550925509355094550955509655097550985509955100551015510255103551045510555106551075510855109551105511155112551135511455115551165511755118551195512055121551225512355124551255512655127551285512955130551315513255133551345513555136551375513855139551405514155142551435514455145551465514755148551495515055151551525515355154551555515655157551585515955160551615516255163551645516555166551675516855169551705517155172551735517455175551765517755178551795518055181551825518355184551855518655187551885518955190551915519255193551945519555196551975519855199552005520155202552035520455205552065520755208552095521055211552125521355214552155521655217552185521955220552215522255223552245522555226552275522855229552305523155232552335523455235552365523755238552395524055241552425524355244552455524655247552485524955250552515525255253552545525555256552575525855259552605526155262552635526455265552665526755268552695527055271552725527355274552755527655277552785527955280552815528255283552845528555286552875528855289552905529155292552935529455295552965529755298552995530055301553025530355304553055530655307553085530955310553115531255313553145531555316553175531855319553205532155322553235532455325553265532755328553295533055331553325533355334553355533655337553385533955340553415534255343553445534555346553475534855349553505535155352553535535455355553565535755358553595536055361553625536355364553655536655367553685536955370553715537255373553745537555376553775537855379553805538155382553835538455385553865538755388553895539055391553925539355394553955539655397553985539955400554015540255403554045540555406554075540855409554105541155412554135541455415554165541755418554195542055421554225542355424554255542655427554285542955430554315543255433554345543555436554375543855439554405544155442554435544455445554465544755448554495545055451554525545355454554555545655457554585545955460554615546255463554645546555466554675546855469554705547155472554735547455475554765547755478554795548055481554825548355484554855548655487554885548955490554915549255493554945549555496554975549855499555005550155502555035550455505555065550755508555095551055511555125551355514555155551655517555185551955520555215552255523555245552555526555275552855529555305553155532555335553455535555365553755538555395554055541555425554355544555455554655547555485554955550555515555255553555545555555556555575555855559555605556155562555635556455565555665556755568555695557055571555725557355574555755557655577555785557955580555815558255583555845558555586555875558855589555905559155592555935559455595555965559755598555995560055601556025560355604556055560655607556085560955610556115561255613556145561555616556175561855619556205562155622556235562455625556265562755628556295563055631556325563355634556355563655637556385563955640556415564255643556445564555646556475564855649556505565155652556535565455655556565565755658556595566055661556625566355664556655566655667556685566955670556715567255673556745567555676556775567855679556805568155682556835568455685556865568755688556895569055691556925569355694556955569655697556985569955700557015570255703557045570555706557075570855709557105571155712557135571455715557165571755718557195572055721557225572355724557255572655727557285572955730557315573255733557345573555736557375573855739557405574155742557435574455745557465574755748557495575055751557525575355754557555575655757557585575955760557615576255763557645576555766557675576855769557705577155772557735577455775557765577755778557795578055781557825578355784557855578655787557885578955790557915579255793557945579555796557975579855799558005580155802558035580455805558065580755808558095581055811558125581355814558155581655817558185581955820558215582255823558245582555826558275582855829558305583155832558335583455835558365583755838558395584055841558425584355844558455584655847558485584955850558515585255853558545585555856558575585855859558605586155862558635586455865558665586755868558695587055871558725587355874558755587655877558785587955880558815588255883558845588555886558875588855889558905589155892558935589455895558965589755898558995590055901559025590355904559055590655907559085590955910559115591255913559145591555916559175591855919559205592155922559235592455925559265592755928559295593055931559325593355934559355593655937559385593955940559415594255943559445594555946559475594855949559505595155952559535595455955559565595755958559595596055961559625596355964559655596655967559685596955970559715597255973559745597555976559775597855979559805598155982559835598455985559865598755988559895599055991559925599355994559955599655997559985599956000560015600256003560045600556006560075600856009560105601156012560135601456015560165601756018560195602056021560225602356024560255602656027560285602956030560315603256033560345603556036560375603856039560405604156042560435604456045560465604756048560495605056051560525605356054560555605656057560585605956060560615606256063560645606556066560675606856069560705607156072560735607456075560765607756078560795608056081560825608356084560855608656087560885608956090560915609256093560945609556096560975609856099561005610156102561035610456105561065610756108561095611056111561125611356114561155611656117561185611956120561215612256123561245612556126561275612856129561305613156132561335613456135561365613756138561395614056141561425614356144561455614656147561485614956150561515615256153561545615556156561575615856159561605616156162561635616456165561665616756168561695617056171561725617356174561755617656177561785617956180561815618256183561845618556186561875618856189561905619156192561935619456195561965619756198561995620056201562025620356204562055620656207562085620956210562115621256213562145621556216562175621856219562205622156222562235622456225562265622756228562295623056231562325623356234562355623656237562385623956240562415624256243562445624556246562475624856249562505625156252562535625456255562565625756258562595626056261562625626356264562655626656267562685626956270562715627256273562745627556276562775627856279562805628156282562835628456285562865628756288562895629056291562925629356294562955629656297562985629956300563015630256303563045630556306563075630856309563105631156312563135631456315563165631756318563195632056321563225632356324563255632656327563285632956330563315633256333563345633556336563375633856339563405634156342563435634456345563465634756348563495635056351563525635356354563555635656357563585635956360563615636256363563645636556366563675636856369563705637156372563735637456375563765637756378563795638056381563825638356384563855638656387563885638956390563915639256393563945639556396563975639856399564005640156402564035640456405564065640756408564095641056411564125641356414564155641656417564185641956420564215642256423564245642556426564275642856429564305643156432564335643456435564365643756438564395644056441564425644356444564455644656447564485644956450564515645256453564545645556456564575645856459564605646156462564635646456465564665646756468564695647056471564725647356474564755647656477564785647956480564815648256483564845648556486564875648856489564905649156492564935649456495564965649756498564995650056501565025650356504565055650656507565085650956510565115651256513565145651556516565175651856519565205652156522565235652456525565265652756528565295653056531565325653356534565355653656537565385653956540565415654256543565445654556546565475654856549565505655156552565535655456555565565655756558565595656056561565625656356564565655656656567565685656956570565715657256573565745657556576565775657856579565805658156582565835658456585565865658756588565895659056591565925659356594565955659656597565985659956600566015660256603566045660556606566075660856609566105661156612566135661456615566165661756618566195662056621566225662356624566255662656627566285662956630566315663256633566345663556636566375663856639566405664156642566435664456645566465664756648566495665056651566525665356654566555665656657566585665956660566615666256663566645666556666566675666856669566705667156672566735667456675566765667756678566795668056681566825668356684566855668656687566885668956690566915669256693566945669556696566975669856699567005670156702567035670456705567065670756708567095671056711567125671356714567155671656717567185671956720567215672256723567245672556726567275672856729567305673156732567335673456735567365673756738567395674056741567425674356744567455674656747567485674956750567515675256753567545675556756567575675856759567605676156762567635676456765567665676756768567695677056771567725677356774567755677656777567785677956780567815678256783567845678556786567875678856789567905679156792567935679456795567965679756798567995680056801568025680356804568055680656807568085680956810568115681256813568145681556816568175681856819568205682156822568235682456825568265682756828568295683056831568325683356834568355683656837568385683956840568415684256843568445684556846568475684856849568505685156852568535685456855568565685756858568595686056861568625686356864568655686656867568685686956870568715687256873568745687556876568775687856879568805688156882568835688456885568865688756888568895689056891568925689356894568955689656897568985689956900569015690256903569045690556906569075690856909569105691156912569135691456915569165691756918569195692056921569225692356924569255692656927569285692956930569315693256933569345693556936569375693856939569405694156942569435694456945569465694756948569495695056951569525695356954569555695656957569585695956960569615696256963569645696556966569675696856969569705697156972569735697456975569765697756978569795698056981569825698356984569855698656987569885698956990569915699256993569945699556996569975699856999570005700157002570035700457005570065700757008570095701057011570125701357014570155701657017570185701957020570215702257023570245702557026570275702857029570305703157032570335703457035570365703757038570395704057041570425704357044570455704657047570485704957050570515705257053570545705557056570575705857059570605706157062570635706457065570665706757068570695707057071570725707357074570755707657077570785707957080570815708257083570845708557086570875708857089570905709157092570935709457095570965709757098570995710057101571025710357104571055710657107571085710957110571115711257113571145711557116571175711857119571205712157122571235712457125571265712757128571295713057131571325713357134571355713657137571385713957140571415714257143571445714557146571475714857149571505715157152571535715457155571565715757158571595716057161571625716357164571655716657167571685716957170571715717257173571745717557176571775717857179571805718157182571835718457185571865718757188571895719057191571925719357194571955719657197571985719957200572015720257203572045720557206572075720857209572105721157212572135721457215572165721757218572195722057221572225722357224572255722657227572285722957230572315723257233572345723557236572375723857239572405724157242572435724457245572465724757248572495725057251572525725357254572555725657257572585725957260572615726257263572645726557266572675726857269572705727157272572735727457275572765727757278572795728057281572825728357284572855728657287572885728957290572915729257293572945729557296572975729857299573005730157302573035730457305573065730757308573095731057311573125731357314573155731657317573185731957320573215732257323573245732557326573275732857329573305733157332573335733457335573365733757338573395734057341573425734357344573455734657347573485734957350573515735257353573545735557356573575735857359573605736157362573635736457365573665736757368573695737057371573725737357374573755737657377573785737957380573815738257383573845738557386573875738857389573905739157392573935739457395573965739757398573995740057401574025740357404574055740657407574085740957410574115741257413574145741557416574175741857419574205742157422574235742457425574265742757428574295743057431574325743357434574355743657437574385743957440574415744257443574445744557446574475744857449574505745157452574535745457455574565745757458574595746057461574625746357464574655746657467574685746957470574715747257473574745747557476574775747857479574805748157482574835748457485574865748757488574895749057491574925749357494574955749657497574985749957500575015750257503575045750557506575075750857509575105751157512575135751457515575165751757518575195752057521575225752357524575255752657527575285752957530575315753257533575345753557536575375753857539575405754157542575435754457545575465754757548575495755057551575525755357554575555755657557575585755957560575615756257563575645756557566575675756857569575705757157572575735757457575575765757757578575795758057581575825758357584575855758657587575885758957590575915759257593575945759557596575975759857599576005760157602576035760457605576065760757608576095761057611576125761357614576155761657617576185761957620576215762257623576245762557626576275762857629576305763157632576335763457635576365763757638576395764057641576425764357644576455764657647576485764957650576515765257653576545765557656576575765857659576605766157662576635766457665576665766757668576695767057671576725767357674576755767657677576785767957680576815768257683576845768557686576875768857689576905769157692576935769457695576965769757698576995770057701577025770357704577055770657707577085770957710577115771257713577145771557716577175771857719577205772157722577235772457725577265772757728577295773057731577325773357734577355773657737577385773957740577415774257743577445774557746577475774857749577505775157752577535775457755577565775757758577595776057761577625776357764577655776657767577685776957770577715777257773577745777557776577775777857779577805778157782577835778457785577865778757788577895779057791577925779357794577955779657797577985779957800578015780257803578045780557806578075780857809578105781157812578135781457815578165781757818578195782057821578225782357824578255782657827578285782957830578315783257833578345783557836578375783857839578405784157842578435784457845578465784757848578495785057851578525785357854578555785657857578585785957860578615786257863578645786557866578675786857869578705787157872578735787457875578765787757878578795788057881578825788357884578855788657887578885788957890578915789257893578945789557896578975789857899579005790157902579035790457905579065790757908579095791057911579125791357914579155791657917579185791957920579215792257923579245792557926579275792857929579305793157932579335793457935579365793757938579395794057941579425794357944579455794657947579485794957950579515795257953579545795557956579575795857959579605796157962579635796457965579665796757968579695797057971579725797357974579755797657977579785797957980579815798257983579845798557986579875798857989579905799157992579935799457995579965799757998579995800058001580025800358004580055800658007580085800958010580115801258013580145801558016580175801858019580205802158022580235802458025580265802758028580295803058031580325803358034580355803658037580385803958040580415804258043580445804558046580475804858049580505805158052580535805458055580565805758058580595806058061580625806358064580655806658067580685806958070580715807258073580745807558076580775807858079580805808158082580835808458085580865808758088580895809058091580925809358094580955809658097580985809958100581015810258103581045810558106581075810858109581105811158112581135811458115581165811758118581195812058121581225812358124581255812658127581285812958130581315813258133581345813558136581375813858139581405814158142581435814458145581465814758148581495815058151581525815358154581555815658157581585815958160581615816258163581645816558166581675816858169581705817158172581735817458175581765817758178581795818058181581825818358184581855818658187581885818958190581915819258193581945819558196581975819858199582005820158202582035820458205582065820758208582095821058211582125821358214582155821658217582185821958220582215822258223582245822558226582275822858229582305823158232582335823458235582365823758238582395824058241582425824358244582455824658247582485824958250582515825258253582545825558256582575825858259582605826158262582635826458265582665826758268582695827058271582725827358274582755827658277582785827958280582815828258283582845828558286582875828858289582905829158292582935829458295582965829758298582995830058301583025830358304583055830658307583085830958310583115831258313583145831558316583175831858319583205832158322583235832458325583265832758328583295833058331583325833358334583355833658337583385833958340583415834258343583445834558346583475834858349583505835158352583535835458355583565835758358583595836058361583625836358364583655836658367583685836958370583715837258373583745837558376583775837858379583805838158382583835838458385583865838758388583895839058391583925839358394583955839658397583985839958400584015840258403584045840558406584075840858409584105841158412584135841458415584165841758418584195842058421584225842358424584255842658427584285842958430584315843258433584345843558436584375843858439584405844158442584435844458445584465844758448584495845058451584525845358454584555845658457584585845958460584615846258463584645846558466584675846858469584705847158472584735847458475584765847758478584795848058481584825848358484584855848658487584885848958490584915849258493584945849558496584975849858499585005850158502585035850458505585065850758508585095851058511585125851358514585155851658517585185851958520585215852258523585245852558526585275852858529585305853158532585335853458535585365853758538585395854058541585425854358544585455854658547585485854958550585515855258553585545855558556585575855858559585605856158562585635856458565585665856758568585695857058571585725857358574585755857658577585785857958580585815858258583585845858558586585875858858589585905859158592585935859458595585965859758598585995860058601586025860358604586055860658607586085860958610586115861258613586145861558616586175861858619586205862158622586235862458625586265862758628586295863058631586325863358634586355863658637586385863958640586415864258643586445864558646586475864858649586505865158652586535865458655586565865758658586595866058661586625866358664586655866658667586685866958670586715867258673586745867558676586775867858679586805868158682586835868458685586865868758688586895869058691586925869358694586955869658697586985869958700587015870258703587045870558706587075870858709587105871158712587135871458715587165871758718587195872058721587225872358724587255872658727587285872958730587315873258733587345873558736587375873858739587405874158742587435874458745587465874758748587495875058751587525875358754587555875658757587585875958760587615876258763587645876558766587675876858769587705877158772587735877458775587765877758778587795878058781587825878358784587855878658787587885878958790587915879258793587945879558796587975879858799588005880158802588035880458805588065880758808588095881058811588125881358814588155881658817588185881958820588215882258823588245882558826588275882858829588305883158832588335883458835588365883758838588395884058841588425884358844588455884658847588485884958850588515885258853588545885558856588575885858859588605886158862588635886458865588665886758868588695887058871588725887358874588755887658877588785887958880588815888258883588845888558886588875888858889588905889158892588935889458895588965889758898588995890058901589025890358904589055890658907589085890958910589115891258913589145891558916589175891858919589205892158922589235892458925589265892758928589295893058931589325893358934589355893658937589385893958940589415894258943589445894558946589475894858949589505895158952589535895458955589565895758958589595896058961589625896358964589655896658967589685896958970589715897258973589745897558976589775897858979589805898158982589835898458985589865898758988589895899058991589925899358994589955899658997589985899959000590015900259003590045900559006590075900859009590105901159012590135901459015590165901759018590195902059021590225902359024590255902659027590285902959030590315903259033590345903559036590375903859039590405904159042590435904459045590465904759048590495905059051590525905359054590555905659057590585905959060590615906259063590645906559066590675906859069590705907159072590735907459075590765907759078590795908059081590825908359084590855908659087590885908959090590915909259093590945909559096590975909859099591005910159102591035910459105591065910759108591095911059111591125911359114591155911659117591185911959120591215912259123591245912559126591275912859129591305913159132591335913459135591365913759138591395914059141591425914359144591455914659147591485914959150591515915259153591545915559156591575915859159591605916159162591635916459165591665916759168591695917059171591725917359174591755917659177591785917959180591815918259183591845918559186591875918859189591905919159192591935919459195591965919759198591995920059201592025920359204592055920659207592085920959210592115921259213592145921559216592175921859219592205922159222592235922459225592265922759228592295923059231592325923359234592355923659237592385923959240592415924259243592445924559246592475924859249592505925159252592535925459255592565925759258592595926059261592625926359264592655926659267592685926959270592715927259273592745927559276592775927859279592805928159282592835928459285592865928759288592895929059291592925929359294592955929659297592985929959300593015930259303593045930559306593075930859309593105931159312593135931459315593165931759318593195932059321593225932359324593255932659327593285932959330593315933259333593345933559336593375933859339593405934159342593435934459345593465934759348593495935059351593525935359354593555935659357593585935959360593615936259363593645936559366593675936859369593705937159372593735937459375593765937759378593795938059381593825938359384593855938659387593885938959390593915939259393593945939559396593975939859399594005940159402594035940459405594065940759408594095941059411594125941359414594155941659417594185941959420594215942259423594245942559426594275942859429594305943159432594335943459435594365943759438594395944059441594425944359444594455944659447594485944959450594515945259453594545945559456594575945859459594605946159462594635946459465594665946759468594695947059471594725947359474594755947659477594785947959480594815948259483594845948559486594875948859489594905949159492594935949459495594965949759498594995950059501595025950359504595055950659507595085950959510595115951259513595145951559516595175951859519595205952159522595235952459525595265952759528595295953059531595325953359534595355953659537595385953959540595415954259543595445954559546595475954859549595505955159552595535955459555595565955759558595595956059561595625956359564595655956659567595685956959570595715957259573595745957559576595775957859579595805958159582595835958459585595865958759588595895959059591595925959359594595955959659597595985959959600596015960259603596045960559606596075960859609596105961159612596135961459615596165961759618596195962059621596225962359624596255962659627596285962959630596315963259633596345963559636596375963859639596405964159642596435964459645596465964759648596495965059651596525965359654596555965659657596585965959660596615966259663596645966559666596675966859669596705967159672596735967459675596765967759678596795968059681596825968359684596855968659687596885968959690596915969259693596945969559696596975969859699597005970159702597035970459705597065970759708597095971059711597125971359714597155971659717597185971959720597215972259723597245972559726597275972859729597305973159732597335973459735597365973759738597395974059741597425974359744597455974659747597485974959750597515975259753597545975559756597575975859759597605976159762597635976459765597665976759768597695977059771597725977359774597755977659777597785977959780597815978259783597845978559786597875978859789597905979159792597935979459795597965979759798597995980059801598025980359804598055980659807598085980959810598115981259813598145981559816598175981859819598205982159822598235982459825598265982759828598295983059831598325983359834598355983659837598385983959840598415984259843598445984559846598475984859849598505985159852598535985459855598565985759858598595986059861598625986359864598655986659867598685986959870598715987259873598745987559876598775987859879598805988159882598835988459885598865988759888598895989059891598925989359894598955989659897598985989959900599015990259903599045990559906599075990859909599105991159912599135991459915599165991759918599195992059921599225992359924599255992659927599285992959930599315993259933599345993559936599375993859939599405994159942599435994459945599465994759948599495995059951599525995359954599555995659957599585995959960599615996259963599645996559966599675996859969599705997159972599735997459975599765997759978599795998059981599825998359984599855998659987599885998959990599915999259993599945999559996599975999859999600006000160002600036000460005600066000760008600096001060011600126001360014600156001660017600186001960020600216002260023600246002560026600276002860029600306003160032600336003460035600366003760038600396004060041600426004360044600456004660047600486004960050600516005260053600546005560056600576005860059600606006160062600636006460065600666006760068600696007060071600726007360074600756007660077600786007960080600816008260083600846008560086600876008860089600906009160092600936009460095600966009760098600996010060101601026010360104601056010660107601086010960110601116011260113601146011560116601176011860119601206012160122601236012460125601266012760128601296013060131601326013360134601356013660137601386013960140601416014260143601446014560146601476014860149601506015160152601536015460155601566015760158601596016060161601626016360164601656016660167601686016960170601716017260173601746017560176601776017860179601806018160182601836018460185601866018760188601896019060191601926019360194601956019660197601986019960200602016020260203602046020560206602076020860209602106021160212602136021460215602166021760218602196022060221602226022360224602256022660227602286022960230602316023260233602346023560236602376023860239602406024160242602436024460245602466024760248602496025060251602526025360254602556025660257602586025960260602616026260263602646026560266602676026860269602706027160272602736027460275602766027760278602796028060281602826028360284602856028660287602886028960290602916029260293602946029560296602976029860299603006030160302603036030460305603066030760308603096031060311603126031360314603156031660317603186031960320603216032260323603246032560326603276032860329603306033160332603336033460335603366033760338603396034060341603426034360344603456034660347603486034960350603516035260353603546035560356603576035860359603606036160362603636036460365603666036760368603696037060371603726037360374603756037660377603786037960380603816038260383603846038560386603876038860389603906039160392603936039460395603966039760398603996040060401604026040360404604056040660407604086040960410604116041260413604146041560416604176041860419604206042160422604236042460425604266042760428604296043060431604326043360434604356043660437604386043960440604416044260443604446044560446604476044860449604506045160452604536045460455604566045760458604596046060461604626046360464604656046660467604686046960470604716047260473604746047560476604776047860479604806048160482604836048460485604866048760488604896049060491604926049360494604956049660497604986049960500605016050260503605046050560506605076050860509605106051160512605136051460515605166051760518605196052060521605226052360524605256052660527605286052960530605316053260533605346053560536605376053860539605406054160542605436054460545605466054760548605496055060551605526055360554605556055660557605586055960560605616056260563605646056560566605676056860569605706057160572605736057460575605766057760578605796058060581605826058360584605856058660587605886058960590605916059260593605946059560596605976059860599606006060160602606036060460605606066060760608606096061060611606126061360614606156061660617606186061960620606216062260623606246062560626606276062860629606306063160632606336063460635606366063760638606396064060641606426064360644606456064660647606486064960650606516065260653606546065560656606576065860659606606066160662606636066460665606666066760668606696067060671606726067360674606756067660677606786067960680606816068260683606846068560686606876068860689606906069160692606936069460695606966069760698606996070060701607026070360704607056070660707607086070960710607116071260713607146071560716607176071860719607206072160722607236072460725607266072760728607296073060731607326073360734607356073660737607386073960740607416074260743607446074560746607476074860749607506075160752607536075460755607566075760758607596076060761607626076360764607656076660767607686076960770607716077260773607746077560776607776077860779607806078160782607836078460785607866078760788607896079060791607926079360794607956079660797607986079960800608016080260803608046080560806608076080860809608106081160812608136081460815608166081760818608196082060821608226082360824608256082660827608286082960830608316083260833608346083560836608376083860839608406084160842608436084460845608466084760848608496085060851608526085360854608556085660857608586085960860608616086260863608646086560866608676086860869608706087160872608736087460875608766087760878608796088060881608826088360884608856088660887608886088960890608916089260893608946089560896608976089860899609006090160902609036090460905609066090760908609096091060911609126091360914609156091660917609186091960920609216092260923609246092560926609276092860929609306093160932609336093460935609366093760938609396094060941609426094360944609456094660947609486094960950609516095260953609546095560956609576095860959609606096160962609636096460965609666096760968609696097060971609726097360974609756097660977609786097960980609816098260983609846098560986609876098860989609906099160992609936099460995609966099760998609996100061001610026100361004610056100661007610086100961010610116101261013610146101561016610176101861019610206102161022610236102461025610266102761028610296103061031610326103361034610356103661037610386103961040610416104261043610446104561046610476104861049610506105161052610536105461055610566105761058610596106061061610626106361064610656106661067610686106961070610716107261073610746107561076610776107861079610806108161082610836108461085610866108761088610896109061091610926109361094610956109661097610986109961100611016110261103611046110561106611076110861109611106111161112611136111461115611166111761118611196112061121611226112361124611256112661127611286112961130611316113261133611346113561136611376113861139611406114161142611436114461145611466114761148611496115061151611526115361154611556115661157611586115961160611616116261163611646116561166611676116861169611706117161172611736117461175611766117761178611796118061181611826118361184611856118661187611886118961190611916119261193611946119561196611976119861199612006120161202612036120461205612066120761208612096121061211612126121361214612156121661217612186121961220612216122261223612246122561226612276122861229612306123161232612336123461235612366123761238612396124061241612426124361244612456124661247612486124961250612516125261253612546125561256612576125861259612606126161262612636126461265612666126761268612696127061271612726127361274612756127661277612786127961280612816128261283612846128561286612876128861289612906129161292612936129461295612966129761298612996130061301613026130361304613056130661307613086130961310613116131261313613146131561316613176131861319613206132161322613236132461325613266132761328613296133061331613326133361334613356133661337613386133961340613416134261343613446134561346613476134861349613506135161352613536135461355613566135761358613596136061361613626136361364613656136661367613686136961370613716137261373613746137561376613776137861379613806138161382613836138461385613866138761388613896139061391613926139361394613956139661397613986139961400614016140261403614046140561406614076140861409614106141161412614136141461415614166141761418614196142061421614226142361424614256142661427614286142961430614316143261433614346143561436614376143861439614406144161442614436144461445614466144761448614496145061451614526145361454614556145661457614586145961460614616146261463614646146561466614676146861469614706147161472614736147461475614766147761478614796148061481614826148361484614856148661487614886148961490614916149261493614946149561496614976149861499615006150161502615036150461505615066150761508615096151061511615126151361514615156151661517615186151961520615216152261523615246152561526615276152861529615306153161532615336153461535615366153761538615396154061541615426154361544615456154661547615486154961550615516155261553615546155561556615576155861559615606156161562615636156461565615666156761568615696157061571615726157361574615756157661577615786157961580615816158261583615846158561586615876158861589615906159161592615936159461595615966159761598615996160061601616026160361604616056160661607616086160961610616116161261613616146161561616616176161861619616206162161622616236162461625616266162761628616296163061631616326163361634616356163661637616386163961640616416164261643616446164561646616476164861649616506165161652616536165461655616566165761658616596166061661616626166361664616656166661667616686166961670616716167261673616746167561676616776167861679616806168161682616836168461685616866168761688616896169061691616926169361694616956169661697616986169961700617016170261703617046170561706617076170861709617106171161712617136171461715617166171761718617196172061721617226172361724617256172661727617286172961730617316173261733617346173561736617376173861739617406174161742617436174461745617466174761748617496175061751617526175361754617556175661757617586175961760617616176261763617646176561766617676176861769617706177161772617736177461775617766177761778617796178061781617826178361784617856178661787617886178961790617916179261793617946179561796617976179861799618006180161802618036180461805618066180761808618096181061811618126181361814618156181661817618186181961820618216182261823618246182561826618276182861829618306183161832618336183461835618366183761838618396184061841618426184361844618456184661847618486184961850618516185261853618546185561856618576185861859618606186161862618636186461865618666186761868618696187061871618726187361874618756187661877618786187961880618816188261883618846188561886618876188861889618906189161892618936189461895618966189761898618996190061901619026190361904619056190661907619086190961910619116191261913619146191561916619176191861919619206192161922619236192461925619266192761928619296193061931619326193361934619356193661937619386193961940619416194261943619446194561946619476194861949619506195161952619536195461955619566195761958619596196061961619626196361964619656196661967619686196961970619716197261973619746197561976619776197861979619806198161982619836198461985619866198761988619896199061991619926199361994619956199661997619986199962000620016200262003620046200562006620076200862009620106201162012620136201462015620166201762018620196202062021620226202362024620256202662027620286202962030620316203262033620346203562036620376203862039620406204162042620436204462045620466204762048620496205062051620526205362054620556205662057620586205962060620616206262063620646206562066620676206862069620706207162072620736207462075620766207762078620796208062081620826208362084620856208662087620886208962090620916209262093620946209562096620976209862099621006210162102621036210462105621066210762108621096211062111621126211362114621156211662117621186211962120621216212262123621246212562126621276212862129621306213162132621336213462135621366213762138621396214062141621426214362144621456214662147621486214962150621516215262153621546215562156621576215862159621606216162162621636216462165621666216762168621696217062171621726217362174621756217662177621786217962180621816218262183621846218562186621876218862189621906219162192621936219462195621966219762198621996220062201622026220362204622056220662207622086220962210622116221262213622146221562216622176221862219622206222162222622236222462225622266222762228622296223062231622326223362234622356223662237622386223962240622416224262243622446224562246622476224862249622506225162252622536225462255622566225762258622596226062261622626226362264622656226662267622686226962270622716227262273622746227562276622776227862279622806228162282622836228462285622866228762288622896229062291622926229362294622956229662297622986229962300623016230262303623046230562306623076230862309623106231162312623136231462315623166231762318623196232062321623226232362324623256232662327623286232962330623316233262333623346233562336623376233862339623406234162342623436234462345623466234762348623496235062351623526235362354623556235662357623586235962360623616236262363623646236562366623676236862369623706237162372623736237462375623766237762378623796238062381623826238362384623856238662387623886238962390623916239262393623946239562396623976239862399624006240162402624036240462405624066240762408624096241062411624126241362414624156241662417624186241962420624216242262423624246242562426624276242862429624306243162432624336243462435624366243762438624396244062441624426244362444624456244662447624486244962450624516245262453624546245562456624576245862459624606246162462624636246462465624666246762468624696247062471624726247362474624756247662477624786247962480624816248262483624846248562486624876248862489624906249162492624936249462495624966249762498624996250062501625026250362504625056250662507625086250962510625116251262513625146251562516625176251862519625206252162522625236252462525625266252762528625296253062531625326253362534625356253662537625386253962540625416254262543625446254562546625476254862549625506255162552625536255462555625566255762558625596256062561625626256362564625656256662567625686256962570625716257262573625746257562576625776257862579625806258162582625836258462585625866258762588625896259062591625926259362594625956259662597625986259962600626016260262603626046260562606626076260862609626106261162612626136261462615626166261762618626196262062621626226262362624626256262662627626286262962630626316263262633626346263562636626376263862639626406264162642626436264462645626466264762648626496265062651626526265362654626556265662657626586265962660626616266262663626646266562666626676266862669626706267162672626736267462675626766267762678626796268062681626826268362684626856268662687626886268962690626916269262693626946269562696626976269862699627006270162702627036270462705627066270762708627096271062711627126271362714627156271662717627186271962720627216272262723627246272562726627276272862729627306273162732627336273462735627366273762738627396274062741627426274362744627456274662747627486274962750627516275262753627546275562756627576275862759627606276162762627636276462765627666276762768627696277062771627726277362774627756277662777627786277962780627816278262783627846278562786627876278862789627906279162792627936279462795627966279762798627996280062801628026280362804628056280662807628086280962810628116281262813628146281562816628176281862819628206282162822628236282462825628266282762828628296283062831628326283362834628356283662837628386283962840628416284262843628446284562846628476284862849628506285162852628536285462855628566285762858628596286062861628626286362864628656286662867628686286962870628716287262873628746287562876628776287862879628806288162882628836288462885628866288762888628896289062891628926289362894628956289662897628986289962900629016290262903629046290562906629076290862909629106291162912629136291462915629166291762918629196292062921629226292362924629256292662927629286292962930629316293262933629346293562936629376293862939629406294162942629436294462945629466294762948629496295062951629526295362954629556295662957629586295962960629616296262963629646296562966629676296862969629706297162972629736297462975629766297762978629796298062981629826298362984629856298662987629886298962990629916299262993629946299562996629976299862999630006300163002630036300463005630066300763008630096301063011630126301363014630156301663017630186301963020630216302263023630246302563026630276302863029630306303163032630336303463035630366303763038630396304063041630426304363044630456304663047630486304963050630516305263053630546305563056630576305863059630606306163062630636306463065630666306763068630696307063071630726307363074630756307663077630786307963080630816308263083630846308563086630876308863089630906309163092630936309463095630966309763098630996310063101631026310363104631056310663107631086310963110631116311263113631146311563116631176311863119631206312163122631236312463125631266312763128631296313063131631326313363134631356313663137631386313963140631416314263143631446314563146631476314863149631506315163152631536315463155631566315763158631596316063161631626316363164631656316663167631686316963170631716317263173631746317563176631776317863179631806318163182631836318463185631866318763188631896319063191631926319363194631956319663197631986319963200632016320263203632046320563206632076320863209632106321163212632136321463215632166321763218632196322063221632226322363224632256322663227632286322963230632316323263233632346323563236632376323863239632406324163242632436324463245632466324763248632496325063251632526325363254632556325663257632586325963260632616326263263632646326563266632676326863269632706327163272632736327463275632766327763278632796328063281632826328363284632856328663287632886328963290632916329263293632946329563296632976329863299633006330163302633036330463305633066330763308633096331063311633126331363314633156331663317633186331963320633216332263323633246332563326633276332863329633306333163332633336333463335633366333763338633396334063341633426334363344633456334663347633486334963350633516335263353633546335563356633576335863359633606336163362633636336463365633666336763368633696337063371633726337363374633756337663377633786337963380633816338263383633846338563386633876338863389633906339163392633936339463395633966339763398633996340063401634026340363404634056340663407634086340963410634116341263413634146341563416634176341863419634206342163422634236342463425634266342763428634296343063431634326343363434634356343663437634386343963440634416344263443634446344563446634476344863449634506345163452634536345463455634566345763458634596346063461634626346363464634656346663467634686346963470634716347263473634746347563476634776347863479634806348163482634836348463485634866348763488634896349063491634926349363494634956349663497634986349963500635016350263503635046350563506635076350863509635106351163512635136351463515635166351763518635196352063521635226352363524635256352663527635286352963530635316353263533635346353563536635376353863539635406354163542635436354463545635466354763548635496355063551635526355363554635556355663557635586355963560635616356263563635646356563566635676356863569635706357163572635736357463575635766357763578635796358063581635826358363584635856358663587635886358963590635916359263593635946359563596635976359863599636006360163602636036360463605636066360763608636096361063611636126361363614636156361663617636186361963620636216362263623636246362563626636276362863629636306363163632636336363463635636366363763638636396364063641636426364363644636456364663647636486364963650636516365263653636546365563656636576365863659636606366163662636636366463665636666366763668636696367063671636726367363674636756367663677636786367963680636816368263683636846368563686636876368863689636906369163692636936369463695636966369763698636996370063701637026370363704637056370663707637086370963710637116371263713637146371563716637176371863719637206372163722637236372463725637266372763728637296373063731637326373363734637356373663737637386373963740637416374263743637446374563746637476374863749637506375163752637536375463755637566375763758637596376063761637626376363764637656376663767637686376963770637716377263773637746377563776637776377863779637806378163782637836378463785637866378763788637896379063791637926379363794637956379663797637986379963800638016380263803638046380563806638076380863809638106381163812638136381463815638166381763818638196382063821638226382363824638256382663827638286382963830638316383263833638346383563836638376383863839638406384163842638436384463845638466384763848638496385063851638526385363854638556385663857638586385963860638616386263863638646386563866638676386863869638706387163872638736387463875638766387763878638796388063881638826388363884638856388663887638886388963890638916389263893638946389563896638976389863899639006390163902639036390463905639066390763908639096391063911639126391363914639156391663917639186391963920639216392263923639246392563926639276392863929639306393163932639336393463935639366393763938639396394063941639426394363944639456394663947639486394963950639516395263953639546395563956639576395863959639606396163962639636396463965639666396763968639696397063971639726397363974639756397663977639786397963980639816398263983639846398563986639876398863989639906399163992639936399463995639966399763998639996400064001640026400364004640056400664007640086400964010640116401264013640146401564016640176401864019640206402164022640236402464025640266402764028640296403064031640326403364034640356403664037640386403964040640416404264043640446404564046640476404864049640506405164052640536405464055640566405764058640596406064061640626406364064640656406664067640686406964070640716407264073640746407564076640776407864079640806408164082640836408464085640866408764088640896409064091640926409364094640956409664097640986409964100641016410264103641046410564106641076410864109641106411164112641136411464115641166411764118641196412064121641226412364124641256412664127641286412964130641316413264133641346413564136641376413864139641406414164142641436414464145641466414764148641496415064151641526415364154641556415664157641586415964160641616416264163641646416564166641676416864169641706417164172641736417464175641766417764178641796418064181641826418364184641856418664187641886418964190641916419264193641946419564196641976419864199642006420164202642036420464205642066420764208642096421064211642126421364214642156421664217642186421964220642216422264223642246422564226642276422864229642306423164232642336423464235642366423764238642396424064241642426424364244642456424664247642486424964250642516425264253642546425564256642576425864259642606426164262642636426464265642666426764268642696427064271642726427364274642756427664277642786427964280642816428264283642846428564286642876428864289642906429164292642936429464295642966429764298642996430064301643026430364304643056430664307643086430964310643116431264313643146431564316643176431864319643206432164322643236432464325643266432764328643296433064331643326433364334643356433664337643386433964340643416434264343643446434564346643476434864349643506435164352643536435464355643566435764358643596436064361643626436364364643656436664367643686436964370643716437264373643746437564376643776437864379643806438164382643836438464385643866438764388643896439064391643926439364394643956439664397643986439964400644016440264403644046440564406644076440864409644106441164412644136441464415644166441764418644196442064421644226442364424644256442664427644286442964430644316443264433644346443564436644376443864439644406444164442644436444464445644466444764448644496445064451644526445364454644556445664457644586445964460644616446264463644646446564466644676446864469644706447164472644736447464475644766447764478644796448064481644826448364484644856448664487644886448964490644916449264493644946449564496644976449864499645006450164502645036450464505645066450764508645096451064511645126451364514645156451664517645186451964520645216452264523645246452564526645276452864529645306453164532645336453464535645366453764538645396454064541645426454364544645456454664547645486454964550645516455264553645546455564556645576455864559645606456164562645636456464565645666456764568645696457064571645726457364574645756457664577645786457964580645816458264583645846458564586645876458864589645906459164592645936459464595645966459764598645996460064601646026460364604646056460664607646086460964610646116461264613646146461564616646176461864619646206462164622646236462464625646266462764628646296463064631646326463364634646356463664637646386463964640646416464264643646446464564646646476464864649646506465164652646536465464655646566465764658646596466064661646626466364664646656466664667646686466964670646716467264673646746467564676646776467864679646806468164682646836468464685646866468764688646896469064691646926469364694646956469664697646986469964700647016470264703647046470564706647076470864709647106471164712647136471464715647166471764718647196472064721647226472364724647256472664727647286472964730647316473264733647346473564736647376473864739647406474164742647436474464745647466474764748647496475064751647526475364754647556475664757647586475964760647616476264763647646476564766647676476864769647706477164772647736477464775647766477764778647796478064781647826478364784647856478664787647886478964790647916479264793647946479564796647976479864799648006480164802648036480464805648066480764808648096481064811648126481364814648156481664817648186481964820648216482264823648246482564826648276482864829648306483164832648336483464835648366483764838648396484064841648426484364844648456484664847648486484964850648516485264853648546485564856648576485864859648606486164862648636486464865648666486764868648696487064871648726487364874648756487664877648786487964880648816488264883648846488564886648876488864889648906489164892648936489464895648966489764898648996490064901649026490364904649056490664907649086490964910649116491264913649146491564916649176491864919649206492164922649236492464925649266492764928649296493064931649326493364934649356493664937649386493964940649416494264943649446494564946649476494864949649506495164952649536495464955649566495764958649596496064961649626496364964649656496664967649686496964970649716497264973649746497564976649776497864979649806498164982649836498464985649866498764988649896499064991649926499364994649956499664997649986499965000650016500265003650046500565006650076500865009650106501165012650136501465015650166501765018650196502065021650226502365024650256502665027650286502965030650316503265033650346503565036650376503865039650406504165042650436504465045650466504765048650496505065051650526505365054650556505665057650586505965060650616506265063650646506565066650676506865069650706507165072650736507465075650766507765078650796508065081650826508365084650856508665087650886508965090650916509265093650946509565096650976509865099651006510165102651036510465105651066510765108651096511065111651126511365114651156511665117651186511965120651216512265123651246512565126651276512865129651306513165132651336513465135651366513765138651396514065141651426514365144651456514665147651486514965150651516515265153651546515565156651576515865159651606516165162651636516465165651666516765168651696517065171651726517365174651756517665177651786517965180651816518265183651846518565186651876518865189651906519165192651936519465195651966519765198651996520065201652026520365204652056520665207652086520965210652116521265213652146521565216652176521865219652206522165222652236522465225652266522765228652296523065231652326523365234652356523665237652386523965240652416524265243652446524565246652476524865249652506525165252652536525465255652566525765258652596526065261652626526365264652656526665267652686526965270652716527265273652746527565276652776527865279652806528165282652836528465285652866528765288652896529065291652926529365294652956529665297652986529965300653016530265303653046530565306653076530865309653106531165312653136531465315653166531765318653196532065321653226532365324653256532665327653286532965330653316533265333653346533565336653376533865339653406534165342653436534465345653466534765348653496535065351653526535365354653556535665357653586535965360653616536265363653646536565366653676536865369653706537165372653736537465375653766537765378653796538065381653826538365384653856538665387653886538965390653916539265393653946539565396653976539865399654006540165402654036540465405654066540765408654096541065411654126541365414654156541665417654186541965420654216542265423654246542565426654276542865429654306543165432654336543465435654366543765438654396544065441654426544365444654456544665447654486544965450654516545265453654546545565456654576545865459654606546165462654636546465465654666546765468654696547065471654726547365474654756547665477654786547965480654816548265483654846548565486654876548865489654906549165492654936549465495654966549765498654996550065501655026550365504655056550665507655086550965510655116551265513655146551565516655176551865519655206552165522655236552465525655266552765528655296553065531655326553365534655356553665537655386553965540655416554265543655446554565546655476554865549655506555165552655536555465555655566555765558655596556065561655626556365564655656556665567655686556965570655716557265573655746557565576655776557865579655806558165582655836558465585655866558765588655896559065591655926559365594655956559665597655986559965600656016560265603656046560565606656076560865609656106561165612656136561465615656166561765618656196562065621656226562365624656256562665627656286562965630656316563265633656346563565636656376563865639656406564165642656436564465645656466564765648656496565065651656526565365654656556565665657656586565965660656616566265663656646566565666656676566865669656706567165672656736567465675656766567765678656796568065681656826568365684656856568665687656886568965690656916569265693656946569565696656976569865699657006570165702657036570465705657066570765708657096571065711657126571365714657156571665717657186571965720657216572265723657246572565726657276572865729657306573165732657336573465735657366573765738657396574065741657426574365744657456574665747657486574965750657516575265753657546575565756657576575865759657606576165762657636576465765657666576765768657696577065771657726577365774657756577665777657786577965780657816578265783657846578565786657876578865789657906579165792657936579465795657966579765798657996580065801658026580365804658056580665807658086580965810658116581265813658146581565816658176581865819658206582165822658236582465825658266582765828658296583065831658326583365834658356583665837658386583965840658416584265843658446584565846658476584865849658506585165852658536585465855658566585765858658596586065861658626586365864658656586665867658686586965870658716587265873658746587565876658776587865879658806588165882658836588465885658866588765888658896589065891658926589365894658956589665897658986589965900659016590265903659046590565906659076590865909659106591165912659136591465915659166591765918659196592065921659226592365924659256592665927659286592965930659316593265933659346593565936659376593865939659406594165942659436594465945659466594765948659496595065951659526595365954659556595665957659586595965960659616596265963659646596565966659676596865969659706597165972659736597465975659766597765978659796598065981659826598365984659856598665987659886598965990659916599265993659946599565996659976599865999660006600166002660036600466005660066600766008660096601066011660126601366014660156601666017660186601966020660216602266023660246602566026660276602866029660306603166032660336603466035660366603766038660396604066041660426604366044660456604666047660486604966050660516605266053660546605566056660576605866059660606606166062660636606466065660666606766068660696607066071660726607366074660756607666077660786607966080660816608266083660846608566086660876608866089660906609166092660936609466095660966609766098660996610066101661026610366104661056610666107661086610966110661116611266113661146611566116661176611866119661206612166122661236612466125661266612766128661296613066131661326613366134661356613666137661386613966140661416614266143661446614566146661476614866149661506615166152661536615466155661566615766158661596616066161661626616366164661656616666167661686616966170661716617266173661746617566176661776617866179661806618166182661836618466185661866618766188661896619066191661926619366194661956619666197661986619966200662016620266203662046620566206662076620866209662106621166212662136621466215662166621766218662196622066221662226622366224662256622666227662286622966230662316623266233662346623566236662376623866239662406624166242662436624466245662466624766248662496625066251662526625366254662556625666257662586625966260662616626266263662646626566266662676626866269662706627166272662736627466275662766627766278662796628066281662826628366284662856628666287662886628966290662916629266293662946629566296662976629866299663006630166302663036630466305663066630766308663096631066311663126631366314663156631666317663186631966320663216632266323663246632566326663276632866329663306633166332663336633466335663366633766338663396634066341663426634366344663456634666347663486634966350663516635266353663546635566356663576635866359663606636166362663636636466365663666636766368663696637066371663726637366374663756637666377663786637966380663816638266383663846638566386663876638866389663906639166392663936639466395663966639766398663996640066401664026640366404664056640666407664086640966410664116641266413664146641566416664176641866419664206642166422664236642466425664266642766428664296643066431664326643366434664356643666437664386643966440664416644266443664446644566446664476644866449664506645166452664536645466455664566645766458664596646066461664626646366464664656646666467664686646966470664716647266473664746647566476664776647866479664806648166482664836648466485664866648766488664896649066491664926649366494664956649666497664986649966500665016650266503665046650566506665076650866509665106651166512665136651466515665166651766518665196652066521665226652366524665256652666527665286652966530665316653266533665346653566536665376653866539665406654166542665436654466545665466654766548665496655066551665526655366554665556655666557665586655966560665616656266563665646656566566665676656866569665706657166572665736657466575665766657766578665796658066581665826658366584665856658666587665886658966590665916659266593665946659566596665976659866599666006660166602666036660466605666066660766608666096661066611666126661366614666156661666617666186661966620666216662266623666246662566626666276662866629666306663166632666336663466635666366663766638666396664066641666426664366644666456664666647666486664966650666516665266653666546665566656666576665866659666606666166662666636666466665666666666766668666696667066671666726667366674666756667666677666786667966680666816668266683666846668566686666876668866689666906669166692666936669466695666966669766698666996670066701667026670366704667056670666707667086670966710667116671266713667146671566716667176671866719667206672166722667236672466725667266672766728667296673066731667326673366734667356673666737667386673966740667416674266743667446674566746667476674866749667506675166752667536675466755667566675766758667596676066761667626676366764667656676666767667686676966770667716677266773667746677566776667776677866779667806678166782667836678466785667866678766788667896679066791667926679366794667956679666797667986679966800668016680266803668046680566806668076680866809668106681166812668136681466815668166681766818668196682066821668226682366824668256682666827668286682966830668316683266833668346683566836668376683866839668406684166842668436684466845668466684766848668496685066851668526685366854668556685666857668586685966860668616686266863668646686566866668676686866869668706687166872668736687466875668766687766878668796688066881668826688366884668856688666887668886688966890668916689266893668946689566896668976689866899669006690166902669036690466905669066690766908669096691066911669126691366914669156691666917669186691966920669216692266923669246692566926669276692866929669306693166932669336693466935669366693766938669396694066941669426694366944669456694666947669486694966950669516695266953669546695566956669576695866959669606696166962669636696466965669666696766968669696697066971669726697366974669756697666977669786697966980669816698266983669846698566986669876698866989669906699166992669936699466995669966699766998669996700067001670026700367004670056700667007670086700967010670116701267013670146701567016670176701867019670206702167022670236702467025670266702767028670296703067031670326703367034670356703667037670386703967040670416704267043670446704567046670476704867049670506705167052670536705467055670566705767058670596706067061670626706367064670656706667067670686706967070670716707267073670746707567076670776707867079670806708167082670836708467085670866708767088670896709067091670926709367094670956709667097670986709967100671016710267103671046710567106671076710867109671106711167112671136711467115671166711767118671196712067121671226712367124671256712667127671286712967130671316713267133671346713567136671376713867139671406714167142671436714467145671466714767148671496715067151671526715367154671556715667157671586715967160671616716267163671646716567166671676716867169671706717167172671736717467175671766717767178671796718067181671826718367184671856718667187671886718967190671916719267193671946719567196671976719867199672006720167202672036720467205672066720767208672096721067211672126721367214672156721667217672186721967220672216722267223672246722567226672276722867229672306723167232672336723467235672366723767238672396724067241672426724367244672456724667247672486724967250672516725267253672546725567256672576725867259672606726167262672636726467265672666726767268672696727067271672726727367274672756727667277672786727967280672816728267283672846728567286672876728867289672906729167292672936729467295672966729767298672996730067301673026730367304673056730667307673086730967310673116731267313673146731567316673176731867319673206732167322673236732467325673266732767328673296733067331673326733367334673356733667337673386733967340673416734267343673446734567346673476734867349673506735167352673536735467355673566735767358673596736067361673626736367364673656736667367673686736967370673716737267373673746737567376673776737867379673806738167382673836738467385673866738767388673896739067391673926739367394673956739667397673986739967400674016740267403674046740567406674076740867409674106741167412674136741467415674166741767418674196742067421674226742367424674256742667427674286742967430674316743267433674346743567436674376743867439674406744167442674436744467445674466744767448674496745067451674526745367454674556745667457674586745967460674616746267463674646746567466674676746867469674706747167472674736747467475674766747767478674796748067481674826748367484674856748667487674886748967490674916749267493674946749567496674976749867499675006750167502675036750467505675066750767508675096751067511675126751367514675156751667517675186751967520675216752267523675246752567526675276752867529675306753167532675336753467535675366753767538675396754067541675426754367544675456754667547675486754967550675516755267553675546755567556675576755867559675606756167562675636756467565675666756767568675696757067571675726757367574675756757667577675786757967580675816758267583675846758567586675876758867589675906759167592675936759467595675966759767598675996760067601676026760367604676056760667607676086760967610676116761267613676146761567616676176761867619676206762167622676236762467625676266762767628676296763067631676326763367634676356763667637676386763967640676416764267643676446764567646676476764867649676506765167652676536765467655676566765767658676596766067661676626766367664676656766667667676686766967670676716767267673676746767567676676776767867679676806768167682676836768467685676866768767688676896769067691676926769367694676956769667697676986769967700677016770267703677046770567706677076770867709677106771167712677136771467715677166771767718677196772067721677226772367724677256772667727677286772967730677316773267733677346773567736677376773867739677406774167742677436774467745677466774767748677496775067751677526775367754677556775667757677586775967760677616776267763677646776567766677676776867769677706777167772677736777467775677766777767778677796778067781677826778367784677856778667787677886778967790677916779267793677946779567796677976779867799678006780167802678036780467805678066780767808678096781067811678126781367814678156781667817678186781967820678216782267823678246782567826678276782867829678306783167832678336783467835678366783767838678396784067841678426784367844678456784667847678486784967850678516785267853678546785567856678576785867859678606786167862678636786467865678666786767868678696787067871678726787367874678756787667877678786787967880678816788267883678846788567886678876788867889678906789167892678936789467895678966789767898678996790067901679026790367904679056790667907679086790967910679116791267913679146791567916679176791867919679206792167922679236792467925679266792767928679296793067931679326793367934679356793667937679386793967940679416794267943679446794567946679476794867949679506795167952679536795467955679566795767958679596796067961679626796367964679656796667967679686796967970679716797267973679746797567976679776797867979679806798167982679836798467985679866798767988679896799067991679926799367994679956799667997679986799968000680016800268003680046800568006680076800868009680106801168012680136801468015680166801768018680196802068021680226802368024680256802668027680286802968030680316803268033680346803568036680376803868039680406804168042680436804468045680466804768048680496805068051680526805368054680556805668057680586805968060680616806268063680646806568066680676806868069680706807168072680736807468075680766807768078680796808068081680826808368084680856808668087680886808968090680916809268093680946809568096680976809868099681006810168102681036810468105681066810768108681096811068111681126811368114681156811668117681186811968120681216812268123681246812568126681276812868129681306813168132681336813468135681366813768138681396814068141681426814368144681456814668147681486814968150681516815268153681546815568156681576815868159681606816168162681636816468165681666816768168681696817068171681726817368174681756817668177681786817968180681816818268183681846818568186681876818868189681906819168192681936819468195681966819768198681996820068201682026820368204682056820668207682086820968210682116821268213682146821568216682176821868219682206822168222682236822468225682266822768228682296823068231682326823368234682356823668237682386823968240682416824268243682446824568246682476824868249682506825168252682536825468255682566825768258682596826068261682626826368264682656826668267682686826968270682716827268273682746827568276682776827868279682806828168282682836828468285682866828768288682896829068291682926829368294682956829668297682986829968300683016830268303683046830568306683076830868309683106831168312683136831468315683166831768318683196832068321683226832368324683256832668327683286832968330683316833268333683346833568336683376833868339683406834168342683436834468345683466834768348683496835068351683526835368354683556835668357683586835968360683616836268363683646836568366683676836868369683706837168372683736837468375683766837768378683796838068381683826838368384683856838668387683886838968390683916839268393683946839568396683976839868399684006840168402684036840468405684066840768408684096841068411684126841368414684156841668417684186841968420684216842268423684246842568426684276842868429684306843168432684336843468435684366843768438684396844068441684426844368444684456844668447684486844968450684516845268453684546845568456684576845868459684606846168462684636846468465684666846768468684696847068471684726847368474684756847668477684786847968480684816848268483684846848568486684876848868489684906849168492684936849468495684966849768498684996850068501685026850368504685056850668507685086850968510685116851268513685146851568516685176851868519685206852168522685236852468525685266852768528685296853068531685326853368534685356853668537685386853968540685416854268543685446854568546685476854868549685506855168552685536855468555685566855768558685596856068561685626856368564685656856668567685686856968570685716857268573685746857568576685776857868579685806858168582685836858468585685866858768588685896859068591685926859368594685956859668597685986859968600686016860268603686046860568606686076860868609686106861168612686136861468615686166861768618686196862068621686226862368624686256862668627686286862968630686316863268633686346863568636686376863868639686406864168642686436864468645686466864768648686496865068651686526865368654686556865668657686586865968660686616866268663686646866568666686676866868669686706867168672686736867468675686766867768678686796868068681686826868368684686856868668687686886868968690686916869268693686946869568696686976869868699687006870168702687036870468705687066870768708687096871068711687126871368714687156871668717687186871968720687216872268723687246872568726687276872868729687306873168732687336873468735687366873768738687396874068741687426874368744687456874668747687486874968750687516875268753687546875568756687576875868759687606876168762687636876468765687666876768768687696877068771687726877368774687756877668777687786877968780687816878268783687846878568786687876878868789687906879168792687936879468795687966879768798687996880068801688026880368804688056880668807688086880968810688116881268813688146881568816688176881868819688206882168822688236882468825688266882768828688296883068831688326883368834688356883668837688386883968840688416884268843688446884568846688476884868849688506885168852688536885468855688566885768858688596886068861688626886368864688656886668867688686886968870688716887268873688746887568876688776887868879688806888168882688836888468885688866888768888688896889068891688926889368894688956889668897688986889968900689016890268903689046890568906689076890868909689106891168912689136891468915689166891768918689196892068921689226892368924689256892668927689286892968930689316893268933689346893568936689376893868939689406894168942689436894468945689466894768948689496895068951689526895368954689556895668957689586895968960689616896268963689646896568966689676896868969689706897168972689736897468975689766897768978689796898068981689826898368984689856898668987689886898968990689916899268993689946899568996689976899868999690006900169002690036900469005690066900769008690096901069011690126901369014690156901669017690186901969020690216902269023690246902569026690276902869029690306903169032690336903469035690366903769038690396904069041690426904369044690456904669047690486904969050690516905269053690546905569056690576905869059690606906169062690636906469065690666906769068690696907069071690726907369074690756907669077690786907969080690816908269083690846908569086690876908869089690906909169092690936909469095690966909769098690996910069101691026910369104691056910669107691086910969110691116911269113691146911569116691176911869119691206912169122691236912469125691266912769128691296913069131691326913369134691356913669137691386913969140691416914269143691446914569146691476914869149691506915169152691536915469155691566915769158691596916069161691626916369164691656916669167691686916969170691716917269173691746917569176691776917869179691806918169182691836918469185691866918769188691896919069191691926919369194691956919669197691986919969200692016920269203692046920569206692076920869209692106921169212692136921469215692166921769218692196922069221692226922369224692256922669227692286922969230692316923269233692346923569236692376923869239692406924169242692436924469245692466924769248692496925069251692526925369254692556925669257692586925969260692616926269263692646926569266692676926869269692706927169272692736927469275692766927769278692796928069281692826928369284692856928669287692886928969290692916929269293692946929569296692976929869299693006930169302693036930469305693066930769308693096931069311693126931369314693156931669317693186931969320693216932269323693246932569326693276932869329693306933169332693336933469335693366933769338693396934069341693426934369344693456934669347693486934969350693516935269353693546935569356693576935869359693606936169362693636936469365693666936769368693696937069371693726937369374693756937669377693786937969380693816938269383693846938569386693876938869389693906939169392693936939469395693966939769398693996940069401694026940369404694056940669407694086940969410694116941269413694146941569416694176941869419694206942169422694236942469425694266942769428694296943069431694326943369434694356943669437694386943969440694416944269443694446944569446694476944869449694506945169452694536945469455694566945769458694596946069461694626946369464694656946669467694686946969470694716947269473694746947569476694776947869479694806948169482694836948469485694866948769488694896949069491694926949369494694956949669497694986949969500695016950269503695046950569506695076950869509695106951169512695136951469515695166951769518695196952069521695226952369524695256952669527695286952969530695316953269533695346953569536695376953869539695406954169542695436954469545695466954769548695496955069551695526955369554695556955669557695586955969560695616956269563695646956569566695676956869569695706957169572695736957469575695766957769578695796958069581695826958369584695856958669587695886958969590695916959269593695946959569596695976959869599696006960169602696036960469605696066960769608696096961069611696126961369614696156961669617696186961969620696216962269623696246962569626696276962869629696306963169632696336963469635696366963769638696396964069641696426964369644696456964669647696486964969650696516965269653696546965569656696576965869659696606966169662696636966469665696666966769668696696967069671696726967369674696756967669677696786967969680696816968269683696846968569686696876968869689696906969169692696936969469695696966969769698696996970069701697026970369704697056970669707697086970969710697116971269713697146971569716697176971869719697206972169722697236972469725697266972769728697296973069731697326973369734697356973669737697386973969740697416974269743697446974569746697476974869749697506975169752697536975469755697566975769758697596976069761697626976369764697656976669767697686976969770697716977269773697746977569776697776977869779697806978169782697836978469785697866978769788697896979069791697926979369794697956979669797697986979969800698016980269803698046980569806698076980869809698106981169812698136981469815698166981769818698196982069821698226982369824698256982669827698286982969830698316983269833698346983569836698376983869839698406984169842698436984469845698466984769848698496985069851698526985369854698556985669857698586985969860698616986269863698646986569866698676986869869698706987169872698736987469875698766987769878698796988069881698826988369884698856988669887698886988969890698916989269893698946989569896698976989869899699006990169902699036990469905699066990769908699096991069911699126991369914699156991669917699186991969920699216992269923699246992569926699276992869929699306993169932699336993469935699366993769938699396994069941699426994369944699456994669947699486994969950699516995269953699546995569956699576995869959699606996169962699636996469965699666996769968699696997069971699726997369974699756997669977699786997969980699816998269983699846998569986699876998869989699906999169992699936999469995699966999769998699997000070001700027000370004700057000670007700087000970010700117001270013700147001570016700177001870019700207002170022700237002470025700267002770028700297003070031700327003370034700357003670037700387003970040700417004270043700447004570046700477004870049700507005170052700537005470055700567005770058700597006070061700627006370064700657006670067700687006970070700717007270073700747007570076700777007870079700807008170082700837008470085700867008770088700897009070091700927009370094700957009670097700987009970100701017010270103701047010570106701077010870109701107011170112701137011470115701167011770118701197012070121701227012370124701257012670127701287012970130701317013270133701347013570136701377013870139701407014170142701437014470145701467014770148701497015070151701527015370154701557015670157701587015970160701617016270163701647016570166701677016870169701707017170172701737017470175701767017770178701797018070181701827018370184701857018670187701887018970190701917019270193701947019570196701977019870199702007020170202702037020470205702067020770208702097021070211702127021370214702157021670217702187021970220702217022270223702247022570226702277022870229702307023170232702337023470235702367023770238702397024070241702427024370244702457024670247702487024970250702517025270253702547025570256702577025870259702607026170262702637026470265702667026770268702697027070271702727027370274702757027670277702787027970280702817028270283702847028570286702877028870289702907029170292702937029470295702967029770298702997030070301703027030370304703057030670307703087030970310703117031270313703147031570316703177031870319703207032170322703237032470325703267032770328703297033070331703327033370334703357033670337703387033970340703417034270343703447034570346703477034870349703507035170352703537035470355703567035770358703597036070361703627036370364703657036670367703687036970370703717037270373703747037570376703777037870379703807038170382703837038470385703867038770388703897039070391703927039370394703957039670397703987039970400704017040270403704047040570406704077040870409704107041170412704137041470415704167041770418704197042070421704227042370424704257042670427704287042970430704317043270433704347043570436704377043870439704407044170442704437044470445704467044770448704497045070451704527045370454704557045670457704587045970460704617046270463704647046570466704677046870469704707047170472704737047470475704767047770478704797048070481704827048370484704857048670487704887048970490704917049270493704947049570496704977049870499705007050170502705037050470505705067050770508705097051070511705127051370514705157051670517705187051970520705217052270523705247052570526705277052870529705307053170532705337053470535705367053770538705397054070541705427054370544705457054670547705487054970550705517055270553705547055570556705577055870559705607056170562705637056470565705667056770568705697057070571705727057370574705757057670577705787057970580705817058270583705847058570586705877058870589705907059170592705937059470595705967059770598705997060070601706027060370604706057060670607706087060970610706117061270613706147061570616706177061870619706207062170622706237062470625706267062770628706297063070631706327063370634706357063670637706387063970640706417064270643706447064570646706477064870649706507065170652706537065470655706567065770658706597066070661706627066370664706657066670667706687066970670706717067270673706747067570676706777067870679706807068170682706837068470685706867068770688706897069070691706927069370694706957069670697706987069970700707017070270703707047070570706707077070870709707107071170712707137071470715707167071770718707197072070721707227072370724707257072670727707287072970730707317073270733707347073570736707377073870739707407074170742707437074470745707467074770748707497075070751707527075370754707557075670757707587075970760707617076270763707647076570766707677076870769707707077170772707737077470775707767077770778707797078070781707827078370784707857078670787707887078970790707917079270793707947079570796707977079870799708007080170802708037080470805708067080770808708097081070811708127081370814708157081670817708187081970820708217082270823708247082570826708277082870829708307083170832708337083470835708367083770838708397084070841708427084370844708457084670847708487084970850708517085270853708547085570856708577085870859708607086170862708637086470865708667086770868708697087070871708727087370874708757087670877708787087970880708817088270883708847088570886708877088870889708907089170892708937089470895708967089770898708997090070901709027090370904709057090670907709087090970910709117091270913709147091570916709177091870919709207092170922709237092470925709267092770928709297093070931709327093370934709357093670937709387093970940709417094270943709447094570946709477094870949709507095170952709537095470955709567095770958709597096070961709627096370964709657096670967709687096970970709717097270973709747097570976709777097870979709807098170982709837098470985709867098770988709897099070991709927099370994709957099670997709987099971000710017100271003710047100571006710077100871009710107101171012710137101471015710167101771018710197102071021710227102371024710257102671027710287102971030710317103271033710347103571036710377103871039710407104171042710437104471045710467104771048710497105071051710527105371054710557105671057710587105971060710617106271063710647106571066710677106871069710707107171072710737107471075710767107771078710797108071081710827108371084710857108671087710887108971090710917109271093710947109571096710977109871099711007110171102711037110471105711067110771108711097111071111711127111371114711157111671117711187111971120711217112271123711247112571126711277112871129711307113171132711337113471135711367113771138711397114071141711427114371144711457114671147711487114971150711517115271153711547115571156711577115871159711607116171162711637116471165711667116771168711697117071171711727117371174711757117671177711787117971180711817118271183711847118571186711877118871189711907119171192711937119471195711967119771198711997120071201712027120371204712057120671207712087120971210712117121271213712147121571216712177121871219712207122171222712237122471225712267122771228712297123071231712327123371234712357123671237712387123971240712417124271243712447124571246712477124871249712507125171252712537125471255712567125771258712597126071261712627126371264712657126671267712687126971270712717127271273712747127571276712777127871279712807128171282712837128471285712867128771288712897129071291712927129371294712957129671297712987129971300713017130271303713047130571306713077130871309713107131171312713137131471315713167131771318713197132071321713227132371324713257132671327713287132971330713317133271333713347133571336713377133871339713407134171342713437134471345713467134771348713497135071351713527135371354713557135671357713587135971360713617136271363713647136571366713677136871369713707137171372713737137471375713767137771378713797138071381713827138371384713857138671387713887138971390713917139271393713947139571396713977139871399714007140171402714037140471405714067140771408714097141071411714127141371414714157141671417714187141971420714217142271423714247142571426714277142871429714307143171432714337143471435714367143771438714397144071441714427144371444714457144671447714487144971450714517145271453714547145571456714577145871459714607146171462714637146471465714667146771468714697147071471714727147371474714757147671477714787147971480714817148271483714847148571486714877148871489714907149171492714937149471495714967149771498714997150071501715027150371504715057150671507715087150971510715117151271513715147151571516715177151871519715207152171522715237152471525715267152771528715297153071531715327153371534715357153671537715387153971540715417154271543715447154571546715477154871549715507155171552715537155471555715567155771558715597156071561715627156371564715657156671567715687156971570715717157271573715747157571576715777157871579715807158171582715837158471585715867158771588715897159071591715927159371594715957159671597715987159971600716017160271603716047160571606716077160871609716107161171612716137161471615716167161771618716197162071621716227162371624716257162671627716287162971630716317163271633716347163571636716377163871639716407164171642716437164471645716467164771648716497165071651716527165371654716557165671657716587165971660716617166271663716647166571666716677166871669716707167171672716737167471675716767167771678716797168071681716827168371684716857168671687716887168971690716917169271693716947169571696716977169871699717007170171702717037170471705717067170771708717097171071711717127171371714717157171671717717187171971720717217172271723717247172571726717277172871729717307173171732717337173471735717367173771738717397174071741717427174371744717457174671747717487174971750717517175271753717547175571756717577175871759717607176171762717637176471765717667176771768717697177071771717727177371774717757177671777717787177971780717817178271783717847178571786717877178871789717907179171792717937179471795717967179771798717997180071801718027180371804718057180671807718087180971810718117181271813718147181571816718177181871819718207182171822718237182471825718267182771828718297183071831718327183371834718357183671837718387183971840718417184271843718447184571846718477184871849718507185171852718537185471855718567185771858718597186071861718627186371864718657186671867718687186971870718717187271873718747187571876718777187871879718807188171882718837188471885718867188771888718897189071891718927189371894718957189671897718987189971900719017190271903719047190571906719077190871909719107191171912719137191471915719167191771918719197192071921719227192371924719257192671927719287192971930719317193271933719347193571936719377193871939719407194171942719437194471945719467194771948719497195071951719527195371954719557195671957719587195971960719617196271963719647196571966719677196871969719707197171972719737197471975719767197771978719797198071981719827198371984719857198671987719887198971990719917199271993719947199571996719977199871999720007200172002720037200472005720067200772008720097201072011720127201372014720157201672017720187201972020720217202272023720247202572026720277202872029720307203172032720337203472035720367203772038720397204072041720427204372044720457204672047720487204972050720517205272053720547205572056720577205872059720607206172062720637206472065720667206772068720697207072071720727207372074720757207672077720787207972080720817208272083720847208572086720877208872089720907209172092720937209472095720967209772098720997210072101721027210372104721057210672107721087210972110721117211272113721147211572116721177211872119721207212172122721237212472125721267212772128721297213072131721327213372134721357213672137721387213972140721417214272143721447214572146721477214872149721507215172152721537215472155721567215772158721597216072161721627216372164721657216672167721687216972170721717217272173721747217572176721777217872179721807218172182721837218472185721867218772188721897219072191721927219372194721957219672197721987219972200722017220272203722047220572206722077220872209722107221172212722137221472215722167221772218722197222072221722227222372224722257222672227722287222972230722317223272233722347223572236722377223872239722407224172242722437224472245722467224772248722497225072251722527225372254722557225672257722587225972260722617226272263722647226572266722677226872269722707227172272722737227472275722767227772278722797228072281722827228372284722857228672287722887228972290722917229272293722947229572296722977229872299723007230172302723037230472305723067230772308723097231072311723127231372314723157231672317723187231972320723217232272323723247232572326723277232872329723307233172332723337233472335723367233772338723397234072341723427234372344723457234672347723487234972350723517235272353723547235572356723577235872359723607236172362723637236472365723667236772368723697237072371723727237372374723757237672377723787237972380723817238272383723847238572386723877238872389723907239172392723937239472395723967239772398723997240072401724027240372404724057240672407724087240972410724117241272413724147241572416724177241872419724207242172422724237242472425724267242772428724297243072431724327243372434724357243672437724387243972440724417244272443724447244572446724477244872449724507245172452724537245472455724567245772458724597246072461724627246372464724657246672467724687246972470724717247272473724747247572476724777247872479724807248172482724837248472485724867248772488724897249072491724927249372494724957249672497724987249972500725017250272503725047250572506725077250872509725107251172512725137251472515725167251772518725197252072521725227252372524725257252672527725287252972530725317253272533725347253572536725377253872539725407254172542725437254472545725467254772548725497255072551725527255372554725557255672557725587255972560725617256272563725647256572566725677256872569725707257172572725737257472575725767257772578725797258072581725827258372584725857258672587725887258972590725917259272593725947259572596725977259872599726007260172602726037260472605726067260772608726097261072611726127261372614726157261672617726187261972620726217262272623726247262572626726277262872629726307263172632726337263472635726367263772638726397264072641726427264372644726457264672647726487264972650726517265272653726547265572656726577265872659726607266172662726637266472665726667266772668726697267072671726727267372674726757267672677726787267972680726817268272683726847268572686726877268872689726907269172692726937269472695726967269772698726997270072701727027270372704727057270672707727087270972710727117271272713727147271572716727177271872719727207272172722727237272472725727267272772728727297273072731727327273372734727357273672737727387273972740727417274272743727447274572746727477274872749727507275172752727537275472755727567275772758727597276072761727627276372764727657276672767727687276972770727717277272773727747277572776727777277872779727807278172782727837278472785727867278772788727897279072791727927279372794727957279672797727987279972800728017280272803728047280572806728077280872809728107281172812728137281472815728167281772818728197282072821728227282372824728257282672827728287282972830728317283272833728347283572836728377283872839728407284172842728437284472845728467284772848728497285072851728527285372854728557285672857728587285972860728617286272863728647286572866728677286872869728707287172872728737287472875728767287772878728797288072881728827288372884728857288672887728887288972890728917289272893728947289572896728977289872899729007290172902729037290472905729067290772908729097291072911729127291372914729157291672917729187291972920729217292272923729247292572926729277292872929729307293172932729337293472935729367293772938729397294072941729427294372944729457294672947729487294972950729517295272953729547295572956729577295872959729607296172962729637296472965729667296772968729697297072971729727297372974729757297672977729787297972980729817298272983729847298572986729877298872989729907299172992729937299472995729967299772998729997300073001730027300373004730057300673007730087300973010730117301273013730147301573016730177301873019730207302173022730237302473025730267302773028730297303073031730327303373034730357303673037730387303973040730417304273043730447304573046730477304873049730507305173052730537305473055730567305773058730597306073061730627306373064730657306673067730687306973070730717307273073730747307573076730777307873079730807308173082730837308473085730867308773088730897309073091730927309373094730957309673097730987309973100731017310273103731047310573106731077310873109731107311173112731137311473115731167311773118731197312073121731227312373124731257312673127731287312973130731317313273133731347313573136731377313873139731407314173142731437314473145731467314773148731497315073151731527315373154731557315673157731587315973160731617316273163731647316573166731677316873169731707317173172731737317473175731767317773178731797318073181731827318373184731857318673187731887318973190731917319273193731947319573196731977319873199732007320173202732037320473205732067320773208732097321073211732127321373214732157321673217732187321973220732217322273223732247322573226732277322873229732307323173232732337323473235732367323773238732397324073241732427324373244732457324673247732487324973250732517325273253732547325573256732577325873259732607326173262732637326473265732667326773268732697327073271732727327373274732757327673277732787327973280732817328273283732847328573286732877328873289732907329173292732937329473295732967329773298732997330073301733027330373304733057330673307733087330973310733117331273313733147331573316733177331873319733207332173322733237332473325733267332773328733297333073331733327333373334733357333673337733387333973340733417334273343733447334573346733477334873349733507335173352733537335473355733567335773358733597336073361733627336373364733657336673367733687336973370733717337273373733747337573376733777337873379733807338173382733837338473385733867338773388733897339073391733927339373394733957339673397733987339973400734017340273403734047340573406734077340873409734107341173412734137341473415734167341773418734197342073421734227342373424734257342673427734287342973430734317343273433734347343573436734377343873439734407344173442734437344473445734467344773448734497345073451734527345373454734557345673457734587345973460734617346273463734647346573466734677346873469734707347173472734737347473475734767347773478734797348073481734827348373484734857348673487734887348973490734917349273493734947349573496734977349873499735007350173502735037350473505735067350773508735097351073511735127351373514735157351673517735187351973520735217352273523735247352573526735277352873529735307353173532735337353473535735367353773538735397354073541735427354373544735457354673547735487354973550735517355273553735547355573556735577355873559735607356173562735637356473565735667356773568735697357073571735727357373574735757357673577735787357973580735817358273583735847358573586735877358873589735907359173592735937359473595735967359773598735997360073601736027360373604736057360673607736087360973610736117361273613736147361573616736177361873619736207362173622736237362473625736267362773628736297363073631736327363373634736357363673637736387363973640736417364273643736447364573646736477364873649736507365173652736537365473655736567365773658736597366073661736627366373664736657366673667736687366973670736717367273673736747367573676736777367873679736807368173682736837368473685736867368773688736897369073691736927369373694736957369673697736987369973700737017370273703737047370573706737077370873709737107371173712737137371473715737167371773718737197372073721737227372373724737257372673727737287372973730737317373273733737347373573736737377373873739737407374173742737437374473745737467374773748737497375073751737527375373754737557375673757737587375973760737617376273763737647376573766737677376873769737707377173772737737377473775737767377773778737797378073781737827378373784737857378673787737887378973790737917379273793737947379573796737977379873799738007380173802738037380473805738067380773808738097381073811738127381373814738157381673817738187381973820738217382273823738247382573826738277382873829738307383173832738337383473835738367383773838738397384073841738427384373844738457384673847738487384973850738517385273853738547385573856738577385873859738607386173862738637386473865738667386773868738697387073871738727387373874738757387673877738787387973880738817388273883738847388573886738877388873889738907389173892738937389473895738967389773898738997390073901739027390373904739057390673907739087390973910739117391273913739147391573916739177391873919739207392173922739237392473925739267392773928739297393073931739327393373934739357393673937739387393973940739417394273943739447394573946739477394873949739507395173952739537395473955739567395773958739597396073961739627396373964739657396673967739687396973970739717397273973739747397573976739777397873979739807398173982739837398473985739867398773988739897399073991739927399373994739957399673997739987399974000740017400274003740047400574006740077400874009740107401174012740137401474015740167401774018740197402074021740227402374024740257402674027740287402974030740317403274033740347403574036740377403874039740407404174042740437404474045740467404774048740497405074051740527405374054740557405674057740587405974060740617406274063740647406574066740677406874069740707407174072740737407474075740767407774078740797408074081740827408374084740857408674087740887408974090740917409274093740947409574096740977409874099741007410174102741037410474105741067410774108741097411074111741127411374114741157411674117741187411974120741217412274123741247412574126741277412874129741307413174132741337413474135741367413774138741397414074141741427414374144741457414674147741487414974150741517415274153741547415574156741577415874159741607416174162741637416474165741667416774168741697417074171741727417374174741757417674177741787417974180741817418274183741847418574186741877418874189741907419174192741937419474195741967419774198741997420074201742027420374204742057420674207742087420974210742117421274213742147421574216742177421874219742207422174222742237422474225742267422774228742297423074231742327423374234742357423674237742387423974240742417424274243742447424574246742477424874249742507425174252742537425474255742567425774258742597426074261742627426374264742657426674267742687426974270742717427274273742747427574276742777427874279742807428174282742837428474285742867428774288742897429074291742927429374294742957429674297742987429974300743017430274303743047430574306743077430874309743107431174312743137431474315743167431774318743197432074321743227432374324743257432674327743287432974330743317433274333743347433574336743377433874339743407434174342743437434474345743467434774348743497435074351743527435374354743557435674357743587435974360743617436274363743647436574366743677436874369743707437174372743737437474375743767437774378743797438074381743827438374384743857438674387743887438974390743917439274393743947439574396743977439874399744007440174402744037440474405744067440774408744097441074411744127441374414744157441674417744187441974420744217442274423744247442574426744277442874429744307443174432744337443474435744367443774438744397444074441744427444374444744457444674447744487444974450744517445274453744547445574456744577445874459744607446174462744637446474465744667446774468744697447074471744727447374474744757447674477744787447974480744817448274483744847448574486744877448874489744907449174492744937449474495744967449774498744997450074501745027450374504745057450674507745087450974510745117451274513745147451574516745177451874519745207452174522745237452474525745267452774528745297453074531745327453374534745357453674537745387453974540745417454274543745447454574546745477454874549745507455174552745537455474555745567455774558745597456074561745627456374564745657456674567745687456974570745717457274573745747457574576745777457874579745807458174582745837458474585745867458774588745897459074591745927459374594745957459674597745987459974600746017460274603746047460574606746077460874609746107461174612746137461474615746167461774618746197462074621746227462374624746257462674627746287462974630746317463274633746347463574636746377463874639746407464174642746437464474645746467464774648746497465074651746527465374654746557465674657746587465974660746617466274663746647466574666746677466874669746707467174672746737467474675746767467774678746797468074681746827468374684746857468674687746887468974690746917469274693746947469574696746977469874699747007470174702747037470474705747067470774708747097471074711747127471374714747157471674717747187471974720747217472274723747247472574726747277472874729747307473174732747337473474735747367473774738747397474074741747427474374744747457474674747747487474974750747517475274753747547475574756747577475874759747607476174762747637476474765747667476774768747697477074771747727477374774747757477674777747787477974780747817478274783747847478574786747877478874789747907479174792747937479474795747967479774798747997480074801748027480374804748057480674807748087480974810748117481274813748147481574816748177481874819748207482174822748237482474825748267482774828748297483074831748327483374834748357483674837748387483974840748417484274843748447484574846748477484874849748507485174852748537485474855748567485774858748597486074861748627486374864748657486674867748687486974870748717487274873748747487574876748777487874879748807488174882748837488474885748867488774888748897489074891748927489374894748957489674897748987489974900749017490274903749047490574906749077490874909749107491174912749137491474915749167491774918749197492074921749227492374924749257492674927749287492974930749317493274933749347493574936749377493874939749407494174942749437494474945749467494774948749497495074951749527495374954749557495674957749587495974960749617496274963749647496574966749677496874969749707497174972749737497474975749767497774978749797498074981749827498374984749857498674987749887498974990749917499274993749947499574996749977499874999750007500175002750037500475005750067500775008750097501075011750127501375014750157501675017750187501975020750217502275023750247502575026750277502875029750307503175032750337503475035750367503775038750397504075041750427504375044750457504675047750487504975050750517505275053750547505575056750577505875059750607506175062750637506475065750667506775068750697507075071750727507375074750757507675077750787507975080750817508275083750847508575086750877508875089750907509175092750937509475095750967509775098750997510075101751027510375104751057510675107751087510975110751117511275113751147511575116751177511875119751207512175122751237512475125751267512775128751297513075131751327513375134751357513675137751387513975140751417514275143751447514575146751477514875149751507515175152751537515475155751567515775158751597516075161751627516375164751657516675167751687516975170751717517275173751747517575176751777517875179751807518175182751837518475185751867518775188751897519075191751927519375194751957519675197751987519975200752017520275203752047520575206752077520875209752107521175212752137521475215752167521775218752197522075221752227522375224752257522675227752287522975230752317523275233752347523575236752377523875239752407524175242752437524475245752467524775248752497525075251752527525375254752557525675257752587525975260752617526275263752647526575266752677526875269752707527175272752737527475275752767527775278752797528075281752827528375284752857528675287752887528975290752917529275293752947529575296752977529875299753007530175302753037530475305753067530775308753097531075311753127531375314753157531675317753187531975320753217532275323753247532575326753277532875329753307533175332753337533475335753367533775338753397534075341753427534375344753457534675347753487534975350753517535275353753547535575356753577535875359753607536175362753637536475365753667536775368753697537075371753727537375374753757537675377753787537975380753817538275383753847538575386753877538875389753907539175392753937539475395753967539775398753997540075401754027540375404754057540675407754087540975410754117541275413754147541575416754177541875419754207542175422754237542475425754267542775428754297543075431754327543375434754357543675437754387543975440754417544275443754447544575446754477544875449754507545175452754537545475455754567545775458754597546075461754627546375464754657546675467754687546975470754717547275473754747547575476754777547875479754807548175482754837548475485754867548775488754897549075491754927549375494754957549675497754987549975500755017550275503755047550575506755077550875509755107551175512755137551475515755167551775518755197552075521755227552375524755257552675527755287552975530755317553275533755347553575536755377553875539755407554175542755437554475545755467554775548755497555075551755527555375554755557555675557755587555975560755617556275563755647556575566755677556875569755707557175572755737557475575755767557775578755797558075581755827558375584755857558675587755887558975590755917559275593755947559575596755977559875599756007560175602756037560475605756067560775608756097561075611756127561375614756157561675617756187561975620756217562275623756247562575626756277562875629756307563175632756337563475635756367563775638756397564075641756427564375644756457564675647756487564975650756517565275653756547565575656756577565875659756607566175662756637566475665756667566775668756697567075671756727567375674756757567675677756787567975680756817568275683756847568575686756877568875689756907569175692756937569475695756967569775698756997570075701757027570375704757057570675707757087570975710757117571275713757147571575716757177571875719757207572175722757237572475725757267572775728757297573075731757327573375734757357573675737757387573975740757417574275743757447574575746757477574875749757507575175752757537575475755757567575775758757597576075761757627576375764757657576675767757687576975770757717577275773757747577575776757777577875779757807578175782757837578475785757867578775788757897579075791757927579375794757957579675797757987579975800758017580275803758047580575806758077580875809758107581175812758137581475815758167581775818758197582075821758227582375824758257582675827758287582975830758317583275833758347583575836758377583875839758407584175842758437584475845758467584775848758497585075851758527585375854758557585675857758587585975860758617586275863758647586575866758677586875869758707587175872758737587475875758767587775878758797588075881758827588375884758857588675887758887588975890758917589275893758947589575896758977589875899759007590175902759037590475905759067590775908759097591075911759127591375914759157591675917759187591975920759217592275923759247592575926759277592875929759307593175932759337593475935759367593775938759397594075941759427594375944759457594675947759487594975950759517595275953759547595575956759577595875959759607596175962759637596475965759667596775968759697597075971759727597375974759757597675977759787597975980759817598275983759847598575986759877598875989759907599175992759937599475995759967599775998759997600076001760027600376004760057600676007760087600976010760117601276013760147601576016760177601876019760207602176022760237602476025760267602776028760297603076031760327603376034760357603676037760387603976040760417604276043760447604576046760477604876049760507605176052760537605476055760567605776058760597606076061760627606376064760657606676067760687606976070760717607276073760747607576076760777607876079760807608176082760837608476085760867608776088760897609076091760927609376094760957609676097760987609976100761017610276103761047610576106761077610876109761107611176112761137611476115761167611776118761197612076121761227612376124761257612676127761287612976130761317613276133761347613576136761377613876139761407614176142761437614476145761467614776148761497615076151761527615376154761557615676157761587615976160761617616276163761647616576166761677616876169761707617176172761737617476175761767617776178761797618076181761827618376184761857618676187761887618976190761917619276193761947619576196761977619876199762007620176202762037620476205762067620776208762097621076211762127621376214762157621676217762187621976220762217622276223762247622576226762277622876229762307623176232762337623476235762367623776238762397624076241762427624376244762457624676247762487624976250762517625276253762547625576256762577625876259762607626176262762637626476265762667626776268762697627076271762727627376274762757627676277762787627976280762817628276283762847628576286762877628876289762907629176292762937629476295762967629776298762997630076301763027630376304763057630676307763087630976310763117631276313763147631576316763177631876319763207632176322763237632476325763267632776328763297633076331763327633376334763357633676337763387633976340763417634276343763447634576346763477634876349763507635176352763537635476355763567635776358763597636076361763627636376364763657636676367763687636976370763717637276373763747637576376763777637876379763807638176382763837638476385763867638776388763897639076391763927639376394763957639676397763987639976400764017640276403764047640576406764077640876409764107641176412764137641476415764167641776418764197642076421764227642376424764257642676427764287642976430764317643276433764347643576436764377643876439764407644176442764437644476445764467644776448764497645076451764527645376454764557645676457764587645976460764617646276463764647646576466764677646876469764707647176472764737647476475764767647776478764797648076481764827648376484764857648676487764887648976490764917649276493764947649576496764977649876499765007650176502765037650476505765067650776508765097651076511765127651376514765157651676517765187651976520765217652276523765247652576526765277652876529765307653176532765337653476535765367653776538765397654076541765427654376544765457654676547765487654976550765517655276553765547655576556765577655876559765607656176562765637656476565765667656776568765697657076571765727657376574765757657676577765787657976580765817658276583765847658576586765877658876589765907659176592765937659476595765967659776598765997660076601766027660376604766057660676607766087660976610766117661276613766147661576616766177661876619766207662176622766237662476625766267662776628766297663076631766327663376634766357663676637766387663976640766417664276643766447664576646766477664876649766507665176652766537665476655766567665776658766597666076661766627666376664766657666676667766687666976670766717667276673766747667576676766777667876679766807668176682766837668476685766867668776688766897669076691766927669376694766957669676697766987669976700767017670276703767047670576706767077670876709767107671176712767137671476715767167671776718767197672076721767227672376724767257672676727767287672976730767317673276733767347673576736767377673876739767407674176742767437674476745767467674776748767497675076751767527675376754767557675676757767587675976760767617676276763767647676576766767677676876769767707677176772767737677476775767767677776778767797678076781767827678376784767857678676787767887678976790767917679276793767947679576796767977679876799768007680176802768037680476805768067680776808768097681076811768127681376814768157681676817768187681976820768217682276823768247682576826768277682876829768307683176832768337683476835768367683776838768397684076841768427684376844768457684676847768487684976850768517685276853768547685576856768577685876859768607686176862768637686476865768667686776868768697687076871768727687376874768757687676877768787687976880768817688276883768847688576886768877688876889768907689176892768937689476895768967689776898768997690076901769027690376904769057690676907769087690976910769117691276913769147691576916769177691876919769207692176922769237692476925769267692776928769297693076931769327693376934769357693676937769387693976940769417694276943769447694576946769477694876949769507695176952769537695476955769567695776958769597696076961769627696376964769657696676967769687696976970769717697276973769747697576976769777697876979769807698176982769837698476985769867698776988769897699076991769927699376994769957699676997769987699977000770017700277003770047700577006770077700877009770107701177012770137701477015770167701777018770197702077021770227702377024770257702677027770287702977030770317703277033770347703577036770377703877039770407704177042770437704477045770467704777048770497705077051770527705377054770557705677057770587705977060770617706277063770647706577066770677706877069770707707177072770737707477075770767707777078770797708077081770827708377084770857708677087770887708977090770917709277093770947709577096770977709877099771007710177102771037710477105771067710777108771097711077111771127711377114771157711677117771187711977120771217712277123771247712577126771277712877129771307713177132771337713477135771367713777138771397714077141771427714377144771457714677147771487714977150771517715277153771547715577156771577715877159771607716177162771637716477165771667716777168771697717077171771727717377174771757717677177771787717977180771817718277183771847718577186771877718877189771907719177192771937719477195771967719777198771997720077201772027720377204772057720677207772087720977210772117721277213772147721577216772177721877219772207722177222772237722477225772267722777228772297723077231772327723377234772357723677237772387723977240772417724277243772447724577246772477724877249772507725177252772537725477255772567725777258772597726077261772627726377264772657726677267772687726977270772717727277273772747727577276772777727877279772807728177282772837728477285772867728777288772897729077291772927729377294772957729677297772987729977300773017730277303773047730577306773077730877309773107731177312773137731477315773167731777318773197732077321773227732377324773257732677327773287732977330773317733277333773347733577336773377733877339773407734177342773437734477345773467734777348773497735077351773527735377354773557735677357773587735977360773617736277363773647736577366773677736877369773707737177372773737737477375773767737777378773797738077381773827738377384773857738677387773887738977390773917739277393773947739577396773977739877399774007740177402774037740477405774067740777408774097741077411774127741377414774157741677417774187741977420774217742277423774247742577426774277742877429774307743177432774337743477435774367743777438774397744077441774427744377444774457744677447774487744977450774517745277453774547745577456774577745877459774607746177462774637746477465774667746777468774697747077471774727747377474774757747677477774787747977480774817748277483774847748577486774877748877489774907749177492774937749477495774967749777498774997750077501775027750377504775057750677507775087750977510775117751277513775147751577516775177751877519775207752177522775237752477525775267752777528775297753077531775327753377534775357753677537775387753977540775417754277543775447754577546775477754877549775507755177552775537755477555775567755777558775597756077561775627756377564775657756677567775687756977570775717757277573775747757577576775777757877579775807758177582775837758477585775867758777588775897759077591775927759377594775957759677597775987759977600776017760277603776047760577606776077760877609776107761177612776137761477615776167761777618776197762077621776227762377624776257762677627776287762977630776317763277633776347763577636776377763877639776407764177642776437764477645776467764777648776497765077651776527765377654776557765677657776587765977660776617766277663776647766577666776677766877669776707767177672776737767477675776767767777678776797768077681776827768377684776857768677687776887768977690776917769277693776947769577696776977769877699777007770177702777037770477705777067770777708777097771077711777127771377714777157771677717777187771977720777217772277723777247772577726777277772877729777307773177732777337773477735777367773777738777397774077741777427774377744777457774677747777487774977750777517775277753777547775577756777577775877759777607776177762777637776477765777667776777768777697777077771777727777377774777757777677777777787777977780777817778277783777847778577786777877778877789777907779177792777937779477795777967779777798777997780077801778027780377804778057780677807778087780977810778117781277813778147781577816778177781877819778207782177822778237782477825778267782777828778297783077831778327783377834778357783677837778387783977840778417784277843778447784577846778477784877849778507785177852778537785477855778567785777858778597786077861778627786377864778657786677867778687786977870778717787277873778747787577876778777787877879778807788177882778837788477885778867788777888778897789077891778927789377894778957789677897778987789977900779017790277903779047790577906779077790877909779107791177912779137791477915779167791777918779197792077921779227792377924779257792677927779287792977930779317793277933779347793577936779377793877939779407794177942779437794477945779467794777948779497795077951779527795377954779557795677957779587795977960779617796277963779647796577966779677796877969779707797177972779737797477975779767797777978779797798077981779827798377984779857798677987779887798977990779917799277993779947799577996779977799877999780007800178002780037800478005780067800778008780097801078011780127801378014780157801678017780187801978020780217802278023780247802578026780277802878029780307803178032780337803478035780367803778038780397804078041780427804378044780457804678047780487804978050780517805278053780547805578056780577805878059780607806178062780637806478065780667806778068780697807078071780727807378074780757807678077780787807978080780817808278083780847808578086780877808878089780907809178092780937809478095780967809778098780997810078101781027810378104781057810678107781087810978110781117811278113781147811578116781177811878119781207812178122781237812478125781267812778128781297813078131781327813378134781357813678137781387813978140781417814278143781447814578146781477814878149781507815178152781537815478155781567815778158781597816078161781627816378164781657816678167781687816978170781717817278173781747817578176781777817878179781807818178182781837818478185781867818778188781897819078191781927819378194781957819678197781987819978200782017820278203782047820578206782077820878209782107821178212782137821478215782167821778218782197822078221782227822378224782257822678227782287822978230782317823278233782347823578236782377823878239782407824178242782437824478245782467824778248782497825078251782527825378254782557825678257782587825978260782617826278263782647826578266782677826878269782707827178272782737827478275782767827778278782797828078281782827828378284782857828678287782887828978290782917829278293782947829578296782977829878299783007830178302783037830478305783067830778308783097831078311783127831378314783157831678317783187831978320783217832278323783247832578326783277832878329783307833178332783337833478335783367833778338783397834078341783427834378344783457834678347783487834978350783517835278353783547835578356783577835878359783607836178362783637836478365783667836778368783697837078371783727837378374783757837678377783787837978380783817838278383783847838578386783877838878389783907839178392783937839478395783967839778398783997840078401784027840378404784057840678407784087840978410784117841278413784147841578416784177841878419784207842178422784237842478425784267842778428784297843078431784327843378434784357843678437784387843978440784417844278443784447844578446784477844878449784507845178452784537845478455784567845778458784597846078461784627846378464784657846678467784687846978470784717847278473784747847578476784777847878479784807848178482784837848478485784867848778488784897849078491784927849378494784957849678497784987849978500785017850278503785047850578506785077850878509785107851178512785137851478515785167851778518785197852078521785227852378524785257852678527785287852978530785317853278533785347853578536785377853878539785407854178542785437854478545785467854778548785497855078551785527855378554785557855678557785587855978560785617856278563785647856578566785677856878569785707857178572785737857478575785767857778578785797858078581785827858378584785857858678587785887858978590785917859278593785947859578596785977859878599786007860178602786037860478605786067860778608786097861078611786127861378614786157861678617786187861978620786217862278623786247862578626786277862878629786307863178632786337863478635786367863778638786397864078641786427864378644786457864678647786487864978650786517865278653786547865578656786577865878659786607866178662786637866478665786667866778668786697867078671786727867378674786757867678677786787867978680786817868278683786847868578686786877868878689786907869178692786937869478695786967869778698786997870078701787027870378704787057870678707787087870978710787117871278713787147871578716787177871878719787207872178722787237872478725787267872778728787297873078731787327873378734787357873678737787387873978740787417874278743787447874578746787477874878749787507875178752787537875478755787567875778758787597876078761787627876378764787657876678767787687876978770787717877278773787747877578776787777877878779787807878178782787837878478785787867878778788787897879078791787927879378794787957879678797787987879978800788017880278803788047880578806788077880878809788107881178812788137881478815788167881778818788197882078821788227882378824788257882678827788287882978830788317883278833788347883578836788377883878839788407884178842788437884478845788467884778848788497885078851788527885378854788557885678857788587885978860788617886278863788647886578866788677886878869788707887178872788737887478875788767887778878788797888078881788827888378884788857888678887788887888978890788917889278893788947889578896788977889878899789007890178902789037890478905789067890778908789097891078911789127891378914789157891678917789187891978920789217892278923789247892578926789277892878929789307893178932789337893478935789367893778938789397894078941789427894378944789457894678947789487894978950789517895278953789547895578956789577895878959789607896178962789637896478965789667896778968789697897078971789727897378974789757897678977789787897978980789817898278983789847898578986789877898878989789907899178992789937899478995789967899778998789997900079001790027900379004790057900679007790087900979010790117901279013790147901579016790177901879019790207902179022790237902479025790267902779028790297903079031790327903379034790357903679037790387903979040790417904279043790447904579046790477904879049790507905179052790537905479055790567905779058790597906079061790627906379064790657906679067790687906979070790717907279073790747907579076790777907879079790807908179082790837908479085790867908779088790897909079091790927909379094790957909679097790987909979100791017910279103791047910579106791077910879109791107911179112791137911479115791167911779118791197912079121791227912379124791257912679127791287912979130791317913279133791347913579136791377913879139791407914179142791437914479145791467914779148791497915079151791527915379154791557915679157791587915979160791617916279163791647916579166791677916879169791707917179172791737917479175791767917779178791797918079181791827918379184791857918679187791887918979190791917919279193791947919579196791977919879199792007920179202792037920479205792067920779208792097921079211792127921379214792157921679217792187921979220792217922279223792247922579226792277922879229792307923179232792337923479235792367923779238792397924079241792427924379244792457924679247792487924979250792517925279253792547925579256792577925879259792607926179262792637926479265792667926779268792697927079271792727927379274792757927679277792787927979280792817928279283792847928579286792877928879289792907929179292792937929479295792967929779298792997930079301793027930379304793057930679307793087930979310793117931279313793147931579316793177931879319793207932179322793237932479325793267932779328793297933079331793327933379334793357933679337793387933979340793417934279343793447934579346793477934879349793507935179352793537935479355793567935779358793597936079361793627936379364793657936679367793687936979370793717937279373793747937579376793777937879379793807938179382793837938479385793867938779388793897939079391793927939379394793957939679397793987939979400794017940279403794047940579406794077940879409794107941179412794137941479415794167941779418794197942079421794227942379424794257942679427794287942979430794317943279433794347943579436794377943879439794407944179442794437944479445794467944779448794497945079451794527945379454794557945679457794587945979460794617946279463794647946579466794677946879469794707947179472794737947479475794767947779478794797948079481794827948379484794857948679487794887948979490794917949279493794947949579496794977949879499795007950179502795037950479505795067950779508795097951079511795127951379514795157951679517795187951979520795217952279523795247952579526795277952879529795307953179532795337953479535795367953779538795397954079541795427954379544795457954679547795487954979550795517955279553795547955579556795577955879559795607956179562795637956479565795667956779568795697957079571795727957379574795757957679577795787957979580795817958279583795847958579586795877958879589795907959179592795937959479595795967959779598795997960079601796027960379604796057960679607796087960979610796117961279613796147961579616796177961879619796207962179622796237962479625796267962779628796297963079631796327963379634796357963679637796387963979640796417964279643796447964579646796477964879649796507965179652796537965479655796567965779658796597966079661796627966379664796657966679667796687966979670796717967279673796747967579676796777967879679796807968179682796837968479685796867968779688796897969079691796927969379694796957969679697796987969979700797017970279703797047970579706797077970879709797107971179712797137971479715797167971779718797197972079721797227972379724797257972679727797287972979730797317973279733797347973579736797377973879739797407974179742797437974479745797467974779748797497975079751797527975379754797557975679757797587975979760797617976279763797647976579766797677976879769797707977179772797737977479775797767977779778797797978079781797827978379784797857978679787797887978979790797917979279793797947979579796797977979879799798007980179802798037980479805798067980779808798097981079811798127981379814798157981679817798187981979820798217982279823798247982579826798277982879829798307983179832798337983479835798367983779838798397984079841798427984379844798457984679847798487984979850798517985279853798547985579856798577985879859798607986179862798637986479865798667986779868798697987079871798727987379874798757987679877798787987979880798817988279883798847988579886798877988879889798907989179892798937989479895798967989779898798997990079901799027990379904799057990679907799087990979910799117991279913799147991579916799177991879919799207992179922799237992479925799267992779928799297993079931799327993379934799357993679937799387993979940799417994279943799447994579946799477994879949799507995179952799537995479955799567995779958799597996079961799627996379964799657996679967799687996979970799717997279973799747997579976799777997879979799807998179982799837998479985799867998779988799897999079991799927999379994799957999679997799987999980000800018000280003800048000580006800078000880009800108001180012800138001480015800168001780018800198002080021800228002380024800258002680027800288002980030800318003280033800348003580036800378003880039800408004180042800438004480045800468004780048800498005080051800528005380054800558005680057800588005980060800618006280063800648006580066800678006880069800708007180072800738007480075800768007780078800798008080081800828008380084800858008680087800888008980090800918009280093800948009580096800978009880099801008010180102801038010480105801068010780108801098011080111801128011380114801158011680117801188011980120801218012280123801248012580126801278012880129801308013180132801338013480135801368013780138801398014080141801428014380144801458014680147801488014980150801518015280153801548015580156801578015880159801608016180162801638016480165801668016780168801698017080171801728017380174801758017680177801788017980180801818018280183801848018580186801878018880189801908019180192801938019480195801968019780198801998020080201802028020380204802058020680207802088020980210802118021280213802148021580216802178021880219802208022180222802238022480225802268022780228802298023080231802328023380234802358023680237802388023980240802418024280243802448024580246802478024880249802508025180252802538025480255802568025780258802598026080261802628026380264802658026680267802688026980270802718027280273802748027580276802778027880279802808028180282802838028480285802868028780288802898029080291802928029380294802958029680297802988029980300803018030280303803048030580306803078030880309803108031180312803138031480315803168031780318803198032080321803228032380324803258032680327803288032980330803318033280333803348033580336803378033880339803408034180342803438034480345803468034780348803498035080351803528035380354803558035680357803588035980360803618036280363803648036580366803678036880369803708037180372803738037480375803768037780378803798038080381803828038380384803858038680387803888038980390803918039280393803948039580396803978039880399804008040180402804038040480405804068040780408804098041080411804128041380414804158041680417804188041980420804218042280423804248042580426804278042880429804308043180432804338043480435804368043780438804398044080441804428044380444804458044680447804488044980450804518045280453804548045580456804578045880459804608046180462804638046480465804668046780468804698047080471804728047380474804758047680477804788047980480804818048280483804848048580486804878048880489804908049180492804938049480495804968049780498804998050080501805028050380504805058050680507805088050980510805118051280513805148051580516805178051880519805208052180522805238052480525805268052780528805298053080531805328053380534805358053680537805388053980540805418054280543805448054580546805478054880549805508055180552805538055480555805568055780558805598056080561805628056380564805658056680567805688056980570805718057280573805748057580576805778057880579805808058180582805838058480585805868058780588805898059080591805928059380594805958059680597805988059980600806018060280603806048060580606806078060880609806108061180612806138061480615806168061780618806198062080621806228062380624806258062680627806288062980630806318063280633806348063580636806378063880639806408064180642806438064480645806468064780648806498065080651806528065380654806558065680657806588065980660806618066280663806648066580666806678066880669806708067180672806738067480675806768067780678806798068080681806828068380684806858068680687806888068980690806918069280693806948069580696806978069880699807008070180702807038070480705807068070780708807098071080711807128071380714807158071680717807188071980720807218072280723807248072580726807278072880729807308073180732807338073480735807368073780738807398074080741807428074380744807458074680747807488074980750807518075280753807548075580756807578075880759807608076180762807638076480765807668076780768807698077080771807728077380774807758077680777807788077980780807818078280783807848078580786807878078880789807908079180792807938079480795807968079780798807998080080801808028080380804808058080680807808088080980810808118081280813808148081580816808178081880819808208082180822808238082480825808268082780828808298083080831808328083380834808358083680837808388083980840808418084280843808448084580846808478084880849808508085180852808538085480855808568085780858808598086080861808628086380864808658086680867808688086980870808718087280873808748087580876808778087880879808808088180882808838088480885808868088780888808898089080891808928089380894808958089680897808988089980900809018090280903809048090580906809078090880909809108091180912809138091480915809168091780918809198092080921809228092380924809258092680927809288092980930809318093280933809348093580936809378093880939809408094180942809438094480945809468094780948809498095080951809528095380954809558095680957809588095980960809618096280963809648096580966809678096880969809708097180972809738097480975809768097780978809798098080981809828098380984809858098680987809888098980990809918099280993809948099580996809978099880999810008100181002810038100481005810068100781008810098101081011810128101381014810158101681017810188101981020810218102281023810248102581026810278102881029810308103181032810338103481035810368103781038810398104081041810428104381044810458104681047810488104981050810518105281053810548105581056810578105881059810608106181062810638106481065810668106781068810698107081071810728107381074810758107681077810788107981080810818108281083810848108581086810878108881089810908109181092810938109481095810968109781098810998110081101811028110381104811058110681107811088110981110811118111281113811148111581116811178111881119811208112181122811238112481125811268112781128811298113081131811328113381134811358113681137811388113981140811418114281143811448114581146811478114881149811508115181152811538115481155811568115781158811598116081161811628116381164811658116681167811688116981170811718117281173811748117581176811778117881179811808118181182811838118481185811868118781188811898119081191811928119381194811958119681197811988119981200812018120281203812048120581206812078120881209812108121181212812138121481215812168121781218812198122081221812228122381224812258122681227812288122981230812318123281233812348123581236812378123881239812408124181242812438124481245812468124781248812498125081251812528125381254812558125681257812588125981260812618126281263812648126581266812678126881269812708127181272812738127481275812768127781278812798128081281812828128381284812858128681287812888128981290812918129281293812948129581296812978129881299813008130181302813038130481305813068130781308813098131081311813128131381314813158131681317813188131981320813218132281323813248132581326813278132881329813308133181332813338133481335813368133781338813398134081341813428134381344813458134681347813488134981350813518135281353813548135581356813578135881359813608136181362813638136481365813668136781368813698137081371813728137381374813758137681377813788137981380813818138281383813848138581386813878138881389813908139181392813938139481395813968139781398813998140081401814028140381404814058140681407814088140981410814118141281413814148141581416814178141881419814208142181422814238142481425814268142781428814298143081431814328143381434814358143681437814388143981440814418144281443814448144581446814478144881449814508145181452814538145481455814568145781458814598146081461814628146381464814658146681467814688146981470814718147281473814748147581476814778147881479814808148181482814838148481485814868148781488814898149081491814928149381494814958149681497814988149981500815018150281503815048150581506815078150881509815108151181512815138151481515815168151781518815198152081521815228152381524815258152681527815288152981530815318153281533815348153581536815378153881539815408154181542815438154481545815468154781548815498155081551815528155381554815558155681557815588155981560815618156281563815648156581566815678156881569815708157181572815738157481575815768157781578815798158081581815828158381584815858158681587815888158981590815918159281593815948159581596815978159881599816008160181602816038160481605816068160781608816098161081611816128161381614816158161681617816188161981620816218162281623816248162581626816278162881629816308163181632816338163481635816368163781638816398164081641816428164381644816458164681647816488164981650816518165281653816548165581656816578165881659816608166181662816638166481665816668166781668816698167081671816728167381674816758167681677816788167981680816818168281683816848168581686816878168881689816908169181692816938169481695816968169781698816998170081701817028170381704817058170681707817088170981710817118171281713817148171581716817178171881719817208172181722817238172481725817268172781728817298173081731817328173381734817358173681737817388173981740817418174281743817448174581746817478174881749817508175181752817538175481755817568175781758817598176081761817628176381764817658176681767817688176981770817718177281773817748177581776817778177881779817808178181782817838178481785817868178781788817898179081791817928179381794817958179681797817988179981800818018180281803818048180581806818078180881809818108181181812818138181481815818168181781818818198182081821818228182381824818258182681827818288182981830818318183281833818348183581836818378183881839818408184181842818438184481845818468184781848818498185081851818528185381854818558185681857818588185981860818618186281863818648186581866818678186881869818708187181872818738187481875818768187781878818798188081881818828188381884818858188681887818888188981890818918189281893818948189581896818978189881899819008190181902819038190481905819068190781908819098191081911819128191381914819158191681917819188191981920819218192281923819248192581926819278192881929819308193181932819338193481935819368193781938819398194081941819428194381944819458194681947819488194981950819518195281953819548195581956819578195881959819608196181962819638196481965819668196781968819698197081971819728197381974819758197681977819788197981980819818198281983819848198581986819878198881989819908199181992819938199481995819968199781998819998200082001820028200382004820058200682007820088200982010820118201282013820148201582016820178201882019820208202182022820238202482025820268202782028820298203082031820328203382034820358203682037820388203982040820418204282043820448204582046820478204882049820508205182052820538205482055820568205782058820598206082061820628206382064820658206682067820688206982070820718207282073820748207582076820778207882079820808208182082820838208482085820868208782088820898209082091820928209382094820958209682097820988209982100821018210282103821048210582106821078210882109821108211182112821138211482115821168211782118821198212082121821228212382124821258212682127821288212982130821318213282133821348213582136821378213882139821408214182142821438214482145821468214782148821498215082151821528215382154821558215682157821588215982160821618216282163821648216582166821678216882169821708217182172821738217482175821768217782178821798218082181821828218382184821858218682187821888218982190821918219282193821948219582196821978219882199822008220182202822038220482205822068220782208822098221082211822128221382214822158221682217822188221982220822218222282223822248222582226822278222882229822308223182232822338223482235822368223782238822398224082241822428224382244822458224682247822488224982250822518225282253822548225582256822578225882259822608226182262822638226482265822668226782268822698227082271822728227382274822758227682277822788227982280822818228282283822848228582286822878228882289822908229182292822938229482295822968229782298822998230082301823028230382304823058230682307823088230982310823118231282313823148231582316823178231882319823208232182322823238232482325823268232782328823298233082331823328233382334823358233682337823388233982340823418234282343823448234582346823478234882349823508235182352823538235482355823568235782358823598236082361823628236382364823658236682367823688236982370823718237282373823748237582376823778237882379823808238182382823838238482385823868238782388823898239082391823928239382394823958239682397823988239982400824018240282403824048240582406824078240882409824108241182412824138241482415824168241782418824198242082421824228242382424824258242682427824288242982430824318243282433824348243582436824378243882439824408244182442824438244482445824468244782448824498245082451824528245382454824558245682457824588245982460824618246282463824648246582466824678246882469824708247182472824738247482475824768247782478824798248082481824828248382484824858248682487824888248982490824918249282493824948249582496824978249882499825008250182502825038250482505825068250782508825098251082511825128251382514825158251682517825188251982520825218252282523825248252582526825278252882529825308253182532825338253482535825368253782538825398254082541825428254382544825458254682547825488254982550825518255282553825548255582556825578255882559825608256182562825638256482565825668256782568825698257082571825728257382574825758257682577825788257982580825818258282583825848258582586825878258882589825908259182592825938259482595825968259782598825998260082601826028260382604826058260682607826088260982610826118261282613826148261582616826178261882619826208262182622826238262482625826268262782628826298263082631826328263382634826358263682637826388263982640826418264282643826448264582646826478264882649826508265182652826538265482655826568265782658826598266082661826628266382664826658266682667826688266982670826718267282673826748267582676826778267882679826808268182682826838268482685826868268782688826898269082691826928269382694826958269682697826988269982700827018270282703827048270582706827078270882709827108271182712827138271482715827168271782718827198272082721827228272382724827258272682727827288272982730827318273282733827348273582736827378273882739827408274182742827438274482745827468274782748827498275082751827528275382754827558275682757827588275982760827618276282763827648276582766827678276882769827708277182772827738277482775827768277782778827798278082781827828278382784827858278682787827888278982790827918279282793827948279582796827978279882799828008280182802828038280482805828068280782808828098281082811828128281382814828158281682817828188281982820828218282282823828248282582826828278282882829828308283182832828338283482835828368283782838828398284082841828428284382844828458284682847828488284982850828518285282853828548285582856828578285882859828608286182862828638286482865828668286782868828698287082871828728287382874828758287682877828788287982880828818288282883828848288582886828878288882889828908289182892828938289482895828968289782898828998290082901829028290382904829058290682907829088290982910829118291282913829148291582916829178291882919829208292182922829238292482925829268292782928829298293082931829328293382934829358293682937829388293982940829418294282943829448294582946829478294882949829508295182952829538295482955829568295782958829598296082961829628296382964829658296682967829688296982970829718297282973829748297582976829778297882979829808298182982829838298482985829868298782988829898299082991829928299382994829958299682997829988299983000830018300283003830048300583006830078300883009830108301183012830138301483015830168301783018830198302083021830228302383024830258302683027830288302983030830318303283033830348303583036830378303883039830408304183042830438304483045830468304783048830498305083051830528305383054830558305683057830588305983060830618306283063830648306583066830678306883069830708307183072830738307483075830768307783078830798308083081830828308383084830858308683087830888308983090830918309283093830948309583096830978309883099831008310183102831038310483105831068310783108831098311083111831128311383114831158311683117831188311983120831218312283123831248312583126831278312883129831308313183132831338313483135831368313783138831398314083141831428314383144831458314683147831488314983150831518315283153831548315583156831578315883159831608316183162831638316483165831668316783168831698317083171831728317383174831758317683177831788317983180831818318283183831848318583186831878318883189831908319183192831938319483195831968319783198831998320083201832028320383204832058320683207832088320983210832118321283213832148321583216832178321883219832208322183222832238322483225832268322783228832298323083231832328323383234832358323683237832388323983240832418324283243832448324583246832478324883249832508325183252832538325483255832568325783258832598326083261832628326383264832658326683267832688326983270832718327283273832748327583276832778327883279832808328183282832838328483285832868328783288832898329083291832928329383294832958329683297832988329983300833018330283303833048330583306833078330883309833108331183312833138331483315833168331783318833198332083321833228332383324833258332683327833288332983330833318333283333833348333583336833378333883339833408334183342833438334483345833468334783348833498335083351833528335383354833558335683357833588335983360833618336283363833648336583366833678336883369833708337183372833738337483375833768337783378833798338083381833828338383384833858338683387833888338983390833918339283393833948339583396833978339883399834008340183402834038340483405834068340783408834098341083411834128341383414834158341683417834188341983420834218342283423834248342583426834278342883429834308343183432834338343483435834368343783438834398344083441834428344383444834458344683447834488344983450834518345283453834548345583456834578345883459834608346183462834638346483465834668346783468834698347083471834728347383474834758347683477834788347983480834818348283483834848348583486834878348883489834908349183492834938349483495834968349783498834998350083501835028350383504835058350683507835088350983510835118351283513835148351583516835178351883519835208352183522835238352483525835268352783528835298353083531835328353383534835358353683537835388353983540835418354283543835448354583546835478354883549835508355183552835538355483555835568355783558835598356083561835628356383564835658356683567835688356983570835718357283573835748357583576835778357883579835808358183582835838358483585835868358783588835898359083591835928359383594835958359683597835988359983600836018360283603836048360583606836078360883609836108361183612836138361483615836168361783618836198362083621836228362383624836258362683627836288362983630836318363283633836348363583636836378363883639836408364183642836438364483645836468364783648836498365083651836528365383654836558365683657836588365983660836618366283663836648366583666836678366883669836708367183672836738367483675836768367783678836798368083681836828368383684836858368683687836888368983690836918369283693836948369583696836978369883699837008370183702837038370483705837068370783708837098371083711837128371383714837158371683717837188371983720837218372283723837248372583726837278372883729837308373183732837338373483735837368373783738837398374083741837428374383744837458374683747837488374983750837518375283753837548375583756837578375883759837608376183762837638376483765837668376783768837698377083771837728377383774837758377683777837788377983780837818378283783837848378583786837878378883789837908379183792837938379483795837968379783798837998380083801838028380383804838058380683807838088380983810838118381283813838148381583816838178381883819838208382183822838238382483825838268382783828838298383083831838328383383834838358383683837838388383983840838418384283843838448384583846838478384883849838508385183852838538385483855838568385783858838598386083861838628386383864838658386683867838688386983870838718387283873838748387583876838778387883879838808388183882838838388483885838868388783888838898389083891838928389383894838958389683897838988389983900839018390283903839048390583906839078390883909839108391183912839138391483915839168391783918839198392083921839228392383924839258392683927839288392983930839318393283933839348393583936839378393883939839408394183942839438394483945839468394783948839498395083951839528395383954839558395683957839588395983960839618396283963839648396583966839678396883969839708397183972839738397483975839768397783978839798398083981839828398383984839858398683987839888398983990839918399283993839948399583996839978399883999840008400184002840038400484005840068400784008840098401084011840128401384014840158401684017840188401984020840218402284023840248402584026840278402884029840308403184032840338403484035840368403784038840398404084041840428404384044840458404684047840488404984050840518405284053840548405584056840578405884059840608406184062840638406484065840668406784068840698407084071840728407384074840758407684077840788407984080840818408284083840848408584086840878408884089840908409184092840938409484095840968409784098840998410084101841028410384104841058410684107841088410984110841118411284113841148411584116841178411884119841208412184122841238412484125841268412784128841298413084131841328413384134841358413684137841388413984140841418414284143841448414584146841478414884149841508415184152841538415484155841568415784158841598416084161841628416384164841658416684167841688416984170841718417284173841748417584176841778417884179841808418184182841838418484185841868418784188841898419084191841928419384194841958419684197841988419984200842018420284203842048420584206842078420884209842108421184212842138421484215842168421784218842198422084221842228422384224842258422684227842288422984230842318423284233842348423584236842378423884239842408424184242842438424484245842468424784248842498425084251842528425384254842558425684257842588425984260842618426284263842648426584266842678426884269842708427184272842738427484275842768427784278842798428084281842828428384284842858428684287842888428984290842918429284293842948429584296842978429884299843008430184302843038430484305843068430784308843098431084311843128431384314843158431684317843188431984320843218432284323843248432584326843278432884329843308433184332843338433484335843368433784338843398434084341843428434384344843458434684347843488434984350843518435284353843548435584356843578435884359843608436184362843638436484365843668436784368843698437084371843728437384374843758437684377843788437984380843818438284383843848438584386843878438884389843908439184392843938439484395843968439784398843998440084401844028440384404844058440684407844088440984410844118441284413844148441584416844178441884419844208442184422844238442484425844268442784428844298443084431844328443384434844358443684437844388443984440844418444284443844448444584446844478444884449844508445184452844538445484455844568445784458844598446084461844628446384464844658446684467844688446984470844718447284473844748447584476844778447884479844808448184482844838448484485844868448784488844898449084491844928449384494844958449684497844988449984500845018450284503845048450584506845078450884509845108451184512845138451484515845168451784518845198452084521845228452384524845258452684527845288452984530845318453284533845348453584536845378453884539845408454184542845438454484545845468454784548845498455084551845528455384554845558455684557845588455984560845618456284563845648456584566845678456884569845708457184572845738457484575845768457784578845798458084581845828458384584845858458684587845888458984590845918459284593845948459584596845978459884599846008460184602846038460484605846068460784608846098461084611846128461384614846158461684617846188461984620846218462284623846248462584626846278462884629846308463184632846338463484635846368463784638846398464084641846428464384644846458464684647846488464984650846518465284653846548465584656846578465884659846608466184662846638466484665846668466784668846698467084671846728467384674846758467684677846788467984680846818468284683846848468584686846878468884689846908469184692846938469484695846968469784698846998470084701847028470384704847058470684707847088470984710847118471284713847148471584716847178471884719847208472184722847238472484725847268472784728847298473084731847328473384734847358473684737847388473984740847418474284743847448474584746847478474884749847508475184752847538475484755847568475784758847598476084761847628476384764847658476684767847688476984770847718477284773847748477584776847778477884779847808478184782847838478484785847868478784788847898479084791847928479384794847958479684797847988479984800848018480284803848048480584806848078480884809848108481184812848138481484815848168481784818848198482084821848228482384824848258482684827848288482984830848318483284833848348483584836848378483884839848408484184842848438484484845848468484784848848498485084851848528485384854848558485684857848588485984860848618486284863848648486584866848678486884869848708487184872848738487484875848768487784878848798488084881848828488384884848858488684887848888488984890848918489284893848948489584896848978489884899849008490184902849038490484905849068490784908849098491084911849128491384914849158491684917849188491984920849218492284923849248492584926849278492884929849308493184932849338493484935849368493784938849398494084941849428494384944849458494684947849488494984950849518495284953849548495584956849578495884959849608496184962849638496484965849668496784968849698497084971849728497384974849758497684977849788497984980849818498284983849848498584986849878498884989849908499184992849938499484995849968499784998849998500085001850028500385004850058500685007850088500985010850118501285013850148501585016850178501885019850208502185022850238502485025850268502785028850298503085031850328503385034850358503685037850388503985040850418504285043850448504585046850478504885049850508505185052850538505485055850568505785058850598506085061850628506385064850658506685067850688506985070850718507285073850748507585076850778507885079850808508185082850838508485085850868508785088850898509085091850928509385094850958509685097850988509985100851018510285103851048510585106851078510885109851108511185112851138511485115851168511785118851198512085121851228512385124851258512685127851288512985130851318513285133851348513585136851378513885139851408514185142851438514485145851468514785148851498515085151851528515385154851558515685157851588515985160851618516285163851648516585166851678516885169851708517185172851738517485175851768517785178851798518085181851828518385184851858518685187851888518985190851918519285193851948519585196851978519885199852008520185202852038520485205852068520785208852098521085211852128521385214852158521685217852188521985220852218522285223852248522585226852278522885229852308523185232852338523485235852368523785238852398524085241852428524385244852458524685247852488524985250852518525285253852548525585256852578525885259852608526185262852638526485265852668526785268852698527085271852728527385274852758527685277852788527985280852818528285283852848528585286852878528885289852908529185292852938529485295852968529785298852998530085301853028530385304853058530685307853088530985310853118531285313853148531585316853178531885319853208532185322853238532485325853268532785328853298533085331853328533385334853358533685337853388533985340853418534285343853448534585346853478534885349853508535185352853538535485355853568535785358853598536085361853628536385364853658536685367853688536985370853718537285373853748537585376853778537885379853808538185382853838538485385853868538785388853898539085391853928539385394853958539685397853988539985400854018540285403854048540585406854078540885409854108541185412854138541485415854168541785418854198542085421854228542385424854258542685427854288542985430854318543285433854348543585436854378543885439854408544185442854438544485445854468544785448854498545085451854528545385454854558545685457854588545985460854618546285463854648546585466854678546885469854708547185472854738547485475854768547785478854798548085481854828548385484854858548685487854888548985490854918549285493854948549585496854978549885499855008550185502855038550485505855068550785508855098551085511855128551385514855158551685517855188551985520855218552285523855248552585526855278552885529855308553185532855338553485535855368553785538855398554085541855428554385544855458554685547855488554985550855518555285553855548555585556855578555885559855608556185562855638556485565855668556785568855698557085571855728557385574855758557685577855788557985580855818558285583855848558585586855878558885589855908559185592855938559485595855968559785598855998560085601856028560385604856058560685607856088560985610856118561285613856148561585616856178561885619856208562185622856238562485625856268562785628856298563085631856328563385634856358563685637856388563985640856418564285643856448564585646856478564885649856508565185652856538565485655856568565785658856598566085661856628566385664856658566685667856688566985670856718567285673856748567585676856778567885679856808568185682856838568485685856868568785688856898569085691856928569385694856958569685697856988569985700857018570285703857048570585706857078570885709857108571185712857138571485715857168571785718857198572085721857228572385724857258572685727857288572985730857318573285733857348573585736857378573885739857408574185742857438574485745857468574785748857498575085751857528575385754857558575685757857588575985760857618576285763857648576585766857678576885769857708577185772857738577485775857768577785778857798578085781857828578385784857858578685787857888578985790857918579285793857948579585796857978579885799858008580185802858038580485805858068580785808858098581085811858128581385814858158581685817858188581985820858218582285823858248582585826858278582885829858308583185832858338583485835858368583785838858398584085841858428584385844858458584685847858488584985850858518585285853858548585585856858578585885859858608586185862858638586485865858668586785868858698587085871858728587385874858758587685877858788587985880858818588285883858848588585886858878588885889858908589185892858938589485895858968589785898858998590085901859028590385904859058590685907859088590985910859118591285913859148591585916859178591885919859208592185922859238592485925859268592785928859298593085931859328593385934859358593685937859388593985940859418594285943859448594585946859478594885949859508595185952859538595485955859568595785958859598596085961859628596385964859658596685967859688596985970859718597285973859748597585976859778597885979859808598185982859838598485985859868598785988859898599085991859928599385994859958599685997859988599986000860018600286003860048600586006860078600886009860108601186012860138601486015860168601786018860198602086021860228602386024860258602686027860288602986030860318603286033860348603586036860378603886039860408604186042860438604486045860468604786048860498605086051860528605386054860558605686057860588605986060860618606286063860648606586066860678606886069860708607186072860738607486075860768607786078860798608086081860828608386084860858608686087860888608986090860918609286093860948609586096860978609886099861008610186102861038610486105861068610786108861098611086111861128611386114861158611686117861188611986120861218612286123861248612586126861278612886129861308613186132861338613486135861368613786138861398614086141861428614386144861458614686147861488614986150861518615286153861548615586156861578615886159861608616186162861638616486165861668616786168861698617086171861728617386174861758617686177861788617986180861818618286183861848618586186861878618886189861908619186192861938619486195861968619786198861998620086201862028620386204862058620686207862088620986210862118621286213862148621586216862178621886219862208622186222862238622486225862268622786228862298623086231862328623386234862358623686237862388623986240862418624286243862448624586246862478624886249862508625186252862538625486255862568625786258862598626086261862628626386264862658626686267862688626986270862718627286273862748627586276862778627886279862808628186282862838628486285862868628786288862898629086291862928629386294862958629686297862988629986300863018630286303863048630586306863078630886309863108631186312863138631486315863168631786318863198632086321863228632386324863258632686327863288632986330863318633286333863348633586336863378633886339863408634186342863438634486345863468634786348863498635086351863528635386354863558635686357863588635986360863618636286363863648636586366863678636886369863708637186372863738637486375863768637786378863798638086381863828638386384863858638686387863888638986390863918639286393863948639586396863978639886399864008640186402864038640486405864068640786408864098641086411864128641386414864158641686417864188641986420864218642286423864248642586426864278642886429864308643186432864338643486435864368643786438864398644086441864428644386444864458644686447864488644986450864518645286453864548645586456864578645886459864608646186462864638646486465864668646786468864698647086471864728647386474864758647686477864788647986480864818648286483864848648586486864878648886489864908649186492864938649486495864968649786498864998650086501865028650386504865058650686507865088650986510865118651286513865148651586516865178651886519865208652186522865238652486525865268652786528865298653086531865328653386534865358653686537865388653986540865418654286543865448654586546865478654886549865508655186552865538655486555865568655786558865598656086561865628656386564865658656686567865688656986570865718657286573865748657586576865778657886579865808658186582865838658486585865868658786588865898659086591865928659386594865958659686597865988659986600866018660286603866048660586606866078660886609866108661186612866138661486615866168661786618866198662086621866228662386624866258662686627866288662986630866318663286633866348663586636866378663886639866408664186642866438664486645866468664786648866498665086651866528665386654866558665686657866588665986660866618666286663866648666586666866678666886669866708667186672866738667486675866768667786678866798668086681866828668386684866858668686687866888668986690866918669286693866948669586696866978669886699867008670186702867038670486705867068670786708867098671086711867128671386714867158671686717867188671986720867218672286723867248672586726867278672886729867308673186732867338673486735867368673786738867398674086741867428674386744867458674686747867488674986750867518675286753867548675586756867578675886759867608676186762867638676486765867668676786768867698677086771867728677386774867758677686777867788677986780867818678286783867848678586786867878678886789867908679186792867938679486795867968679786798867998680086801868028680386804868058680686807868088680986810868118681286813868148681586816868178681886819868208682186822868238682486825868268682786828868298683086831868328683386834868358683686837868388683986840868418684286843868448684586846868478684886849868508685186852868538685486855868568685786858868598686086861868628686386864868658686686867868688686986870868718687286873868748687586876868778687886879868808688186882868838688486885868868688786888868898689086891868928689386894868958689686897868988689986900869018690286903869048690586906869078690886909869108691186912869138691486915869168691786918869198692086921869228692386924869258692686927869288692986930869318693286933869348693586936869378693886939869408694186942869438694486945869468694786948869498695086951869528695386954869558695686957869588695986960869618696286963869648696586966869678696886969869708697186972869738697486975869768697786978869798698086981869828698386984869858698686987869888698986990869918699286993869948699586996869978699886999870008700187002870038700487005870068700787008870098701087011870128701387014870158701687017870188701987020870218702287023870248702587026870278702887029870308703187032870338703487035870368703787038870398704087041870428704387044870458704687047870488704987050870518705287053870548705587056870578705887059870608706187062870638706487065870668706787068870698707087071870728707387074870758707687077870788707987080870818708287083870848708587086870878708887089870908709187092870938709487095870968709787098870998710087101871028710387104871058710687107871088710987110871118711287113871148711587116871178711887119871208712187122871238712487125871268712787128871298713087131871328713387134871358713687137871388713987140871418714287143871448714587146871478714887149871508715187152871538715487155871568715787158871598716087161871628716387164871658716687167871688716987170871718717287173871748717587176871778717887179871808718187182871838718487185871868718787188871898719087191871928719387194871958719687197871988719987200872018720287203872048720587206872078720887209872108721187212872138721487215872168721787218872198722087221872228722387224872258722687227872288722987230872318723287233872348723587236872378723887239872408724187242872438724487245872468724787248872498725087251872528725387254872558725687257872588725987260872618726287263872648726587266872678726887269872708727187272872738727487275872768727787278872798728087281872828728387284872858728687287872888728987290872918729287293872948729587296872978729887299873008730187302873038730487305873068730787308873098731087311873128731387314873158731687317873188731987320873218732287323873248732587326873278732887329873308733187332873338733487335873368733787338873398734087341873428734387344873458734687347873488734987350873518735287353873548735587356873578735887359873608736187362873638736487365873668736787368873698737087371873728737387374873758737687377873788737987380873818738287383873848738587386873878738887389873908739187392873938739487395873968739787398873998740087401874028740387404874058740687407874088740987410874118741287413874148741587416874178741887419874208742187422874238742487425874268742787428874298743087431874328743387434874358743687437874388743987440874418744287443874448744587446874478744887449874508745187452874538745487455874568745787458874598746087461874628746387464874658746687467874688746987470874718747287473874748747587476874778747887479874808748187482874838748487485874868748787488874898749087491874928749387494874958749687497874988749987500875018750287503875048750587506875078750887509875108751187512875138751487515875168751787518875198752087521875228752387524875258752687527875288752987530875318753287533875348753587536875378753887539875408754187542875438754487545875468754787548875498755087551875528755387554875558755687557875588755987560875618756287563875648756587566875678756887569875708757187572875738757487575875768757787578875798758087581875828758387584875858758687587875888758987590875918759287593875948759587596875978759887599876008760187602876038760487605876068760787608876098761087611876128761387614876158761687617876188761987620876218762287623876248762587626876278762887629876308763187632876338763487635876368763787638876398764087641876428764387644876458764687647876488764987650876518765287653876548765587656876578765887659876608766187662876638766487665876668766787668876698767087671876728767387674876758767687677876788767987680876818768287683876848768587686876878768887689876908769187692876938769487695876968769787698876998770087701877028770387704877058770687707877088770987710877118771287713877148771587716877178771887719877208772187722877238772487725877268772787728877298773087731877328773387734877358773687737877388773987740877418774287743877448774587746877478774887749877508775187752877538775487755877568775787758877598776087761877628776387764877658776687767877688776987770877718777287773877748777587776877778777887779877808778187782877838778487785877868778787788877898779087791877928779387794877958779687797877988779987800878018780287803878048780587806878078780887809878108781187812878138781487815878168781787818878198782087821878228782387824878258782687827878288782987830878318783287833878348783587836878378783887839878408784187842878438784487845878468784787848878498785087851878528785387854878558785687857878588785987860878618786287863878648786587866878678786887869878708787187872878738787487875878768787787878878798788087881878828788387884878858788687887878888788987890878918789287893878948789587896878978789887899879008790187902879038790487905879068790787908879098791087911879128791387914879158791687917879188791987920879218792287923879248792587926879278792887929879308793187932879338793487935879368793787938879398794087941879428794387944879458794687947879488794987950879518795287953879548795587956879578795887959879608796187962879638796487965879668796787968879698797087971879728797387974879758797687977879788797987980879818798287983879848798587986879878798887989879908799187992879938799487995879968799787998879998800088001880028800388004880058800688007880088800988010880118801288013880148801588016880178801888019880208802188022880238802488025880268802788028880298803088031880328803388034880358803688037880388803988040880418804288043880448804588046880478804888049880508805188052880538805488055880568805788058880598806088061880628806388064880658806688067880688806988070880718807288073880748807588076880778807888079880808808188082880838808488085880868808788088880898809088091880928809388094880958809688097880988809988100881018810288103881048810588106881078810888109881108811188112881138811488115881168811788118881198812088121881228812388124881258812688127881288812988130881318813288133881348813588136881378813888139881408814188142881438814488145881468814788148881498815088151881528815388154881558815688157881588815988160881618816288163881648816588166881678816888169881708817188172881738817488175881768817788178881798818088181881828818388184881858818688187881888818988190881918819288193881948819588196881978819888199882008820188202882038820488205882068820788208882098821088211882128821388214882158821688217882188821988220882218822288223882248822588226882278822888229882308823188232882338823488235882368823788238882398824088241882428824388244882458824688247882488824988250882518825288253882548825588256882578825888259882608826188262882638826488265882668826788268882698827088271882728827388274882758827688277882788827988280882818828288283882848828588286882878828888289882908829188292882938829488295882968829788298882998830088301883028830388304883058830688307883088830988310883118831288313883148831588316883178831888319883208832188322883238832488325883268832788328883298833088331883328833388334883358833688337883388833988340883418834288343883448834588346883478834888349883508835188352883538835488355883568835788358883598836088361883628836388364883658836688367883688836988370883718837288373883748837588376883778837888379883808838188382883838838488385883868838788388883898839088391883928839388394883958839688397883988839988400884018840288403884048840588406884078840888409884108841188412884138841488415884168841788418884198842088421884228842388424884258842688427884288842988430884318843288433884348843588436884378843888439884408844188442884438844488445884468844788448884498845088451884528845388454884558845688457884588845988460884618846288463884648846588466884678846888469884708847188472884738847488475884768847788478884798848088481884828848388484884858848688487884888848988490884918849288493884948849588496884978849888499885008850188502885038850488505885068850788508885098851088511885128851388514885158851688517885188851988520885218852288523885248852588526885278852888529885308853188532885338853488535885368853788538885398854088541885428854388544885458854688547885488854988550885518855288553885548855588556885578855888559885608856188562885638856488565885668856788568885698857088571885728857388574885758857688577885788857988580885818858288583885848858588586885878858888589885908859188592885938859488595885968859788598885998860088601886028860388604886058860688607886088860988610886118861288613886148861588616886178861888619886208862188622886238862488625886268862788628886298863088631886328863388634886358863688637886388863988640886418864288643886448864588646886478864888649886508865188652886538865488655886568865788658886598866088661886628866388664886658866688667886688866988670886718867288673886748867588676886778867888679886808868188682886838868488685886868868788688886898869088691886928869388694886958869688697886988869988700887018870288703887048870588706887078870888709887108871188712887138871488715887168871788718887198872088721887228872388724887258872688727887288872988730887318873288733887348873588736887378873888739887408874188742887438874488745887468874788748887498875088751887528875388754887558875688757887588875988760887618876288763887648876588766887678876888769887708877188772887738877488775887768877788778887798878088781887828878388784887858878688787887888878988790887918879288793887948879588796887978879888799888008880188802888038880488805888068880788808888098881088811888128881388814888158881688817888188881988820888218882288823888248882588826888278882888829888308883188832888338883488835888368883788838888398884088841888428884388844888458884688847888488884988850888518885288853888548885588856888578885888859888608886188862888638886488865888668886788868888698887088871888728887388874888758887688877888788887988880888818888288883888848888588886888878888888889888908889188892888938889488895888968889788898888998890088901889028890388904889058890688907889088890988910889118891288913889148891588916889178891888919889208892188922889238892488925889268892788928889298893088931889328893388934889358893688937889388893988940889418894288943889448894588946889478894888949889508895188952889538895488955889568895788958889598896088961889628896388964889658896688967889688896988970889718897288973889748897588976889778897888979889808898188982889838898488985889868898788988889898899088991889928899388994889958899688997889988899989000890018900289003890048900589006890078900889009890108901189012890138901489015890168901789018890198902089021890228902389024890258902689027890288902989030890318903289033890348903589036890378903889039890408904189042890438904489045890468904789048890498905089051890528905389054890558905689057890588905989060890618906289063890648906589066890678906889069890708907189072890738907489075890768907789078890798908089081890828908389084890858908689087890888908989090890918909289093890948909589096890978909889099891008910189102891038910489105891068910789108891098911089111891128911389114891158911689117891188911989120891218912289123891248912589126891278912889129891308913189132891338913489135891368913789138891398914089141891428914389144891458914689147891488914989150891518915289153891548915589156891578915889159891608916189162891638916489165891668916789168891698917089171891728917389174891758917689177891788917989180891818918289183891848918589186891878918889189891908919189192891938919489195891968919789198891998920089201892028920389204892058920689207892088920989210892118921289213892148921589216892178921889219892208922189222892238922489225892268922789228892298923089231892328923389234892358923689237892388923989240892418924289243892448924589246892478924889249892508925189252892538925489255892568925789258892598926089261892628926389264892658926689267892688926989270892718927289273892748927589276892778927889279892808928189282892838928489285892868928789288892898929089291892928929389294892958929689297892988929989300893018930289303893048930589306893078930889309893108931189312893138931489315893168931789318893198932089321893228932389324893258932689327893288932989330893318933289333893348933589336893378933889339893408934189342893438934489345893468934789348893498935089351893528935389354893558935689357893588935989360893618936289363893648936589366893678936889369893708937189372893738937489375893768937789378893798938089381893828938389384893858938689387893888938989390893918939289393893948939589396893978939889399894008940189402894038940489405894068940789408894098941089411894128941389414894158941689417894188941989420894218942289423894248942589426894278942889429894308943189432894338943489435894368943789438894398944089441894428944389444894458944689447894488944989450894518945289453894548945589456894578945889459894608946189462894638946489465894668946789468894698947089471894728947389474894758947689477894788947989480894818948289483894848948589486894878948889489894908949189492894938949489495894968949789498894998950089501895028950389504895058950689507895088950989510895118951289513895148951589516895178951889519895208952189522895238952489525895268952789528895298953089531895328953389534895358953689537895388953989540895418954289543895448954589546895478954889549895508955189552895538955489555895568955789558895598956089561895628956389564895658956689567895688956989570895718957289573895748957589576895778957889579895808958189582895838958489585895868958789588895898959089591895928959389594895958959689597895988959989600896018960289603896048960589606896078960889609896108961189612896138961489615896168961789618896198962089621896228962389624896258962689627896288962989630896318963289633896348963589636896378963889639896408964189642896438964489645896468964789648896498965089651896528965389654896558965689657896588965989660896618966289663896648966589666896678966889669896708967189672896738967489675896768967789678896798968089681896828968389684896858968689687896888968989690896918969289693896948969589696896978969889699897008970189702897038970489705897068970789708897098971089711897128971389714897158971689717897188971989720897218972289723897248972589726897278972889729897308973189732897338973489735897368973789738897398974089741897428974389744897458974689747897488974989750897518975289753897548975589756897578975889759897608976189762897638976489765897668976789768897698977089771897728977389774897758977689777897788977989780897818978289783897848978589786897878978889789897908979189792897938979489795897968979789798897998980089801898028980389804898058980689807898088980989810898118981289813898148981589816898178981889819898208982189822898238982489825898268982789828898298983089831898328983389834898358983689837898388983989840898418984289843898448984589846898478984889849898508985189852898538985489855898568985789858898598986089861898628986389864898658986689867898688986989870898718987289873898748987589876898778987889879898808988189882898838988489885898868988789888898898989089891898928989389894898958989689897898988989989900899018990289903899048990589906899078990889909899108991189912899138991489915899168991789918899198992089921899228992389924899258992689927899288992989930899318993289933899348993589936899378993889939899408994189942899438994489945899468994789948899498995089951899528995389954899558995689957899588995989960899618996289963899648996589966899678996889969899708997189972899738997489975899768997789978899798998089981899828998389984899858998689987899888998989990899918999289993899948999589996899978999889999900009000190002900039000490005900069000790008900099001090011900129001390014900159001690017900189001990020900219002290023900249002590026900279002890029900309003190032900339003490035900369003790038900399004090041900429004390044900459004690047900489004990050900519005290053900549005590056900579005890059900609006190062900639006490065900669006790068900699007090071900729007390074900759007690077900789007990080900819008290083900849008590086900879008890089900909009190092900939009490095900969009790098900999010090101901029010390104901059010690107901089010990110901119011290113901149011590116901179011890119901209012190122901239012490125901269012790128901299013090131901329013390134901359013690137901389013990140901419014290143901449014590146901479014890149901509015190152901539015490155901569015790158901599016090161901629016390164901659016690167901689016990170901719017290173901749017590176901779017890179901809018190182901839018490185901869018790188901899019090191901929019390194901959019690197901989019990200902019020290203902049020590206902079020890209902109021190212902139021490215902169021790218902199022090221902229022390224902259022690227902289022990230902319023290233902349023590236902379023890239902409024190242902439024490245902469024790248902499025090251902529025390254902559025690257902589025990260902619026290263902649026590266902679026890269902709027190272902739027490275902769027790278902799028090281902829028390284902859028690287902889028990290902919029290293902949029590296902979029890299903009030190302903039030490305903069030790308903099031090311903129031390314903159031690317903189031990320903219032290323903249032590326903279032890329903309033190332903339033490335903369033790338903399034090341903429034390344903459034690347903489034990350903519035290353903549035590356903579035890359903609036190362903639036490365903669036790368903699037090371903729037390374903759037690377903789037990380903819038290383903849038590386903879038890389903909039190392903939039490395903969039790398903999040090401904029040390404904059040690407904089040990410904119041290413904149041590416904179041890419904209042190422904239042490425904269042790428904299043090431904329043390434904359043690437904389043990440904419044290443904449044590446904479044890449904509045190452904539045490455904569045790458904599046090461904629046390464904659046690467904689046990470904719047290473904749047590476904779047890479904809048190482904839048490485904869048790488904899049090491904929049390494904959049690497904989049990500905019050290503905049050590506905079050890509905109051190512905139051490515905169051790518905199052090521905229052390524905259052690527905289052990530905319053290533905349053590536905379053890539905409054190542905439054490545905469054790548905499055090551905529055390554905559055690557905589055990560905619056290563905649056590566905679056890569905709057190572905739057490575905769057790578905799058090581905829058390584905859058690587905889058990590905919059290593905949059590596905979059890599906009060190602906039060490605906069060790608906099061090611906129061390614906159061690617906189061990620906219062290623906249062590626906279062890629906309063190632906339063490635906369063790638906399064090641906429064390644906459064690647906489064990650906519065290653906549065590656906579065890659906609066190662906639066490665906669066790668906699067090671906729067390674906759067690677906789067990680906819068290683906849068590686906879068890689906909069190692906939069490695906969069790698906999070090701907029070390704907059070690707907089070990710907119071290713907149071590716907179071890719907209072190722907239072490725907269072790728907299073090731907329073390734907359073690737907389073990740907419074290743907449074590746907479074890749907509075190752907539075490755907569075790758907599076090761907629076390764907659076690767907689076990770907719077290773907749077590776907779077890779907809078190782907839078490785907869078790788907899079090791907929079390794907959079690797907989079990800908019080290803908049080590806908079080890809908109081190812908139081490815908169081790818908199082090821908229082390824908259082690827908289082990830908319083290833908349083590836908379083890839908409084190842908439084490845908469084790848908499085090851908529085390854908559085690857908589085990860908619086290863908649086590866908679086890869908709087190872908739087490875908769087790878908799088090881908829088390884908859088690887908889088990890908919089290893908949089590896908979089890899909009090190902909039090490905909069090790908909099091090911909129091390914909159091690917909189091990920909219092290923909249092590926909279092890929909309093190932909339093490935909369093790938909399094090941909429094390944909459094690947909489094990950909519095290953909549095590956909579095890959909609096190962909639096490965909669096790968909699097090971909729097390974909759097690977909789097990980909819098290983909849098590986909879098890989909909099190992909939099490995909969099790998909999100091001910029100391004910059100691007910089100991010910119101291013910149101591016910179101891019910209102191022910239102491025910269102791028910299103091031910329103391034910359103691037910389103991040910419104291043910449104591046910479104891049910509105191052910539105491055910569105791058910599106091061910629106391064910659106691067910689106991070910719107291073910749107591076910779107891079910809108191082910839108491085910869108791088910899109091091910929109391094910959109691097910989109991100911019110291103911049110591106911079110891109911109111191112911139111491115911169111791118911199112091121911229112391124911259112691127911289112991130911319113291133911349113591136911379113891139911409114191142911439114491145911469114791148911499115091151911529115391154911559115691157911589115991160911619116291163911649116591166911679116891169911709117191172911739117491175911769117791178911799118091181911829118391184911859118691187911889118991190911919119291193911949119591196911979119891199912009120191202912039120491205912069120791208912099121091211912129121391214912159121691217912189121991220912219122291223912249122591226912279122891229912309123191232912339123491235912369123791238912399124091241912429124391244912459124691247912489124991250912519125291253912549125591256912579125891259912609126191262912639126491265912669126791268912699127091271912729127391274912759127691277912789127991280912819128291283912849128591286912879128891289912909129191292912939129491295912969129791298912999130091301913029130391304913059130691307913089130991310913119131291313913149131591316913179131891319913209132191322913239132491325913269132791328913299133091331913329133391334913359133691337913389133991340913419134291343913449134591346913479134891349913509135191352913539135491355913569135791358913599136091361913629136391364913659136691367913689136991370913719137291373913749137591376913779137891379913809138191382913839138491385913869138791388913899139091391913929139391394913959139691397913989139991400914019140291403914049140591406914079140891409914109141191412914139141491415914169141791418914199142091421914229142391424914259142691427914289142991430914319143291433914349143591436914379143891439914409144191442914439144491445914469144791448914499145091451914529145391454914559145691457914589145991460914619146291463914649146591466914679146891469914709147191472914739147491475914769147791478914799148091481914829148391484914859148691487914889148991490914919149291493914949149591496914979149891499915009150191502915039150491505915069150791508915099151091511915129151391514915159151691517915189151991520915219152291523915249152591526915279152891529915309153191532915339153491535915369153791538915399154091541915429154391544915459154691547915489154991550915519155291553915549155591556915579155891559915609156191562915639156491565915669156791568915699157091571915729157391574915759157691577915789157991580915819158291583915849158591586915879158891589915909159191592915939159491595915969159791598915999160091601916029160391604916059160691607916089160991610916119161291613916149161591616916179161891619916209162191622916239162491625916269162791628916299163091631916329163391634916359163691637916389163991640916419164291643916449164591646916479164891649916509165191652916539165491655916569165791658916599166091661916629166391664916659166691667916689166991670916719167291673916749167591676916779167891679916809168191682916839168491685916869168791688916899169091691916929169391694916959169691697916989169991700917019170291703917049170591706917079170891709917109171191712917139171491715917169171791718917199172091721917229172391724917259172691727917289172991730917319173291733917349173591736917379173891739917409174191742917439174491745917469174791748917499175091751917529175391754917559175691757917589175991760917619176291763917649176591766917679176891769917709177191772917739177491775917769177791778917799178091781917829178391784917859178691787917889178991790917919179291793917949179591796917979179891799918009180191802918039180491805918069180791808918099181091811918129181391814918159181691817918189181991820918219182291823918249182591826918279182891829918309183191832918339183491835918369183791838918399184091841918429184391844918459184691847918489184991850918519185291853918549185591856918579185891859918609186191862918639186491865918669186791868918699187091871918729187391874918759187691877918789187991880918819188291883918849188591886918879188891889918909189191892918939189491895918969189791898918999190091901919029190391904919059190691907919089190991910919119191291913919149191591916919179191891919919209192191922919239192491925919269192791928919299193091931919329193391934919359193691937919389193991940919419194291943919449194591946919479194891949919509195191952919539195491955919569195791958919599196091961919629196391964919659196691967919689196991970919719197291973919749197591976919779197891979919809198191982919839198491985919869198791988919899199091991919929199391994919959199691997919989199992000920019200292003920049200592006920079200892009920109201192012920139201492015920169201792018920199202092021920229202392024920259202692027920289202992030920319203292033920349203592036920379203892039920409204192042920439204492045920469204792048920499205092051920529205392054920559205692057920589205992060920619206292063920649206592066920679206892069920709207192072920739207492075920769207792078920799208092081920829208392084920859208692087920889208992090920919209292093920949209592096920979209892099921009210192102921039210492105921069210792108921099211092111921129211392114921159211692117921189211992120921219212292123921249212592126921279212892129921309213192132921339213492135921369213792138921399214092141921429214392144921459214692147921489214992150921519215292153921549215592156921579215892159921609216192162921639216492165921669216792168921699217092171921729217392174921759217692177921789217992180921819218292183921849218592186921879218892189921909219192192921939219492195921969219792198921999220092201922029220392204922059220692207922089220992210922119221292213922149221592216922179221892219922209222192222922239222492225922269222792228922299223092231922329223392234922359223692237922389223992240922419224292243922449224592246922479224892249922509225192252922539225492255922569225792258922599226092261922629226392264922659226692267922689226992270922719227292273922749227592276922779227892279922809228192282922839228492285922869228792288922899229092291922929229392294922959229692297922989229992300923019230292303923049230592306923079230892309923109231192312923139231492315923169231792318923199232092321923229232392324923259232692327923289232992330923319233292333923349233592336923379233892339923409234192342923439234492345923469234792348923499235092351923529235392354923559235692357923589235992360923619236292363923649236592366923679236892369923709237192372923739237492375923769237792378923799238092381923829238392384923859238692387923889238992390923919239292393923949239592396923979239892399924009240192402924039240492405924069240792408924099241092411924129241392414924159241692417924189241992420924219242292423924249242592426924279242892429924309243192432924339243492435924369243792438924399244092441924429244392444924459244692447924489244992450924519245292453924549245592456924579245892459924609246192462924639246492465924669246792468924699247092471924729247392474924759247692477924789247992480924819248292483924849248592486924879248892489924909249192492924939249492495924969249792498924999250092501925029250392504925059250692507925089250992510925119251292513925149251592516925179251892519925209252192522925239252492525925269252792528925299253092531925329253392534925359253692537925389253992540925419254292543925449254592546925479254892549925509255192552925539255492555925569255792558925599256092561925629256392564925659256692567925689256992570925719257292573925749257592576925779257892579925809258192582925839258492585925869258792588925899259092591925929259392594925959259692597925989259992600926019260292603926049260592606926079260892609926109261192612926139261492615926169261792618926199262092621926229262392624926259262692627926289262992630926319263292633926349263592636926379263892639926409264192642926439264492645926469264792648926499265092651926529265392654926559265692657926589265992660926619266292663926649266592666926679266892669926709267192672926739267492675926769267792678926799268092681926829268392684926859268692687926889268992690926919269292693926949269592696926979269892699927009270192702927039270492705927069270792708927099271092711927129271392714927159271692717927189271992720927219272292723927249272592726927279272892729927309273192732927339273492735927369273792738927399274092741927429274392744927459274692747927489274992750927519275292753927549275592756927579275892759927609276192762927639276492765927669276792768927699277092771927729277392774927759277692777927789277992780927819278292783927849278592786927879278892789927909279192792927939279492795927969279792798927999280092801928029280392804928059280692807928089280992810928119281292813928149281592816928179281892819928209282192822928239282492825928269282792828928299283092831928329283392834928359283692837928389283992840928419284292843928449284592846928479284892849928509285192852928539285492855928569285792858928599286092861928629286392864928659286692867928689286992870928719287292873928749287592876928779287892879928809288192882928839288492885928869288792888928899289092891928929289392894928959289692897928989289992900929019290292903929049290592906929079290892909929109291192912929139291492915929169291792918929199292092921929229292392924929259292692927929289292992930929319293292933929349293592936929379293892939929409294192942929439294492945929469294792948929499295092951929529295392954929559295692957929589295992960929619296292963929649296592966929679296892969929709297192972929739297492975929769297792978929799298092981929829298392984929859298692987929889298992990929919299292993929949299592996929979299892999930009300193002930039300493005930069300793008930099301093011930129301393014930159301693017930189301993020930219302293023930249302593026930279302893029930309303193032930339303493035930369303793038930399304093041930429304393044930459304693047930489304993050930519305293053930549305593056930579305893059930609306193062930639306493065930669306793068930699307093071930729307393074930759307693077930789307993080930819308293083930849308593086930879308893089930909309193092930939309493095930969309793098930999310093101931029310393104931059310693107931089310993110931119311293113931149311593116931179311893119931209312193122931239312493125931269312793128931299313093131931329313393134931359313693137931389313993140931419314293143931449314593146931479314893149931509315193152931539315493155931569315793158931599316093161931629316393164931659316693167931689316993170931719317293173931749317593176931779317893179931809318193182931839318493185931869318793188931899319093191931929319393194931959319693197931989319993200932019320293203932049320593206932079320893209932109321193212932139321493215932169321793218932199322093221932229322393224932259322693227932289322993230932319323293233932349323593236932379323893239932409324193242932439324493245932469324793248932499325093251932529325393254932559325693257932589325993260932619326293263932649326593266932679326893269932709327193272932739327493275932769327793278932799328093281932829328393284932859328693287932889328993290932919329293293932949329593296932979329893299933009330193302933039330493305933069330793308933099331093311933129331393314933159331693317933189331993320933219332293323933249332593326933279332893329933309333193332933339333493335933369333793338933399334093341933429334393344933459334693347933489334993350933519335293353933549335593356933579335893359933609336193362933639336493365933669336793368933699337093371933729337393374933759337693377933789337993380933819338293383933849338593386933879338893389933909339193392933939339493395933969339793398933999340093401934029340393404934059340693407934089340993410934119341293413934149341593416934179341893419934209342193422
  1. var __decorate=this&&this.__decorate||function(e,t,r,c){var o,f=arguments.length,n=f<3?t:null===c?c=Object.getOwnPropertyDescriptor(t,r):c;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)n=Reflect.decorate(e,t,r,c);else for(var l=e.length-1;l>=0;l--)(o=e[l])&&(n=(f<3?o(n):f>3?o(t,r,n):o(t,r))||n);return f>3&&n&&Object.defineProperty(t,r,n),n};
  2. var __extends=this&&this.__extends||function(){var t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,o){t.__proto__=o}||function(t,o){for(var n in o)o.hasOwnProperty(n)&&(t[n]=o[n])};return function(o,n){function r(){this.constructor=o}t(o,n),o.prototype=null===n?Object.create(n):(r.prototype=n.prototype,new r)}}();
  3. var BABYLON;
  4. (function (BABYLON) {
  5. /**
  6. * EffectFallbacks can be used to add fallbacks (properties to disable) to certain properties when desired to improve performance.
  7. * (Eg. Start at high quality with reflection and fog, if fps is low, remove reflection, if still low remove fog)
  8. */
  9. var EffectFallbacks = /** @class */ (function () {
  10. function EffectFallbacks() {
  11. this._defines = {};
  12. this._currentRank = 32;
  13. this._maxRank = -1;
  14. }
  15. /**
  16. * Removes the fallback from the bound mesh.
  17. */
  18. EffectFallbacks.prototype.unBindMesh = function () {
  19. this._mesh = null;
  20. };
  21. /**
  22. * Adds a fallback on the specified property.
  23. * @param rank The rank of the fallback (Lower ranks will be fallbacked to first)
  24. * @param define The name of the define in the shader
  25. */
  26. EffectFallbacks.prototype.addFallback = function (rank, define) {
  27. if (!this._defines[rank]) {
  28. if (rank < this._currentRank) {
  29. this._currentRank = rank;
  30. }
  31. if (rank > this._maxRank) {
  32. this._maxRank = rank;
  33. }
  34. this._defines[rank] = new Array();
  35. }
  36. this._defines[rank].push(define);
  37. };
  38. /**
  39. * Sets the mesh to use CPU skinning when needing to fallback.
  40. * @param rank The rank of the fallback (Lower ranks will be fallbacked to first)
  41. * @param mesh The mesh to use the fallbacks.
  42. */
  43. EffectFallbacks.prototype.addCPUSkinningFallback = function (rank, mesh) {
  44. this._mesh = mesh;
  45. if (rank < this._currentRank) {
  46. this._currentRank = rank;
  47. }
  48. if (rank > this._maxRank) {
  49. this._maxRank = rank;
  50. }
  51. };
  52. Object.defineProperty(EffectFallbacks.prototype, "isMoreFallbacks", {
  53. /**
  54. * Checks to see if more fallbacks are still availible.
  55. */
  56. get: function () {
  57. return this._currentRank <= this._maxRank;
  58. },
  59. enumerable: true,
  60. configurable: true
  61. });
  62. /**
  63. * Removes the defines that shoould be removed when falling back.
  64. * @param currentDefines defines the current define statements for the shader.
  65. * @param effect defines the current effect we try to compile
  66. * @returns The resulting defines with defines of the current rank removed.
  67. */
  68. EffectFallbacks.prototype.reduce = function (currentDefines, effect) {
  69. // First we try to switch to CPU skinning
  70. if (this._mesh && this._mesh.computeBonesUsingShaders && this._mesh.numBoneInfluencers > 0 && this._mesh.material) {
  71. this._mesh.computeBonesUsingShaders = false;
  72. currentDefines = currentDefines.replace("#define NUM_BONE_INFLUENCERS " + this._mesh.numBoneInfluencers, "#define NUM_BONE_INFLUENCERS 0");
  73. var scene = this._mesh.getScene();
  74. for (var index = 0; index < scene.meshes.length; index++) {
  75. var otherMesh = scene.meshes[index];
  76. if (!otherMesh.material) {
  77. continue;
  78. }
  79. if (!otherMesh.computeBonesUsingShaders || otherMesh.numBoneInfluencers === 0) {
  80. continue;
  81. }
  82. if (otherMesh.material.getEffect() === effect) {
  83. otherMesh.computeBonesUsingShaders = false;
  84. }
  85. else {
  86. for (var _i = 0, _a = otherMesh.subMeshes; _i < _a.length; _i++) {
  87. var subMesh = _a[_i];
  88. var subMeshEffect = subMesh.effect;
  89. if (subMeshEffect === effect) {
  90. otherMesh.computeBonesUsingShaders = false;
  91. break;
  92. }
  93. }
  94. }
  95. }
  96. }
  97. else {
  98. var currentFallbacks = this._defines[this._currentRank];
  99. if (currentFallbacks) {
  100. for (var index = 0; index < currentFallbacks.length; index++) {
  101. currentDefines = currentDefines.replace("#define " + currentFallbacks[index], "");
  102. }
  103. }
  104. this._currentRank++;
  105. }
  106. return currentDefines;
  107. };
  108. return EffectFallbacks;
  109. }());
  110. BABYLON.EffectFallbacks = EffectFallbacks;
  111. /**
  112. * Options to be used when creating an effect.
  113. */
  114. var EffectCreationOptions = /** @class */ (function () {
  115. function EffectCreationOptions() {
  116. }
  117. return EffectCreationOptions;
  118. }());
  119. BABYLON.EffectCreationOptions = EffectCreationOptions;
  120. /**
  121. * Effect containing vertex and fragment shader that can be executed on an object.
  122. */
  123. var Effect = /** @class */ (function () {
  124. /**
  125. * Instantiates an effect.
  126. * An effect can be used to create/manage/execute vertex and fragment shaders.
  127. * @param baseName Name of the effect.
  128. * @param attributesNamesOrOptions List of attribute names that will be passed to the shader or set of all options to create the effect.
  129. * @param uniformsNamesOrEngine List of uniform variable names that will be passed to the shader or the engine that will be used to render effect.
  130. * @param samplers List of sampler variables that will be passed to the shader.
  131. * @param engine Engine to be used to render the effect
  132. * @param defines Define statements to be added to the shader.
  133. * @param fallbacks Possible fallbacks for this effect to improve performance when needed.
  134. * @param onCompiled Callback that will be called when the shader is compiled.
  135. * @param onError Callback that will be called if an error occurs during shader compilation.
  136. * @param indexParameters Parameters to be used with Babylons include syntax to iterate over an array (eg. {lights: 10})
  137. */
  138. function Effect(baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, engine, defines, fallbacks, onCompiled, onError, indexParameters) {
  139. if (samplers === void 0) { samplers = null; }
  140. if (defines === void 0) { defines = null; }
  141. if (fallbacks === void 0) { fallbacks = null; }
  142. if (onCompiled === void 0) { onCompiled = null; }
  143. if (onError === void 0) { onError = null; }
  144. var _this = this;
  145. /**
  146. * Unique ID of the effect.
  147. */
  148. this.uniqueId = 0;
  149. /**
  150. * Observable that will be called when the shader is compiled.
  151. */
  152. this.onCompileObservable = new BABYLON.Observable();
  153. /**
  154. * Observable that will be called if an error occurs during shader compilation.
  155. */
  156. this.onErrorObservable = new BABYLON.Observable();
  157. /**
  158. * Observable that will be called when effect is bound.
  159. */
  160. this.onBindObservable = new BABYLON.Observable();
  161. this._uniformBuffersNames = {};
  162. this._isReady = false;
  163. this._compilationError = "";
  164. this.name = baseName;
  165. if (attributesNamesOrOptions.attributes) {
  166. var options = attributesNamesOrOptions;
  167. this._engine = uniformsNamesOrEngine;
  168. this._attributesNames = options.attributes;
  169. this._uniformsNames = options.uniformsNames.concat(options.samplers);
  170. this._samplers = options.samplers;
  171. this.defines = options.defines;
  172. this.onError = options.onError;
  173. this.onCompiled = options.onCompiled;
  174. this._fallbacks = options.fallbacks;
  175. this._indexParameters = options.indexParameters;
  176. this._transformFeedbackVaryings = options.transformFeedbackVaryings;
  177. if (options.uniformBuffersNames) {
  178. for (var i = 0; i < options.uniformBuffersNames.length; i++) {
  179. this._uniformBuffersNames[options.uniformBuffersNames[i]] = i;
  180. }
  181. }
  182. }
  183. else {
  184. this._engine = engine;
  185. this.defines = defines;
  186. this._uniformsNames = uniformsNamesOrEngine.concat(samplers);
  187. this._samplers = samplers;
  188. this._attributesNames = attributesNamesOrOptions;
  189. this.onError = onError;
  190. this.onCompiled = onCompiled;
  191. this._indexParameters = indexParameters;
  192. this._fallbacks = fallbacks;
  193. }
  194. this.uniqueId = Effect._uniqueIdSeed++;
  195. var vertexSource;
  196. var fragmentSource;
  197. if (baseName.vertexElement) {
  198. vertexSource = document.getElementById(baseName.vertexElement);
  199. if (!vertexSource) {
  200. vertexSource = baseName.vertexElement;
  201. }
  202. }
  203. else {
  204. vertexSource = baseName.vertex || baseName;
  205. }
  206. if (baseName.fragmentElement) {
  207. fragmentSource = document.getElementById(baseName.fragmentElement);
  208. if (!fragmentSource) {
  209. fragmentSource = baseName.fragmentElement;
  210. }
  211. }
  212. else {
  213. fragmentSource = baseName.fragment || baseName;
  214. }
  215. var finalVertexCode;
  216. this._loadVertexShaderAsync(vertexSource)
  217. .then(function (vertexCode) {
  218. return _this._processIncludesAsync(vertexCode);
  219. })
  220. .then(function (vertexCodeWithIncludes) {
  221. finalVertexCode = _this._processShaderConversion(vertexCodeWithIncludes, false);
  222. return _this._loadFragmentShaderAsync(fragmentSource);
  223. })
  224. .then(function (fragmentCode) {
  225. return _this._processIncludesAsync(fragmentCode);
  226. })
  227. .then(function (fragmentCodeWithIncludes) {
  228. var migratedFragmentCode = _this._processShaderConversion(fragmentCodeWithIncludes, true);
  229. if (baseName) {
  230. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  231. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  232. _this._vertexSourceCode = "#define SHADER_NAME vertex:" + vertex + "\n" + finalVertexCode;
  233. _this._fragmentSourceCode = "#define SHADER_NAME fragment:" + fragment + "\n" + migratedFragmentCode;
  234. }
  235. else {
  236. _this._vertexSourceCode = finalVertexCode;
  237. _this._fragmentSourceCode = migratedFragmentCode;
  238. }
  239. _this._prepareEffect();
  240. });
  241. }
  242. Object.defineProperty(Effect.prototype, "key", {
  243. /**
  244. * Unique key for this effect
  245. */
  246. get: function () {
  247. return this._key;
  248. },
  249. enumerable: true,
  250. configurable: true
  251. });
  252. /**
  253. * If the effect has been compiled and prepared.
  254. * @returns if the effect is compiled and prepared.
  255. */
  256. Effect.prototype.isReady = function () {
  257. return this._isReady;
  258. };
  259. /**
  260. * The engine the effect was initialized with.
  261. * @returns the engine.
  262. */
  263. Effect.prototype.getEngine = function () {
  264. return this._engine;
  265. };
  266. /**
  267. * The compiled webGL program for the effect
  268. * @returns the webGL program.
  269. */
  270. Effect.prototype.getProgram = function () {
  271. return this._program;
  272. };
  273. /**
  274. * The set of names of attribute variables for the shader.
  275. * @returns An array of attribute names.
  276. */
  277. Effect.prototype.getAttributesNames = function () {
  278. return this._attributesNames;
  279. };
  280. /**
  281. * Returns the attribute at the given index.
  282. * @param index The index of the attribute.
  283. * @returns The location of the attribute.
  284. */
  285. Effect.prototype.getAttributeLocation = function (index) {
  286. return this._attributes[index];
  287. };
  288. /**
  289. * Returns the attribute based on the name of the variable.
  290. * @param name of the attribute to look up.
  291. * @returns the attribute location.
  292. */
  293. Effect.prototype.getAttributeLocationByName = function (name) {
  294. var index = this._attributesNames.indexOf(name);
  295. return this._attributes[index];
  296. };
  297. /**
  298. * The number of attributes.
  299. * @returns the numnber of attributes.
  300. */
  301. Effect.prototype.getAttributesCount = function () {
  302. return this._attributes.length;
  303. };
  304. /**
  305. * Gets the index of a uniform variable.
  306. * @param uniformName of the uniform to look up.
  307. * @returns the index.
  308. */
  309. Effect.prototype.getUniformIndex = function (uniformName) {
  310. return this._uniformsNames.indexOf(uniformName);
  311. };
  312. /**
  313. * Returns the attribute based on the name of the variable.
  314. * @param uniformName of the uniform to look up.
  315. * @returns the location of the uniform.
  316. */
  317. Effect.prototype.getUniform = function (uniformName) {
  318. return this._uniforms[this._uniformsNames.indexOf(uniformName)];
  319. };
  320. /**
  321. * Returns an array of sampler variable names
  322. * @returns The array of sampler variable neames.
  323. */
  324. Effect.prototype.getSamplers = function () {
  325. return this._samplers;
  326. };
  327. /**
  328. * The error from the last compilation.
  329. * @returns the error string.
  330. */
  331. Effect.prototype.getCompilationError = function () {
  332. return this._compilationError;
  333. };
  334. /**
  335. * Adds a callback to the onCompiled observable and call the callback imediatly if already ready.
  336. * @param func The callback to be used.
  337. */
  338. Effect.prototype.executeWhenCompiled = function (func) {
  339. if (this.isReady()) {
  340. func(this);
  341. return;
  342. }
  343. this.onCompileObservable.add(function (effect) {
  344. func(effect);
  345. });
  346. };
  347. /** @ignore */
  348. Effect.prototype._loadVertexShaderAsync = function (vertex) {
  349. if (BABYLON.Tools.IsWindowObjectExist()) {
  350. // DOM element ?
  351. if (vertex instanceof HTMLElement) {
  352. var vertexCode = BABYLON.Tools.GetDOMTextContent(vertex);
  353. return Promise.resolve(vertexCode);
  354. }
  355. }
  356. // Base64 encoded ?
  357. if (vertex.substr(0, 7) === "base64:") {
  358. var vertexBinary = window.atob(vertex.substr(7));
  359. return Promise.resolve(vertexBinary);
  360. }
  361. // Is in local store ?
  362. if (Effect.ShadersStore[vertex + "VertexShader"]) {
  363. return Promise.resolve(Effect.ShadersStore[vertex + "VertexShader"]);
  364. }
  365. var vertexShaderUrl;
  366. if (vertex[0] === "." || vertex[0] === "/" || vertex.indexOf("http") > -1) {
  367. vertexShaderUrl = vertex;
  368. }
  369. else {
  370. vertexShaderUrl = BABYLON.Engine.ShadersRepository + vertex;
  371. }
  372. // Vertex shader
  373. return this._engine._loadFileAsync(vertexShaderUrl + ".vertex.fx");
  374. };
  375. /** @ignore */
  376. Effect.prototype._loadFragmentShaderAsync = function (fragment) {
  377. if (BABYLON.Tools.IsWindowObjectExist()) {
  378. // DOM element ?
  379. if (fragment instanceof HTMLElement) {
  380. var fragmentCode = BABYLON.Tools.GetDOMTextContent(fragment);
  381. return Promise.resolve(fragmentCode);
  382. }
  383. }
  384. // Base64 encoded ?
  385. if (fragment.substr(0, 7) === "base64:") {
  386. var fragmentBinary = window.atob(fragment.substr(7));
  387. return Promise.resolve(fragmentBinary);
  388. }
  389. // Is in local store ?
  390. if (Effect.ShadersStore[fragment + "PixelShader"]) {
  391. return Promise.resolve(Effect.ShadersStore[fragment + "PixelShader"]);
  392. }
  393. if (Effect.ShadersStore[fragment + "FragmentShader"]) {
  394. return Promise.resolve(Effect.ShadersStore[fragment + "FragmentShader"]);
  395. }
  396. var fragmentShaderUrl;
  397. if (fragment[0] === "." || fragment[0] === "/" || fragment.indexOf("http") > -1) {
  398. fragmentShaderUrl = fragment;
  399. }
  400. else {
  401. fragmentShaderUrl = BABYLON.Engine.ShadersRepository + fragment;
  402. }
  403. // Fragment shader
  404. return this._engine._loadFileAsync(fragmentShaderUrl + ".fragment.fx");
  405. };
  406. Effect.prototype._dumpShadersSource = function (vertexCode, fragmentCode, defines) {
  407. // Rebuild shaders source code
  408. var shaderVersion = (this._engine.webGLVersion > 1) ? "#version 300 es\n" : "";
  409. var prefix = shaderVersion + (defines ? defines + "\n" : "");
  410. vertexCode = prefix + vertexCode;
  411. fragmentCode = prefix + fragmentCode;
  412. // Number lines of shaders source code
  413. var i = 2;
  414. var regex = /\n/gm;
  415. var formattedVertexCode = "\n1\t" + vertexCode.replace(regex, function () { return "\n" + (i++) + "\t"; });
  416. i = 2;
  417. var formattedFragmentCode = "\n1\t" + fragmentCode.replace(regex, function () { return "\n" + (i++) + "\t"; });
  418. // Dump shaders name and formatted source code
  419. if (this.name.vertexElement) {
  420. BABYLON.Tools.Error("Vertex shader: " + this.name.vertexElement + formattedVertexCode);
  421. BABYLON.Tools.Error("Fragment shader: " + this.name.fragmentElement + formattedFragmentCode);
  422. }
  423. else if (this.name.vertex) {
  424. BABYLON.Tools.Error("Vertex shader: " + this.name.vertex + formattedVertexCode);
  425. BABYLON.Tools.Error("Fragment shader: " + this.name.fragment + formattedFragmentCode);
  426. }
  427. else {
  428. BABYLON.Tools.Error("Vertex shader: " + this.name + formattedVertexCode);
  429. BABYLON.Tools.Error("Fragment shader: " + this.name + formattedFragmentCode);
  430. }
  431. };
  432. ;
  433. Effect.prototype._processShaderConversion = function (sourceCode, isFragment) {
  434. var preparedSourceCode = this._processPrecision(sourceCode);
  435. if (this._engine.webGLVersion == 1) {
  436. return preparedSourceCode;
  437. }
  438. // Already converted
  439. if (preparedSourceCode.indexOf("#version 3") !== -1) {
  440. return preparedSourceCode.replace("#version 300 es", "");
  441. }
  442. var hasDrawBuffersExtension = preparedSourceCode.search(/#extension.+GL_EXT_draw_buffers.+require/) !== -1;
  443. // Remove extensions
  444. // #extension GL_OES_standard_derivatives : enable
  445. // #extension GL_EXT_shader_texture_lod : enable
  446. // #extension GL_EXT_frag_depth : enable
  447. // #extension GL_EXT_draw_buffers : require
  448. var regex = /#extension.+(GL_OES_standard_derivatives|GL_EXT_shader_texture_lod|GL_EXT_frag_depth|GL_EXT_draw_buffers).+(enable|require)/g;
  449. var result = preparedSourceCode.replace(regex, "");
  450. // Migrate to GLSL v300
  451. result = result.replace(/varying(?![\n\r])\s/g, isFragment ? "in " : "out ");
  452. result = result.replace(/attribute[ \t]/g, "in ");
  453. result = result.replace(/[ \t]attribute/g, " in");
  454. if (isFragment) {
  455. result = result.replace(/texture2DLodEXT\s*\(/g, "textureLod(");
  456. result = result.replace(/textureCubeLodEXT\s*\(/g, "textureLod(");
  457. result = result.replace(/texture2D\s*\(/g, "texture(");
  458. result = result.replace(/textureCube\s*\(/g, "texture(");
  459. result = result.replace(/gl_FragDepthEXT/g, "gl_FragDepth");
  460. result = result.replace(/gl_FragColor/g, "glFragColor");
  461. result = result.replace(/gl_FragData/g, "glFragData");
  462. result = result.replace(/void\s+?main\s*\(/g, (hasDrawBuffersExtension ? "" : "out vec4 glFragColor;\n") + "void main(");
  463. }
  464. return result;
  465. };
  466. Effect.prototype._processIncludesAsync = function (sourceCode) {
  467. var _this = this;
  468. return new Promise(function (resolve, reject) {
  469. var regex = /#include<(.+)>(\((.*)\))*(\[(.*)\])*/g;
  470. var match = regex.exec(sourceCode);
  471. var returnValue = sourceCode;
  472. while (match != null) {
  473. var includeFile = match[1];
  474. // Uniform declaration
  475. if (includeFile.indexOf("__decl__") !== -1) {
  476. includeFile = includeFile.replace(/__decl__/, "");
  477. if (_this._engine.supportsUniformBuffers) {
  478. includeFile = includeFile.replace(/Vertex/, "Ubo");
  479. includeFile = includeFile.replace(/Fragment/, "Ubo");
  480. }
  481. includeFile = includeFile + "Declaration";
  482. }
  483. if (Effect.IncludesShadersStore[includeFile]) {
  484. // Substitution
  485. var includeContent = Effect.IncludesShadersStore[includeFile];
  486. if (match[2]) {
  487. var splits = match[3].split(",");
  488. for (var index = 0; index < splits.length; index += 2) {
  489. var source = new RegExp(splits[index], "g");
  490. var dest = splits[index + 1];
  491. includeContent = includeContent.replace(source, dest);
  492. }
  493. }
  494. if (match[4]) {
  495. var indexString = match[5];
  496. if (indexString.indexOf("..") !== -1) {
  497. var indexSplits = indexString.split("..");
  498. var minIndex = parseInt(indexSplits[0]);
  499. var maxIndex = parseInt(indexSplits[1]);
  500. var sourceIncludeContent = includeContent.slice(0);
  501. includeContent = "";
  502. if (isNaN(maxIndex)) {
  503. maxIndex = _this._indexParameters[indexSplits[1]];
  504. }
  505. for (var i = minIndex; i < maxIndex; i++) {
  506. if (!_this._engine.supportsUniformBuffers) {
  507. // Ubo replacement
  508. sourceIncludeContent = sourceIncludeContent.replace(/light\{X\}.(\w*)/g, function (str, p1) {
  509. return p1 + "{X}";
  510. });
  511. }
  512. includeContent += sourceIncludeContent.replace(/\{X\}/g, i.toString()) + "\n";
  513. }
  514. }
  515. else {
  516. if (!_this._engine.supportsUniformBuffers) {
  517. // Ubo replacement
  518. includeContent = includeContent.replace(/light\{X\}.(\w*)/g, function (str, p1) {
  519. return p1 + "{X}";
  520. });
  521. }
  522. includeContent = includeContent.replace(/\{X\}/g, indexString);
  523. }
  524. }
  525. // Replace
  526. returnValue = returnValue.replace(match[0], includeContent);
  527. }
  528. else {
  529. var includeShaderUrl = BABYLON.Engine.ShadersRepository + "ShadersInclude/" + includeFile + ".fx";
  530. _this._engine._loadFileAsync(includeShaderUrl)
  531. .then(function (fileContent) {
  532. Effect.IncludesShadersStore[includeFile] = fileContent;
  533. return _this._processIncludesAsync(returnValue);
  534. })
  535. .then(function (returnValue) {
  536. resolve(returnValue);
  537. });
  538. return;
  539. }
  540. match = regex.exec(sourceCode);
  541. }
  542. resolve(returnValue);
  543. });
  544. };
  545. Effect.prototype._processPrecision = function (source) {
  546. if (source.indexOf("precision highp float") === -1) {
  547. if (!this._engine.getCaps().highPrecisionShaderSupported) {
  548. source = "precision mediump float;\n" + source;
  549. }
  550. else {
  551. source = "precision highp float;\n" + source;
  552. }
  553. }
  554. else {
  555. if (!this._engine.getCaps().highPrecisionShaderSupported) {
  556. source = source.replace("precision highp float", "precision mediump float");
  557. }
  558. }
  559. return source;
  560. };
  561. /**
  562. * Recompiles the webGL program
  563. * @param vertexSourceCode The source code for the vertex shader.
  564. * @param fragmentSourceCode The source code for the fragment shader.
  565. * @param onCompiled Callback called when completed.
  566. * @param onError Callback called on error.
  567. */
  568. Effect.prototype._rebuildProgram = function (vertexSourceCode, fragmentSourceCode, onCompiled, onError) {
  569. var _this = this;
  570. this._isReady = false;
  571. this._vertexSourceCodeOverride = vertexSourceCode;
  572. this._fragmentSourceCodeOverride = fragmentSourceCode;
  573. this.onError = function (effect, error) {
  574. if (onError) {
  575. onError(error);
  576. }
  577. };
  578. this.onCompiled = function () {
  579. var scenes = _this.getEngine().scenes;
  580. for (var i = 0; i < scenes.length; i++) {
  581. scenes[i].markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  582. }
  583. if (onCompiled) {
  584. onCompiled(_this._program);
  585. }
  586. };
  587. this._fallbacks = null;
  588. this._prepareEffect();
  589. };
  590. /**
  591. * Gets the uniform locations of the the specified variable names
  592. * @param names THe names of the variables to lookup.
  593. * @returns Array of locations in the same order as variable names.
  594. */
  595. Effect.prototype.getSpecificUniformLocations = function (names) {
  596. var engine = this._engine;
  597. return engine.getUniforms(this._program, names);
  598. };
  599. /**
  600. * Prepares the effect
  601. */
  602. Effect.prototype._prepareEffect = function () {
  603. var attributesNames = this._attributesNames;
  604. var defines = this.defines;
  605. var fallbacks = this._fallbacks;
  606. this._valueCache = {};
  607. var previousProgram = this._program;
  608. try {
  609. var engine = this._engine;
  610. if (this._vertexSourceCodeOverride && this._fragmentSourceCodeOverride) {
  611. this._program = engine.createRawShaderProgram(this._vertexSourceCodeOverride, this._fragmentSourceCodeOverride, undefined, this._transformFeedbackVaryings);
  612. }
  613. else {
  614. this._program = engine.createShaderProgram(this._vertexSourceCode, this._fragmentSourceCode, defines, undefined, this._transformFeedbackVaryings);
  615. }
  616. this._program.__SPECTOR_rebuildProgram = this._rebuildProgram.bind(this);
  617. if (engine.supportsUniformBuffers) {
  618. for (var name in this._uniformBuffersNames) {
  619. this.bindUniformBlock(name, this._uniformBuffersNames[name]);
  620. }
  621. }
  622. this._uniforms = engine.getUniforms(this._program, this._uniformsNames);
  623. this._attributes = engine.getAttributes(this._program, attributesNames);
  624. var index;
  625. for (index = 0; index < this._samplers.length; index++) {
  626. var sampler = this.getUniform(this._samplers[index]);
  627. if (sampler == null) {
  628. this._samplers.splice(index, 1);
  629. index--;
  630. }
  631. }
  632. engine.bindSamplers(this);
  633. this._compilationError = "";
  634. this._isReady = true;
  635. if (this.onCompiled) {
  636. this.onCompiled(this);
  637. }
  638. this.onCompileObservable.notifyObservers(this);
  639. this.onCompileObservable.clear();
  640. // Unbind mesh reference in fallbacks
  641. if (this._fallbacks) {
  642. this._fallbacks.unBindMesh();
  643. }
  644. if (previousProgram) {
  645. this.getEngine()._deleteProgram(previousProgram);
  646. }
  647. }
  648. catch (e) {
  649. this._compilationError = e.message;
  650. // Let's go through fallbacks then
  651. BABYLON.Tools.Error("Unable to compile effect:");
  652. BABYLON.Tools.Error("Uniforms: " + this._uniformsNames.map(function (uniform) {
  653. return " " + uniform;
  654. }));
  655. BABYLON.Tools.Error("Attributes: " + attributesNames.map(function (attribute) {
  656. return " " + attribute;
  657. }));
  658. this._dumpShadersSource(this._vertexSourceCode, this._fragmentSourceCode, defines);
  659. BABYLON.Tools.Error("Error: " + this._compilationError);
  660. if (previousProgram) {
  661. this._program = previousProgram;
  662. this._isReady = true;
  663. if (this.onError) {
  664. this.onError(this, this._compilationError);
  665. }
  666. this.onErrorObservable.notifyObservers(this);
  667. }
  668. if (fallbacks && fallbacks.isMoreFallbacks) {
  669. BABYLON.Tools.Error("Trying next fallback.");
  670. this.defines = fallbacks.reduce(this.defines, this);
  671. this._prepareEffect();
  672. }
  673. else {
  674. if (this.onError) {
  675. this.onError(this, this._compilationError);
  676. }
  677. this.onErrorObservable.notifyObservers(this);
  678. this.onErrorObservable.clear();
  679. // Unbind mesh reference in fallbacks
  680. if (this._fallbacks) {
  681. this._fallbacks.unBindMesh();
  682. }
  683. }
  684. }
  685. };
  686. Object.defineProperty(Effect.prototype, "isSupported", {
  687. /**
  688. * Checks if the effect is supported. (Must be called after compilation)
  689. */
  690. get: function () {
  691. return this._compilationError === "";
  692. },
  693. enumerable: true,
  694. configurable: true
  695. });
  696. /**
  697. * Binds a texture to the engine to be used as output of the shader.
  698. * @param channel Name of the output variable.
  699. * @param texture Texture to bind.
  700. */
  701. Effect.prototype._bindTexture = function (channel, texture) {
  702. this._engine._bindTexture(this._samplers.indexOf(channel), texture);
  703. };
  704. /**
  705. * Sets a texture on the engine to be used in the shader.
  706. * @param channel Name of the sampler variable.
  707. * @param texture Texture to set.
  708. */
  709. Effect.prototype.setTexture = function (channel, texture) {
  710. this._engine.setTexture(this._samplers.indexOf(channel), this.getUniform(channel), texture);
  711. };
  712. /**
  713. * Sets an array of textures on the engine to be used in the shader.
  714. * @param channel Name of the variable.
  715. * @param textures Textures to set.
  716. */
  717. Effect.prototype.setTextureArray = function (channel, textures) {
  718. if (this._samplers.indexOf(channel + "Ex") === -1) {
  719. var initialPos = this._samplers.indexOf(channel);
  720. for (var index = 1; index < textures.length; index++) {
  721. this._samplers.splice(initialPos + index, 0, channel + "Ex");
  722. }
  723. }
  724. this._engine.setTextureArray(this._samplers.indexOf(channel), this.getUniform(channel), textures);
  725. };
  726. /**
  727. * Sets a texture to be the input of the specified post process. (To use the output, pass in the next post process in the pipeline)
  728. * @param channel Name of the sampler variable.
  729. * @param postProcess Post process to get the input texture from.
  730. */
  731. Effect.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  732. this._engine.setTextureFromPostProcess(this._samplers.indexOf(channel), postProcess);
  733. };
  734. /** @ignore */
  735. Effect.prototype._cacheMatrix = function (uniformName, matrix) {
  736. var cache = this._valueCache[uniformName];
  737. var flag = matrix.updateFlag;
  738. if (cache !== undefined && cache === flag) {
  739. return false;
  740. }
  741. this._valueCache[uniformName] = flag;
  742. return true;
  743. };
  744. /** @ignore */
  745. Effect.prototype._cacheFloat2 = function (uniformName, x, y) {
  746. var cache = this._valueCache[uniformName];
  747. if (!cache) {
  748. cache = [x, y];
  749. this._valueCache[uniformName] = cache;
  750. return true;
  751. }
  752. var changed = false;
  753. if (cache[0] !== x) {
  754. cache[0] = x;
  755. changed = true;
  756. }
  757. if (cache[1] !== y) {
  758. cache[1] = y;
  759. changed = true;
  760. }
  761. return changed;
  762. };
  763. /** @ignore */
  764. Effect.prototype._cacheFloat3 = function (uniformName, x, y, z) {
  765. var cache = this._valueCache[uniformName];
  766. if (!cache) {
  767. cache = [x, y, z];
  768. this._valueCache[uniformName] = cache;
  769. return true;
  770. }
  771. var changed = false;
  772. if (cache[0] !== x) {
  773. cache[0] = x;
  774. changed = true;
  775. }
  776. if (cache[1] !== y) {
  777. cache[1] = y;
  778. changed = true;
  779. }
  780. if (cache[2] !== z) {
  781. cache[2] = z;
  782. changed = true;
  783. }
  784. return changed;
  785. };
  786. /** @ignore */
  787. Effect.prototype._cacheFloat4 = function (uniformName, x, y, z, w) {
  788. var cache = this._valueCache[uniformName];
  789. if (!cache) {
  790. cache = [x, y, z, w];
  791. this._valueCache[uniformName] = cache;
  792. return true;
  793. }
  794. var changed = false;
  795. if (cache[0] !== x) {
  796. cache[0] = x;
  797. changed = true;
  798. }
  799. if (cache[1] !== y) {
  800. cache[1] = y;
  801. changed = true;
  802. }
  803. if (cache[2] !== z) {
  804. cache[2] = z;
  805. changed = true;
  806. }
  807. if (cache[3] !== w) {
  808. cache[3] = w;
  809. changed = true;
  810. }
  811. return changed;
  812. };
  813. /**
  814. * Binds a buffer to a uniform.
  815. * @param buffer Buffer to bind.
  816. * @param name Name of the uniform variable to bind to.
  817. */
  818. Effect.prototype.bindUniformBuffer = function (buffer, name) {
  819. var bufferName = this._uniformBuffersNames[name];
  820. if (bufferName === undefined || Effect._baseCache[bufferName] === buffer) {
  821. return;
  822. }
  823. Effect._baseCache[bufferName] = buffer;
  824. this._engine.bindUniformBufferBase(buffer, bufferName);
  825. };
  826. /**
  827. * Binds block to a uniform.
  828. * @param blockName Name of the block to bind.
  829. * @param index Index to bind.
  830. */
  831. Effect.prototype.bindUniformBlock = function (blockName, index) {
  832. this._engine.bindUniformBlock(this._program, blockName, index);
  833. };
  834. /**
  835. * Sets an interger value on a uniform variable.
  836. * @param uniformName Name of the variable.
  837. * @param value Value to be set.
  838. * @returns this effect.
  839. */
  840. Effect.prototype.setInt = function (uniformName, value) {
  841. var cache = this._valueCache[uniformName];
  842. if (cache !== undefined && cache === value)
  843. return this;
  844. this._valueCache[uniformName] = value;
  845. this._engine.setInt(this.getUniform(uniformName), value);
  846. return this;
  847. };
  848. /**
  849. * Sets an int array on a uniform variable.
  850. * @param uniformName Name of the variable.
  851. * @param array array to be set.
  852. * @returns this effect.
  853. */
  854. Effect.prototype.setIntArray = function (uniformName, array) {
  855. this._valueCache[uniformName] = null;
  856. this._engine.setIntArray(this.getUniform(uniformName), array);
  857. return this;
  858. };
  859. /**
  860. * Sets an int array 2 on a uniform variable. (Array is specified as single array eg. [1,2,3,4] will result in [[1,2],[3,4]] in the shader)
  861. * @param uniformName Name of the variable.
  862. * @param array array to be set.
  863. * @returns this effect.
  864. */
  865. Effect.prototype.setIntArray2 = function (uniformName, array) {
  866. this._valueCache[uniformName] = null;
  867. this._engine.setIntArray2(this.getUniform(uniformName), array);
  868. return this;
  869. };
  870. /**
  871. * Sets an int array 3 on a uniform variable. (Array is specified as single array eg. [1,2,3,4,5,6] will result in [[1,2,3],[4,5,6]] in the shader)
  872. * @param uniformName Name of the variable.
  873. * @param array array to be set.
  874. * @returns this effect.
  875. */
  876. Effect.prototype.setIntArray3 = function (uniformName, array) {
  877. this._valueCache[uniformName] = null;
  878. this._engine.setIntArray3(this.getUniform(uniformName), array);
  879. return this;
  880. };
  881. /**
  882. * Sets an int array 4 on a uniform variable. (Array is specified as single array eg. [1,2,3,4,5,6,7,8] will result in [[1,2,3,4],[5,6,7,8]] in the shader)
  883. * @param uniformName Name of the variable.
  884. * @param array array to be set.
  885. * @returns this effect.
  886. */
  887. Effect.prototype.setIntArray4 = function (uniformName, array) {
  888. this._valueCache[uniformName] = null;
  889. this._engine.setIntArray4(this.getUniform(uniformName), array);
  890. return this;
  891. };
  892. /**
  893. * Sets an float array on a uniform variable.
  894. * @param uniformName Name of the variable.
  895. * @param array array to be set.
  896. * @returns this effect.
  897. */
  898. Effect.prototype.setFloatArray = function (uniformName, array) {
  899. this._valueCache[uniformName] = null;
  900. this._engine.setFloatArray(this.getUniform(uniformName), array);
  901. return this;
  902. };
  903. /**
  904. * Sets an float array 2 on a uniform variable. (Array is specified as single array eg. [1,2,3,4] will result in [[1,2],[3,4]] in the shader)
  905. * @param uniformName Name of the variable.
  906. * @param array array to be set.
  907. * @returns this effect.
  908. */
  909. Effect.prototype.setFloatArray2 = function (uniformName, array) {
  910. this._valueCache[uniformName] = null;
  911. this._engine.setFloatArray2(this.getUniform(uniformName), array);
  912. return this;
  913. };
  914. /**
  915. * Sets an float array 3 on a uniform variable. (Array is specified as single array eg. [1,2,3,4,5,6] will result in [[1,2,3],[4,5,6]] in the shader)
  916. * @param uniformName Name of the variable.
  917. * @param array array to be set.
  918. * @returns this effect.
  919. */
  920. Effect.prototype.setFloatArray3 = function (uniformName, array) {
  921. this._valueCache[uniformName] = null;
  922. this._engine.setFloatArray3(this.getUniform(uniformName), array);
  923. return this;
  924. };
  925. /**
  926. * Sets an float array 4 on a uniform variable. (Array is specified as single array eg. [1,2,3,4,5,6,7,8] will result in [[1,2,3,4],[5,6,7,8]] in the shader)
  927. * @param uniformName Name of the variable.
  928. * @param array array to be set.
  929. * @returns this effect.
  930. */
  931. Effect.prototype.setFloatArray4 = function (uniformName, array) {
  932. this._valueCache[uniformName] = null;
  933. this._engine.setFloatArray4(this.getUniform(uniformName), array);
  934. return this;
  935. };
  936. /**
  937. * Sets an array on a uniform variable.
  938. * @param uniformName Name of the variable.
  939. * @param array array to be set.
  940. * @returns this effect.
  941. */
  942. Effect.prototype.setArray = function (uniformName, array) {
  943. this._valueCache[uniformName] = null;
  944. this._engine.setArray(this.getUniform(uniformName), array);
  945. return this;
  946. };
  947. /**
  948. * Sets an array 2 on a uniform variable. (Array is specified as single array eg. [1,2,3,4] will result in [[1,2],[3,4]] in the shader)
  949. * @param uniformName Name of the variable.
  950. * @param array array to be set.
  951. * @returns this effect.
  952. */
  953. Effect.prototype.setArray2 = function (uniformName, array) {
  954. this._valueCache[uniformName] = null;
  955. this._engine.setArray2(this.getUniform(uniformName), array);
  956. return this;
  957. };
  958. /**
  959. * Sets an array 3 on a uniform variable. (Array is specified as single array eg. [1,2,3,4,5,6] will result in [[1,2,3],[4,5,6]] in the shader)
  960. * @param uniformName Name of the variable.
  961. * @param array array to be set.
  962. * @returns this effect.
  963. */
  964. Effect.prototype.setArray3 = function (uniformName, array) {
  965. this._valueCache[uniformName] = null;
  966. this._engine.setArray3(this.getUniform(uniformName), array);
  967. return this;
  968. };
  969. /**
  970. * Sets an array 4 on a uniform variable. (Array is specified as single array eg. [1,2,3,4,5,6,7,8] will result in [[1,2,3,4],[5,6,7,8]] in the shader)
  971. * @param uniformName Name of the variable.
  972. * @param array array to be set.
  973. * @returns this effect.
  974. */
  975. Effect.prototype.setArray4 = function (uniformName, array) {
  976. this._valueCache[uniformName] = null;
  977. this._engine.setArray4(this.getUniform(uniformName), array);
  978. return this;
  979. };
  980. /**
  981. * Sets matrices on a uniform variable.
  982. * @param uniformName Name of the variable.
  983. * @param matrices matrices to be set.
  984. * @returns this effect.
  985. */
  986. Effect.prototype.setMatrices = function (uniformName, matrices) {
  987. if (!matrices) {
  988. return this;
  989. }
  990. this._valueCache[uniformName] = null;
  991. this._engine.setMatrices(this.getUniform(uniformName), matrices);
  992. return this;
  993. };
  994. /**
  995. * Sets matrix on a uniform variable.
  996. * @param uniformName Name of the variable.
  997. * @param matrix matrix to be set.
  998. * @returns this effect.
  999. */
  1000. Effect.prototype.setMatrix = function (uniformName, matrix) {
  1001. if (this._cacheMatrix(uniformName, matrix)) {
  1002. this._engine.setMatrix(this.getUniform(uniformName), matrix);
  1003. }
  1004. return this;
  1005. };
  1006. /**
  1007. * Sets a 3x3 matrix on a uniform variable. (Speicified as [1,2,3,4,5,6,7,8,9] will result in [1,2,3][4,5,6][7,8,9] matrix)
  1008. * @param uniformName Name of the variable.
  1009. * @param matrix matrix to be set.
  1010. * @returns this effect.
  1011. */
  1012. Effect.prototype.setMatrix3x3 = function (uniformName, matrix) {
  1013. this._valueCache[uniformName] = null;
  1014. this._engine.setMatrix3x3(this.getUniform(uniformName), matrix);
  1015. return this;
  1016. };
  1017. /**
  1018. * Sets a 2x2 matrix on a uniform variable. (Speicified as [1,2,3,4] will result in [1,2][3,4] matrix)
  1019. * @param uniformName Name of the variable.
  1020. * @param matrix matrix to be set.
  1021. * @returns this effect.
  1022. */
  1023. Effect.prototype.setMatrix2x2 = function (uniformName, matrix) {
  1024. this._valueCache[uniformName] = null;
  1025. this._engine.setMatrix2x2(this.getUniform(uniformName), matrix);
  1026. return this;
  1027. };
  1028. /**
  1029. * Sets a float on a uniform variable.
  1030. * @param uniformName Name of the variable.
  1031. * @param value value to be set.
  1032. * @returns this effect.
  1033. */
  1034. Effect.prototype.setFloat = function (uniformName, value) {
  1035. var cache = this._valueCache[uniformName];
  1036. if (cache !== undefined && cache === value)
  1037. return this;
  1038. this._valueCache[uniformName] = value;
  1039. this._engine.setFloat(this.getUniform(uniformName), value);
  1040. return this;
  1041. };
  1042. /**
  1043. * Sets a boolean on a uniform variable.
  1044. * @param uniformName Name of the variable.
  1045. * @param bool value to be set.
  1046. * @returns this effect.
  1047. */
  1048. Effect.prototype.setBool = function (uniformName, bool) {
  1049. var cache = this._valueCache[uniformName];
  1050. if (cache !== undefined && cache === bool)
  1051. return this;
  1052. this._valueCache[uniformName] = bool;
  1053. this._engine.setBool(this.getUniform(uniformName), bool ? 1 : 0);
  1054. return this;
  1055. };
  1056. /**
  1057. * Sets a Vector2 on a uniform variable.
  1058. * @param uniformName Name of the variable.
  1059. * @param vector2 vector2 to be set.
  1060. * @returns this effect.
  1061. */
  1062. Effect.prototype.setVector2 = function (uniformName, vector2) {
  1063. if (this._cacheFloat2(uniformName, vector2.x, vector2.y)) {
  1064. this._engine.setFloat2(this.getUniform(uniformName), vector2.x, vector2.y);
  1065. }
  1066. return this;
  1067. };
  1068. /**
  1069. * Sets a float2 on a uniform variable.
  1070. * @param uniformName Name of the variable.
  1071. * @param x First float in float2.
  1072. * @param y Second float in float2.
  1073. * @returns this effect.
  1074. */
  1075. Effect.prototype.setFloat2 = function (uniformName, x, y) {
  1076. if (this._cacheFloat2(uniformName, x, y)) {
  1077. this._engine.setFloat2(this.getUniform(uniformName), x, y);
  1078. }
  1079. return this;
  1080. };
  1081. /**
  1082. * Sets a Vector3 on a uniform variable.
  1083. * @param uniformName Name of the variable.
  1084. * @param vector3 Value to be set.
  1085. * @returns this effect.
  1086. */
  1087. Effect.prototype.setVector3 = function (uniformName, vector3) {
  1088. if (this._cacheFloat3(uniformName, vector3.x, vector3.y, vector3.z)) {
  1089. this._engine.setFloat3(this.getUniform(uniformName), vector3.x, vector3.y, vector3.z);
  1090. }
  1091. return this;
  1092. };
  1093. /**
  1094. * Sets a float3 on a uniform variable.
  1095. * @param uniformName Name of the variable.
  1096. * @param x First float in float3.
  1097. * @param y Second float in float3.
  1098. * @param z Third float in float3.
  1099. * @returns this effect.
  1100. */
  1101. Effect.prototype.setFloat3 = function (uniformName, x, y, z) {
  1102. if (this._cacheFloat3(uniformName, x, y, z)) {
  1103. this._engine.setFloat3(this.getUniform(uniformName), x, y, z);
  1104. }
  1105. return this;
  1106. };
  1107. /**
  1108. * Sets a Vector4 on a uniform variable.
  1109. * @param uniformName Name of the variable.
  1110. * @param vector4 Value to be set.
  1111. * @returns this effect.
  1112. */
  1113. Effect.prototype.setVector4 = function (uniformName, vector4) {
  1114. if (this._cacheFloat4(uniformName, vector4.x, vector4.y, vector4.z, vector4.w)) {
  1115. this._engine.setFloat4(this.getUniform(uniformName), vector4.x, vector4.y, vector4.z, vector4.w);
  1116. }
  1117. return this;
  1118. };
  1119. /**
  1120. * Sets a float4 on a uniform variable.
  1121. * @param uniformName Name of the variable.
  1122. * @param x First float in float4.
  1123. * @param y Second float in float4.
  1124. * @param z Third float in float4.
  1125. * @param w Fourth float in float4.
  1126. * @returns this effect.
  1127. */
  1128. Effect.prototype.setFloat4 = function (uniformName, x, y, z, w) {
  1129. if (this._cacheFloat4(uniformName, x, y, z, w)) {
  1130. this._engine.setFloat4(this.getUniform(uniformName), x, y, z, w);
  1131. }
  1132. return this;
  1133. };
  1134. /**
  1135. * Sets a Color3 on a uniform variable.
  1136. * @param uniformName Name of the variable.
  1137. * @param color3 Value to be set.
  1138. * @returns this effect.
  1139. */
  1140. Effect.prototype.setColor3 = function (uniformName, color3) {
  1141. if (this._cacheFloat3(uniformName, color3.r, color3.g, color3.b)) {
  1142. this._engine.setColor3(this.getUniform(uniformName), color3);
  1143. }
  1144. return this;
  1145. };
  1146. /**
  1147. * Sets a Color4 on a uniform variable.
  1148. * @param uniformName Name of the variable.
  1149. * @param color3 Value to be set.
  1150. * @param alpha Alpha value to be set.
  1151. * @returns this effect.
  1152. */
  1153. Effect.prototype.setColor4 = function (uniformName, color3, alpha) {
  1154. if (this._cacheFloat4(uniformName, color3.r, color3.g, color3.b, alpha)) {
  1155. this._engine.setColor4(this.getUniform(uniformName), color3, alpha);
  1156. }
  1157. return this;
  1158. };
  1159. /**
  1160. * Sets a Color4 on a uniform variable
  1161. * @param uniformName defines the name of the variable
  1162. * @param color4 defines the value to be set
  1163. * @returns this effect.
  1164. */
  1165. Effect.prototype.setDirectColor4 = function (uniformName, color4) {
  1166. if (this._cacheFloat4(uniformName, color4.r, color4.g, color4.b, color4.a)) {
  1167. this._engine.setDirectColor4(this.getUniform(uniformName), color4);
  1168. }
  1169. return this;
  1170. };
  1171. /**
  1172. * Resets the cache of effects.
  1173. */
  1174. Effect.ResetCache = function () {
  1175. Effect._baseCache = {};
  1176. };
  1177. Effect._uniqueIdSeed = 0;
  1178. Effect._baseCache = {};
  1179. // Statics
  1180. /**
  1181. * Store of each shader (The can be looked up using effect.key)
  1182. */
  1183. Effect.ShadersStore = {};
  1184. /**
  1185. * Store of each included file for a shader (The can be looked up using effect.key)
  1186. */
  1187. Effect.IncludesShadersStore = {};
  1188. return Effect;
  1189. }());
  1190. BABYLON.Effect = Effect;
  1191. })(BABYLON || (BABYLON = {}));
  1192. //# sourceMappingURL=babylon.effect.js.map
  1193. //# sourceMappingURL=babylon.types.js.map
  1194. var BABYLON;
  1195. (function (BABYLON) {
  1196. var KeyboardEventTypes = /** @class */ (function () {
  1197. function KeyboardEventTypes() {
  1198. }
  1199. Object.defineProperty(KeyboardEventTypes, "KEYDOWN", {
  1200. get: function () {
  1201. return KeyboardEventTypes._KEYDOWN;
  1202. },
  1203. enumerable: true,
  1204. configurable: true
  1205. });
  1206. Object.defineProperty(KeyboardEventTypes, "KEYUP", {
  1207. get: function () {
  1208. return KeyboardEventTypes._KEYUP;
  1209. },
  1210. enumerable: true,
  1211. configurable: true
  1212. });
  1213. KeyboardEventTypes._KEYDOWN = 0x01;
  1214. KeyboardEventTypes._KEYUP = 0x02;
  1215. return KeyboardEventTypes;
  1216. }());
  1217. BABYLON.KeyboardEventTypes = KeyboardEventTypes;
  1218. var KeyboardInfo = /** @class */ (function () {
  1219. function KeyboardInfo(type, event) {
  1220. this.type = type;
  1221. this.event = event;
  1222. }
  1223. return KeyboardInfo;
  1224. }());
  1225. BABYLON.KeyboardInfo = KeyboardInfo;
  1226. /**
  1227. * This class is used to store keyboard related info for the onPreKeyboardObservable event.
  1228. * Set the skipOnKeyboardObservable property to true if you want the engine to stop any process after this event is triggered, even not calling onKeyboardObservable
  1229. */
  1230. var KeyboardInfoPre = /** @class */ (function (_super) {
  1231. __extends(KeyboardInfoPre, _super);
  1232. function KeyboardInfoPre(type, event) {
  1233. var _this = _super.call(this, type, event) || this;
  1234. _this.skipOnPointerObservable = false;
  1235. return _this;
  1236. }
  1237. return KeyboardInfoPre;
  1238. }(KeyboardInfo));
  1239. BABYLON.KeyboardInfoPre = KeyboardInfoPre;
  1240. })(BABYLON || (BABYLON = {}));
  1241. //# sourceMappingURL=babylon.keyboardEvents.js.map
  1242. var BABYLON;
  1243. (function (BABYLON) {
  1244. var PointerEventTypes = /** @class */ (function () {
  1245. function PointerEventTypes() {
  1246. }
  1247. Object.defineProperty(PointerEventTypes, "POINTERDOWN", {
  1248. get: function () {
  1249. return PointerEventTypes._POINTERDOWN;
  1250. },
  1251. enumerable: true,
  1252. configurable: true
  1253. });
  1254. Object.defineProperty(PointerEventTypes, "POINTERUP", {
  1255. get: function () {
  1256. return PointerEventTypes._POINTERUP;
  1257. },
  1258. enumerable: true,
  1259. configurable: true
  1260. });
  1261. Object.defineProperty(PointerEventTypes, "POINTERMOVE", {
  1262. get: function () {
  1263. return PointerEventTypes._POINTERMOVE;
  1264. },
  1265. enumerable: true,
  1266. configurable: true
  1267. });
  1268. Object.defineProperty(PointerEventTypes, "POINTERWHEEL", {
  1269. get: function () {
  1270. return PointerEventTypes._POINTERWHEEL;
  1271. },
  1272. enumerable: true,
  1273. configurable: true
  1274. });
  1275. Object.defineProperty(PointerEventTypes, "POINTERPICK", {
  1276. get: function () {
  1277. return PointerEventTypes._POINTERPICK;
  1278. },
  1279. enumerable: true,
  1280. configurable: true
  1281. });
  1282. Object.defineProperty(PointerEventTypes, "POINTERTAP", {
  1283. get: function () {
  1284. return PointerEventTypes._POINTERTAP;
  1285. },
  1286. enumerable: true,
  1287. configurable: true
  1288. });
  1289. Object.defineProperty(PointerEventTypes, "POINTERDOUBLETAP", {
  1290. get: function () {
  1291. return PointerEventTypes._POINTERDOUBLETAP;
  1292. },
  1293. enumerable: true,
  1294. configurable: true
  1295. });
  1296. PointerEventTypes._POINTERDOWN = 0x01;
  1297. PointerEventTypes._POINTERUP = 0x02;
  1298. PointerEventTypes._POINTERMOVE = 0x04;
  1299. PointerEventTypes._POINTERWHEEL = 0x08;
  1300. PointerEventTypes._POINTERPICK = 0x10;
  1301. PointerEventTypes._POINTERTAP = 0x20;
  1302. PointerEventTypes._POINTERDOUBLETAP = 0x40;
  1303. return PointerEventTypes;
  1304. }());
  1305. BABYLON.PointerEventTypes = PointerEventTypes;
  1306. var PointerInfoBase = /** @class */ (function () {
  1307. function PointerInfoBase(type, event) {
  1308. this.type = type;
  1309. this.event = event;
  1310. }
  1311. return PointerInfoBase;
  1312. }());
  1313. BABYLON.PointerInfoBase = PointerInfoBase;
  1314. /**
  1315. * This class is used to store pointer related info for the onPrePointerObservable event.
  1316. * Set the skipOnPointerObservable property to true if you want the engine to stop any process after this event is triggered, even not calling onPointerObservable
  1317. */
  1318. var PointerInfoPre = /** @class */ (function (_super) {
  1319. __extends(PointerInfoPre, _super);
  1320. function PointerInfoPre(type, event, localX, localY) {
  1321. var _this = _super.call(this, type, event) || this;
  1322. _this.skipOnPointerObservable = false;
  1323. _this.localPosition = new BABYLON.Vector2(localX, localY);
  1324. return _this;
  1325. }
  1326. return PointerInfoPre;
  1327. }(PointerInfoBase));
  1328. BABYLON.PointerInfoPre = PointerInfoPre;
  1329. /**
  1330. * This type contains all the data related to a pointer event in Babylon.js.
  1331. * The event member is an instance of PointerEvent for all types except PointerWheel and is of type MouseWheelEvent when type equals PointerWheel. The different event types can be found in the PointerEventTypes class.
  1332. */
  1333. var PointerInfo = /** @class */ (function (_super) {
  1334. __extends(PointerInfo, _super);
  1335. function PointerInfo(type, event, pickInfo) {
  1336. var _this = _super.call(this, type, event) || this;
  1337. _this.pickInfo = pickInfo;
  1338. return _this;
  1339. }
  1340. return PointerInfo;
  1341. }(PointerInfoBase));
  1342. BABYLON.PointerInfo = PointerInfo;
  1343. })(BABYLON || (BABYLON = {}));
  1344. //# sourceMappingURL=babylon.pointerEvents.js.map
  1345. var BABYLON;
  1346. (function (BABYLON) {
  1347. BABYLON.ToGammaSpace = 1 / 2.2;
  1348. BABYLON.ToLinearSpace = 2.2;
  1349. BABYLON.Epsilon = 0.001;
  1350. /**
  1351. * Class used to hold a RBG color
  1352. */
  1353. var Color3 = /** @class */ (function () {
  1354. /**
  1355. * Creates a new Color3 object from red, green, blue values, all between 0 and 1
  1356. * @param r defines the red component (between 0 and 1, default is 0)
  1357. * @param g defines the green component (between 0 and 1, default is 0)
  1358. * @param b defines the blue component (between 0 and 1, default is 0)
  1359. */
  1360. function Color3(
  1361. /**
  1362. * Defines the red component (between 0 and 1, default is 0)
  1363. */
  1364. r,
  1365. /**
  1366. * Defines the green component (between 0 and 1, default is 0)
  1367. */
  1368. g,
  1369. /**
  1370. * Defines the blue component (between 0 and 1, default is 0)
  1371. */
  1372. b) {
  1373. if (r === void 0) { r = 0; }
  1374. if (g === void 0) { g = 0; }
  1375. if (b === void 0) { b = 0; }
  1376. this.r = r;
  1377. this.g = g;
  1378. this.b = b;
  1379. }
  1380. /**
  1381. * Creates a string with the Color3 current values
  1382. * @returns the string representation of the Color3 object
  1383. */
  1384. Color3.prototype.toString = function () {
  1385. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + "}";
  1386. };
  1387. /**
  1388. * Returns the string "Color3"
  1389. * @returns "Color3"
  1390. */
  1391. Color3.prototype.getClassName = function () {
  1392. return "Color3";
  1393. };
  1394. /**
  1395. * Compute the Color3 hash code
  1396. * @returns an unique number that can be used to hash Color3 objects
  1397. */
  1398. Color3.prototype.getHashCode = function () {
  1399. var hash = this.r || 0;
  1400. hash = (hash * 397) ^ (this.g || 0);
  1401. hash = (hash * 397) ^ (this.b || 0);
  1402. return hash;
  1403. };
  1404. // Operators
  1405. /**
  1406. * Stores in the passed array from the passed starting index the red, green, blue values as successive elements
  1407. * @param array defines the array where to store the r,g,b components
  1408. * @param index defines an optional index in the target array to define where to start storing values
  1409. * @returns the current Color3 object
  1410. */
  1411. Color3.prototype.toArray = function (array, index) {
  1412. if (index === undefined) {
  1413. index = 0;
  1414. }
  1415. array[index] = this.r;
  1416. array[index + 1] = this.g;
  1417. array[index + 2] = this.b;
  1418. return this;
  1419. };
  1420. /**
  1421. * Returns a new {BABYLON.Color4} object from the current Color3 and the passed alpha
  1422. * @param alpha defines the alpha component on the new {BABYLON.Color4} object (default is 1)
  1423. * @returns a new {BABYLON.Color4} object
  1424. */
  1425. Color3.prototype.toColor4 = function (alpha) {
  1426. if (alpha === void 0) { alpha = 1; }
  1427. return new Color4(this.r, this.g, this.b, alpha);
  1428. };
  1429. /**
  1430. * Returns a new array populated with 3 numeric elements : red, green and blue values
  1431. * @returns the new array
  1432. */
  1433. Color3.prototype.asArray = function () {
  1434. var result = new Array();
  1435. this.toArray(result, 0);
  1436. return result;
  1437. };
  1438. /**
  1439. * Returns the luminance value
  1440. * @returns a float value
  1441. */
  1442. Color3.prototype.toLuminance = function () {
  1443. return this.r * 0.3 + this.g * 0.59 + this.b * 0.11;
  1444. };
  1445. /**
  1446. * Multiply each Color3 rgb values by the passed Color3 rgb values in a new Color3 object
  1447. * @param otherColor defines the second operand
  1448. * @returns the new Color3 object
  1449. */
  1450. Color3.prototype.multiply = function (otherColor) {
  1451. return new Color3(this.r * otherColor.r, this.g * otherColor.g, this.b * otherColor.b);
  1452. };
  1453. /**
  1454. * Multiply the rgb values of the Color3 and the passed Color3 and stores the result in the object "result"
  1455. * @param otherColor defines the second operand
  1456. * @param result defines the Color3 object where to store the result
  1457. * @returns the current Color3
  1458. */
  1459. Color3.prototype.multiplyToRef = function (otherColor, result) {
  1460. result.r = this.r * otherColor.r;
  1461. result.g = this.g * otherColor.g;
  1462. result.b = this.b * otherColor.b;
  1463. return this;
  1464. };
  1465. /**
  1466. * Determines equality between Color3 objects
  1467. * @param otherColor defines the second operand
  1468. * @returns true if the rgb values are equal to the passed ones
  1469. */
  1470. Color3.prototype.equals = function (otherColor) {
  1471. return otherColor && this.r === otherColor.r && this.g === otherColor.g && this.b === otherColor.b;
  1472. };
  1473. /**
  1474. * Determines equality between the current Color3 object and a set of r,b,g values
  1475. * @param r defines the red component to check
  1476. * @param g defines the green component to check
  1477. * @param b defines the blue component to check
  1478. * @returns true if the rgb values are equal to the passed ones
  1479. */
  1480. Color3.prototype.equalsFloats = function (r, g, b) {
  1481. return this.r === r && this.g === g && this.b === b;
  1482. };
  1483. /**
  1484. * Multiplies in place each rgb value by scale
  1485. * @param scale defines the scaling factor
  1486. * @returns the updated Color3.
  1487. */
  1488. Color3.prototype.scale = function (scale) {
  1489. return new Color3(this.r * scale, this.g * scale, this.b * scale);
  1490. };
  1491. /**
  1492. * Multiplies the rgb values by scale and stores the result into "result"
  1493. * @param scale defines the scaling factor
  1494. * @param result defines the Color3 object where to store the result
  1495. * @returns the unmodified current Color3.
  1496. */
  1497. Color3.prototype.scaleToRef = function (scale, result) {
  1498. result.r = this.r * scale;
  1499. result.g = this.g * scale;
  1500. result.b = this.b * scale;
  1501. return this;
  1502. };
  1503. /**
  1504. * Clamps the rgb values by the min and max values and stores the result into "result"
  1505. * @param min defines minimum clamping value (default is 0)
  1506. * @param max defines maximum clamping value (default is 1)
  1507. * @param result defines color to store the result into
  1508. * @returns the original Color3
  1509. */
  1510. Color3.prototype.clampToRef = function (min, max, result) {
  1511. if (min === void 0) { min = 0; }
  1512. if (max === void 0) { max = 1; }
  1513. result.r = BABYLON.Scalar.Clamp(this.r, min, max);
  1514. result.g = BABYLON.Scalar.Clamp(this.g, min, max);
  1515. result.b = BABYLON.Scalar.Clamp(this.b, min, max);
  1516. return this;
  1517. };
  1518. /**
  1519. * Creates a new Color3 set with the added values of the current Color3 and of the passed one
  1520. * @param otherColor defines the second operand
  1521. * @returns the new Color3
  1522. */
  1523. Color3.prototype.add = function (otherColor) {
  1524. return new Color3(this.r + otherColor.r, this.g + otherColor.g, this.b + otherColor.b);
  1525. };
  1526. /**
  1527. * Stores the result of the addition of the current Color3 and passed one rgb values into "result"
  1528. * @param otherColor defines the second operand
  1529. * @param result defines Color3 object to store the result into
  1530. * @returns the unmodified current Color3
  1531. */
  1532. Color3.prototype.addToRef = function (otherColor, result) {
  1533. result.r = this.r + otherColor.r;
  1534. result.g = this.g + otherColor.g;
  1535. result.b = this.b + otherColor.b;
  1536. return this;
  1537. };
  1538. /**
  1539. * Returns a new Color3 set with the subtracted values of the passed one from the current Color3
  1540. * @param otherColor defines the second operand
  1541. * @returns the new Color3
  1542. */
  1543. Color3.prototype.subtract = function (otherColor) {
  1544. return new Color3(this.r - otherColor.r, this.g - otherColor.g, this.b - otherColor.b);
  1545. };
  1546. /**
  1547. * Stores the result of the subtraction of passed one from the current Color3 rgb values into "result"
  1548. * @param otherColor defines the second operand
  1549. * @param result defines Color3 object to store the result into
  1550. * @returns the unmodified current Color3
  1551. */
  1552. Color3.prototype.subtractToRef = function (otherColor, result) {
  1553. result.r = this.r - otherColor.r;
  1554. result.g = this.g - otherColor.g;
  1555. result.b = this.b - otherColor.b;
  1556. return this;
  1557. };
  1558. /**
  1559. * Copy the current object
  1560. * @returns a new Color3 copied the current one
  1561. */
  1562. Color3.prototype.clone = function () {
  1563. return new Color3(this.r, this.g, this.b);
  1564. };
  1565. /**
  1566. * Copies the rgb values from the source in the current Color3
  1567. * @param source defines the source Color3 object
  1568. * @returns the updated Color3 object
  1569. */
  1570. Color3.prototype.copyFrom = function (source) {
  1571. this.r = source.r;
  1572. this.g = source.g;
  1573. this.b = source.b;
  1574. return this;
  1575. };
  1576. /**
  1577. * Updates the Color3 rgb values from the passed floats
  1578. * @param r defines the red component to read from
  1579. * @param g defines the green component to read from
  1580. * @param b defines the blue component to read from
  1581. * @returns the current Color3 object
  1582. */
  1583. Color3.prototype.copyFromFloats = function (r, g, b) {
  1584. this.r = r;
  1585. this.g = g;
  1586. this.b = b;
  1587. return this;
  1588. };
  1589. /**
  1590. * Updates the Color3 rgb values from the passed floats
  1591. * @param r defines the red component to read from
  1592. * @param g defines the green component to read from
  1593. * @param b defines the blue component to read from
  1594. * @returns the current Color3 object
  1595. */
  1596. Color3.prototype.set = function (r, g, b) {
  1597. return this.copyFromFloats(r, g, b);
  1598. };
  1599. /**
  1600. * Compute the Color3 hexadecimal code as a string
  1601. * @returns a string containing the hexadecimal representation of the Color3 object
  1602. */
  1603. Color3.prototype.toHexString = function () {
  1604. var intR = (this.r * 255) | 0;
  1605. var intG = (this.g * 255) | 0;
  1606. var intB = (this.b * 255) | 0;
  1607. return "#" + BABYLON.Scalar.ToHex(intR) + BABYLON.Scalar.ToHex(intG) + BABYLON.Scalar.ToHex(intB);
  1608. };
  1609. /**
  1610. * Computes a new Color3 converted from the current one to linear space
  1611. * @returns a new Color3 object
  1612. */
  1613. Color3.prototype.toLinearSpace = function () {
  1614. var convertedColor = new Color3();
  1615. this.toLinearSpaceToRef(convertedColor);
  1616. return convertedColor;
  1617. };
  1618. /**
  1619. * Converts the Color3 values to linear space and stores the result in "convertedColor"
  1620. * @param convertedColor defines the Color3 object where to store the linear space version
  1621. * @returns the unmodified Color3
  1622. */
  1623. Color3.prototype.toLinearSpaceToRef = function (convertedColor) {
  1624. convertedColor.r = Math.pow(this.r, BABYLON.ToLinearSpace);
  1625. convertedColor.g = Math.pow(this.g, BABYLON.ToLinearSpace);
  1626. convertedColor.b = Math.pow(this.b, BABYLON.ToLinearSpace);
  1627. return this;
  1628. };
  1629. /**
  1630. * Computes a new Color3 converted from the current one to gamma space
  1631. * @returns a new Color3 object
  1632. */
  1633. Color3.prototype.toGammaSpace = function () {
  1634. var convertedColor = new Color3();
  1635. this.toGammaSpaceToRef(convertedColor);
  1636. return convertedColor;
  1637. };
  1638. /**
  1639. * Converts the Color3 values to gamma space and stores the result in "convertedColor"
  1640. * @param convertedColor defines the Color3 object where to store the gamma space version
  1641. * @returns the unmodified Color3
  1642. */
  1643. Color3.prototype.toGammaSpaceToRef = function (convertedColor) {
  1644. convertedColor.r = Math.pow(this.r, BABYLON.ToGammaSpace);
  1645. convertedColor.g = Math.pow(this.g, BABYLON.ToGammaSpace);
  1646. convertedColor.b = Math.pow(this.b, BABYLON.ToGammaSpace);
  1647. return this;
  1648. };
  1649. // Statics
  1650. /**
  1651. * Creates a new Color3 from the string containing valid hexadecimal values
  1652. * @param hex defines a string containing valid hexadecimal values
  1653. * @returns a new Color3 object
  1654. */
  1655. Color3.FromHexString = function (hex) {
  1656. if (hex.substring(0, 1) !== "#" || hex.length !== 7) {
  1657. //Tools.Warn("Color3.FromHexString must be called with a string like #FFFFFF");
  1658. return new Color3(0, 0, 0);
  1659. }
  1660. var r = parseInt(hex.substring(1, 3), 16);
  1661. var g = parseInt(hex.substring(3, 5), 16);
  1662. var b = parseInt(hex.substring(5, 7), 16);
  1663. return Color3.FromInts(r, g, b);
  1664. };
  1665. /**
  1666. * Creates a new Vector3 from the starting index of the passed array
  1667. * @param array defines the source array
  1668. * @param offset defines an offset in the source array
  1669. * @returns a new Color3 object
  1670. */
  1671. Color3.FromArray = function (array, offset) {
  1672. if (offset === void 0) { offset = 0; }
  1673. return new Color3(array[offset], array[offset + 1], array[offset + 2]);
  1674. };
  1675. /**
  1676. * Creates a new Color3 from integer values (< 256)
  1677. * @param r defines the red component to read from (value between 0 and 255)
  1678. * @param g defines the green component to read from (value between 0 and 255)
  1679. * @param b defines the blue component to read from (value between 0 and 255)
  1680. * @returns a new Color3 object
  1681. */
  1682. Color3.FromInts = function (r, g, b) {
  1683. return new Color3(r / 255.0, g / 255.0, b / 255.0);
  1684. };
  1685. /**
  1686. * Creates a new Color3 with values linearly interpolated of "amount" between the start Color3 and the end Color3
  1687. * @param start defines the start Color3 value
  1688. * @param end defines the end Color3 value
  1689. * @param amount defines the gradient value between start and end
  1690. * @returns a new Color3 object
  1691. */
  1692. Color3.Lerp = function (start, end, amount) {
  1693. var r = start.r + ((end.r - start.r) * amount);
  1694. var g = start.g + ((end.g - start.g) * amount);
  1695. var b = start.b + ((end.b - start.b) * amount);
  1696. return new Color3(r, g, b);
  1697. };
  1698. /**
  1699. * Returns a Color3 value containing a red color
  1700. * @returns a new Color3 object
  1701. */
  1702. Color3.Red = function () { return new Color3(1, 0, 0); };
  1703. /**
  1704. * Returns a Color3 value containing a green color
  1705. * @returns a new Color3 object
  1706. */
  1707. Color3.Green = function () { return new Color3(0, 1, 0); };
  1708. /**
  1709. * Returns a Color3 value containing a blue color
  1710. * @returns a new Color3 object
  1711. */
  1712. Color3.Blue = function () { return new Color3(0, 0, 1); };
  1713. /**
  1714. * Returns a Color3 value containing a black color
  1715. * @returns a new Color3 object
  1716. */
  1717. Color3.Black = function () { return new Color3(0, 0, 0); };
  1718. /**
  1719. * Returns a Color3 value containing a white color
  1720. * @returns a new Color3 object
  1721. */
  1722. Color3.White = function () { return new Color3(1, 1, 1); };
  1723. /**
  1724. * Returns a Color3 value containing a purple color
  1725. * @returns a new Color3 object
  1726. */
  1727. Color3.Purple = function () { return new Color3(0.5, 0, 0.5); };
  1728. /**
  1729. * Returns a Color3 value containing a magenta color
  1730. * @returns a new Color3 object
  1731. */
  1732. Color3.Magenta = function () { return new Color3(1, 0, 1); };
  1733. /**
  1734. * Returns a Color3 value containing a yellow color
  1735. * @returns a new Color3 object
  1736. */
  1737. Color3.Yellow = function () { return new Color3(1, 1, 0); };
  1738. /**
  1739. * Returns a Color3 value containing a gray color
  1740. * @returns a new Color3 object
  1741. */
  1742. Color3.Gray = function () { return new Color3(0.5, 0.5, 0.5); };
  1743. /**
  1744. * Returns a Color3 value containing a teal color
  1745. * @returns a new Color3 object
  1746. */
  1747. Color3.Teal = function () { return new Color3(0, 1.0, 1.0); };
  1748. /**
  1749. * Returns a Color3 value containing a random color
  1750. * @returns a new Color3 object
  1751. */
  1752. Color3.Random = function () { return new Color3(Math.random(), Math.random(), Math.random()); };
  1753. return Color3;
  1754. }());
  1755. BABYLON.Color3 = Color3;
  1756. /**
  1757. * Class used to hold a RBGA color
  1758. */
  1759. var Color4 = /** @class */ (function () {
  1760. /**
  1761. * Creates a new Color4 object from red, green, blue values, all between 0 and 1
  1762. * @param r defines the red component (between 0 and 1, default is 0)
  1763. * @param g defines the green component (between 0 and 1, default is 0)
  1764. * @param b defines the blue component (between 0 and 1, default is 0)
  1765. * @param a defines the alpha component (between 0 and 1, default is 1)
  1766. */
  1767. function Color4(
  1768. /**
  1769. * Defines the red component (between 0 and 1, default is 0)
  1770. */
  1771. r,
  1772. /**
  1773. * Defines the green component (between 0 and 1, default is 0)
  1774. */
  1775. g,
  1776. /**
  1777. * Defines the blue component (between 0 and 1, default is 0)
  1778. */
  1779. b,
  1780. /**
  1781. * Defines the alpha component (between 0 and 1, default is 1)
  1782. */
  1783. a) {
  1784. if (r === void 0) { r = 0; }
  1785. if (g === void 0) { g = 0; }
  1786. if (b === void 0) { b = 0; }
  1787. if (a === void 0) { a = 1; }
  1788. this.r = r;
  1789. this.g = g;
  1790. this.b = b;
  1791. this.a = a;
  1792. }
  1793. // Operators
  1794. /**
  1795. * Adds in place the passed Color4 values to the current Color4 object
  1796. * @param right defines the second operand
  1797. * @returns the current updated Color4 object
  1798. */
  1799. Color4.prototype.addInPlace = function (right) {
  1800. this.r += right.r;
  1801. this.g += right.g;
  1802. this.b += right.b;
  1803. this.a += right.a;
  1804. return this;
  1805. };
  1806. /**
  1807. * Creates a new array populated with 4 numeric elements : red, green, blue, alpha values
  1808. * @returns the new array
  1809. */
  1810. Color4.prototype.asArray = function () {
  1811. var result = new Array();
  1812. this.toArray(result, 0);
  1813. return result;
  1814. };
  1815. /**
  1816. * Stores from the starting index in the passed array the Color4 successive values
  1817. * @param array defines the array where to store the r,g,b components
  1818. * @param index defines an optional index in the target array to define where to start storing values
  1819. * @returns the current Color4 object
  1820. */
  1821. Color4.prototype.toArray = function (array, index) {
  1822. if (index === undefined) {
  1823. index = 0;
  1824. }
  1825. array[index] = this.r;
  1826. array[index + 1] = this.g;
  1827. array[index + 2] = this.b;
  1828. array[index + 3] = this.a;
  1829. return this;
  1830. };
  1831. /**
  1832. * Creates a new Color4 set with the added values of the current Color4 and of the passed one
  1833. * @param right defines the second operand
  1834. * @returns a new Color4 object
  1835. */
  1836. Color4.prototype.add = function (right) {
  1837. return new Color4(this.r + right.r, this.g + right.g, this.b + right.b, this.a + right.a);
  1838. };
  1839. /**
  1840. * Creates a new Color4 set with the subtracted values of the passed one from the current Color4
  1841. * @param right defines the second operand
  1842. * @returns a new Color4 object
  1843. */
  1844. Color4.prototype.subtract = function (right) {
  1845. return new Color4(this.r - right.r, this.g - right.g, this.b - right.b, this.a - right.a);
  1846. };
  1847. /**
  1848. * Subtracts the passed ones from the current Color4 values and stores the results in "result"
  1849. * @param right defines the second operand
  1850. * @param result defines the Color4 object where to store the result
  1851. * @returns the current Color4 object
  1852. */
  1853. Color4.prototype.subtractToRef = function (right, result) {
  1854. result.r = this.r - right.r;
  1855. result.g = this.g - right.g;
  1856. result.b = this.b - right.b;
  1857. result.a = this.a - right.a;
  1858. return this;
  1859. };
  1860. /**
  1861. * Creates a new Color4 with the current Color4 values multiplied by scale
  1862. * @param scale defines the scaling factor to apply
  1863. * @returns a new Color4 object
  1864. */
  1865. Color4.prototype.scale = function (scale) {
  1866. return new Color4(this.r * scale, this.g * scale, this.b * scale, this.a * scale);
  1867. };
  1868. /**
  1869. * Multiplies the current Color4 values by scale and stores the result in "result"
  1870. * @param scale defines the scaling factor to apply
  1871. * @param result defines the Color4 object where to store the result
  1872. * @returns the current Color4.
  1873. */
  1874. Color4.prototype.scaleToRef = function (scale, result) {
  1875. result.r = this.r * scale;
  1876. result.g = this.g * scale;
  1877. result.b = this.b * scale;
  1878. result.a = this.a * scale;
  1879. return this;
  1880. };
  1881. /**
  1882. * Clamps the rgb values by the min and max values and stores the result into "result"
  1883. * @param min defines minimum clamping value (default is 0)
  1884. * @param max defines maximum clamping value (default is 1)
  1885. * @param result defines color to store the result into.
  1886. * @returns the cuurent Color4
  1887. */
  1888. Color4.prototype.clampToRef = function (min, max, result) {
  1889. if (min === void 0) { min = 0; }
  1890. if (max === void 0) { max = 1; }
  1891. result.r = BABYLON.Scalar.Clamp(this.r, min, max);
  1892. result.g = BABYLON.Scalar.Clamp(this.g, min, max);
  1893. result.b = BABYLON.Scalar.Clamp(this.b, min, max);
  1894. result.a = BABYLON.Scalar.Clamp(this.a, min, max);
  1895. return this;
  1896. };
  1897. /**
  1898. * Multipy an Color4 value by another and return a new Color4 object
  1899. * @param color defines the Color4 value to multiply by
  1900. * @returns a new Color4 object
  1901. */
  1902. Color4.prototype.multiply = function (color) {
  1903. return new Color4(this.r * color.r, this.g * color.g, this.b * color.b, this.a * color.a);
  1904. };
  1905. /**
  1906. * Multipy a Color4 value by another and push the result in a reference value
  1907. * @param color defines the Color4 value to multiply by
  1908. * @param result defines the Color4 to fill the result in
  1909. * @returns the result Color4
  1910. */
  1911. Color4.prototype.multiplyToRef = function (color, result) {
  1912. result.r = this.r * color.r;
  1913. result.g = this.g * color.g;
  1914. result.b = this.b * color.b;
  1915. result.a = this.a * color.a;
  1916. return result;
  1917. };
  1918. /**
  1919. * Creates a string with the Color4 current values
  1920. * @returns the string representation of the Color4 object
  1921. */
  1922. Color4.prototype.toString = function () {
  1923. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + " A:" + this.a + "}";
  1924. };
  1925. /**
  1926. * Returns the string "Color4"
  1927. * @returns "Color4"
  1928. */
  1929. Color4.prototype.getClassName = function () {
  1930. return "Color4";
  1931. };
  1932. /**
  1933. * Compute the Color4 hash code
  1934. * @returns an unique number that can be used to hash Color4 objects
  1935. */
  1936. Color4.prototype.getHashCode = function () {
  1937. var hash = this.r || 0;
  1938. hash = (hash * 397) ^ (this.g || 0);
  1939. hash = (hash * 397) ^ (this.b || 0);
  1940. hash = (hash * 397) ^ (this.a || 0);
  1941. return hash;
  1942. };
  1943. /**
  1944. * Creates a new Color4 copied from the current one
  1945. * @returns a new Color4 object
  1946. */
  1947. Color4.prototype.clone = function () {
  1948. return new Color4(this.r, this.g, this.b, this.a);
  1949. };
  1950. /**
  1951. * Copies the passed Color4 values into the current one
  1952. * @param source defines the source Color4 object
  1953. * @returns the current updated Color4 object
  1954. */
  1955. Color4.prototype.copyFrom = function (source) {
  1956. this.r = source.r;
  1957. this.g = source.g;
  1958. this.b = source.b;
  1959. this.a = source.a;
  1960. return this;
  1961. };
  1962. /**
  1963. * Copies the passed float values into the current one
  1964. * @param r defines the red component to read from
  1965. * @param g defines the green component to read from
  1966. * @param b defines the blue component to read from
  1967. * @param a defines the alpha component to read from
  1968. * @returns the current updated Color4 object
  1969. */
  1970. Color4.prototype.copyFromFloats = function (r, g, b, a) {
  1971. this.r = r;
  1972. this.g = g;
  1973. this.b = b;
  1974. this.a = a;
  1975. return this;
  1976. };
  1977. /**
  1978. * Copies the passed float values into the current one
  1979. * @param r defines the red component to read from
  1980. * @param g defines the green component to read from
  1981. * @param b defines the blue component to read from
  1982. * @param a defines the alpha component to read from
  1983. * @returns the current updated Color4 object
  1984. */
  1985. Color4.prototype.set = function (r, g, b, a) {
  1986. return this.copyFromFloats(r, g, b, a);
  1987. };
  1988. /**
  1989. * Compute the Color4 hexadecimal code as a string
  1990. * @returns a string containing the hexadecimal representation of the Color4 object
  1991. */
  1992. Color4.prototype.toHexString = function () {
  1993. var intR = (this.r * 255) | 0;
  1994. var intG = (this.g * 255) | 0;
  1995. var intB = (this.b * 255) | 0;
  1996. var intA = (this.a * 255) | 0;
  1997. return "#" + BABYLON.Scalar.ToHex(intR) + BABYLON.Scalar.ToHex(intG) + BABYLON.Scalar.ToHex(intB) + BABYLON.Scalar.ToHex(intA);
  1998. };
  1999. /**
  2000. * Computes a new Color4 converted from the current one to linear space
  2001. * @returns a new Color4 object
  2002. */
  2003. Color4.prototype.toLinearSpace = function () {
  2004. var convertedColor = new Color4();
  2005. this.toLinearSpaceToRef(convertedColor);
  2006. return convertedColor;
  2007. };
  2008. /**
  2009. * Converts the Color4 values to linear space and stores the result in "convertedColor"
  2010. * @param convertedColor defines the Color4 object where to store the linear space version
  2011. * @returns the unmodified Color4
  2012. */
  2013. Color4.prototype.toLinearSpaceToRef = function (convertedColor) {
  2014. convertedColor.r = Math.pow(this.r, BABYLON.ToLinearSpace);
  2015. convertedColor.g = Math.pow(this.g, BABYLON.ToLinearSpace);
  2016. convertedColor.b = Math.pow(this.b, BABYLON.ToLinearSpace);
  2017. convertedColor.a = this.a;
  2018. return this;
  2019. };
  2020. /**
  2021. * Computes a new Color4 converted from the current one to gamma space
  2022. * @returns a new Color4 object
  2023. */
  2024. Color4.prototype.toGammaSpace = function () {
  2025. var convertedColor = new Color4();
  2026. this.toGammaSpaceToRef(convertedColor);
  2027. return convertedColor;
  2028. };
  2029. /**
  2030. * Converts the Color4 values to gamma space and stores the result in "convertedColor"
  2031. * @param convertedColor defines the Color4 object where to store the gamma space version
  2032. * @returns the unmodified Color4
  2033. */
  2034. Color4.prototype.toGammaSpaceToRef = function (convertedColor) {
  2035. convertedColor.r = Math.pow(this.r, BABYLON.ToGammaSpace);
  2036. convertedColor.g = Math.pow(this.g, BABYLON.ToGammaSpace);
  2037. convertedColor.b = Math.pow(this.b, BABYLON.ToGammaSpace);
  2038. convertedColor.a = this.a;
  2039. return this;
  2040. };
  2041. // Statics
  2042. /**
  2043. * Creates a new Color4 from the string containing valid hexadecimal values
  2044. * @param hex defines a string containing valid hexadecimal values
  2045. * @returns a new Color4 object
  2046. */
  2047. Color4.FromHexString = function (hex) {
  2048. if (hex.substring(0, 1) !== "#" || hex.length !== 9) {
  2049. //Tools.Warn("Color4.FromHexString must be called with a string like #FFFFFFFF");
  2050. return new Color4(0.0, 0.0, 0.0, 0.0);
  2051. }
  2052. var r = parseInt(hex.substring(1, 3), 16);
  2053. var g = parseInt(hex.substring(3, 5), 16);
  2054. var b = parseInt(hex.substring(5, 7), 16);
  2055. var a = parseInt(hex.substring(7, 9), 16);
  2056. return Color4.FromInts(r, g, b, a);
  2057. };
  2058. /**
  2059. * Creates a new Color4 object set with the linearly interpolated values of "amount" between the left Color4 object and the right Color4 object
  2060. * @param left defines the start value
  2061. * @param right defines the end value
  2062. * @param amount defines the gradient factor
  2063. * @returns a new Color4 object
  2064. */
  2065. Color4.Lerp = function (left, right, amount) {
  2066. var result = new Color4(0.0, 0.0, 0.0, 0.0);
  2067. Color4.LerpToRef(left, right, amount, result);
  2068. return result;
  2069. };
  2070. /**
  2071. * Set the passed "result" with the linearly interpolated values of "amount" between the left Color4 object and the right Color4 object
  2072. * @param left defines the start value
  2073. * @param right defines the end value
  2074. * @param amount defines the gradient factor
  2075. * @param result defines the Color4 object where to store data
  2076. */
  2077. Color4.LerpToRef = function (left, right, amount, result) {
  2078. result.r = left.r + (right.r - left.r) * amount;
  2079. result.g = left.g + (right.g - left.g) * amount;
  2080. result.b = left.b + (right.b - left.b) * amount;
  2081. result.a = left.a + (right.a - left.a) * amount;
  2082. };
  2083. /**
  2084. * Creates a new Color4 from the starting index element of the passed array
  2085. * @param array defines the source array to read from
  2086. * @param offset defines the offset in the source array
  2087. * @returns a new Color4 object
  2088. */
  2089. Color4.FromArray = function (array, offset) {
  2090. if (offset === void 0) { offset = 0; }
  2091. return new Color4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  2092. };
  2093. /**
  2094. * Creates a new Color3 from integer values (< 256)
  2095. * @param r defines the red component to read from (value between 0 and 255)
  2096. * @param g defines the green component to read from (value between 0 and 255)
  2097. * @param b defines the blue component to read from (value between 0 and 255)
  2098. * @param a defines the alpha component to read from (value between 0 and 255)
  2099. * @returns a new Color3 object
  2100. */
  2101. Color4.FromInts = function (r, g, b, a) {
  2102. return new Color4(r / 255.0, g / 255.0, b / 255.0, a / 255.0);
  2103. };
  2104. /**
  2105. * Check the content of a given array and convert it to an array containing RGBA data
  2106. * If the original array was already containing count * 4 values then it is returned directly
  2107. * @param colors defines the array to check
  2108. * @param count defines the number of RGBA data to expect
  2109. * @returns an array containing count * 4 values (RGBA)
  2110. */
  2111. Color4.CheckColors4 = function (colors, count) {
  2112. // Check if color3 was used
  2113. if (colors.length === count * 3) {
  2114. var colors4 = [];
  2115. for (var index = 0; index < colors.length; index += 3) {
  2116. var newIndex = (index / 3) * 4;
  2117. colors4[newIndex] = colors[index];
  2118. colors4[newIndex + 1] = colors[index + 1];
  2119. colors4[newIndex + 2] = colors[index + 2];
  2120. colors4[newIndex + 3] = 1.0;
  2121. }
  2122. return colors4;
  2123. }
  2124. return colors;
  2125. };
  2126. return Color4;
  2127. }());
  2128. BABYLON.Color4 = Color4;
  2129. var Vector2 = /** @class */ (function () {
  2130. /**
  2131. * Creates a new Vector2 from the passed x and y coordinates.
  2132. */
  2133. function Vector2(x, y) {
  2134. this.x = x;
  2135. this.y = y;
  2136. }
  2137. /**
  2138. * Returns a string with the Vector2 coordinates.
  2139. */
  2140. Vector2.prototype.toString = function () {
  2141. return "{X: " + this.x + " Y:" + this.y + "}";
  2142. };
  2143. /**
  2144. * Returns the string "Vector2"
  2145. */
  2146. Vector2.prototype.getClassName = function () {
  2147. return "Vector2";
  2148. };
  2149. /**
  2150. * Returns the Vector2 hash code as a number.
  2151. */
  2152. Vector2.prototype.getHashCode = function () {
  2153. var hash = this.x || 0;
  2154. hash = (hash * 397) ^ (this.y || 0);
  2155. return hash;
  2156. };
  2157. // Operators
  2158. /**
  2159. * Sets the Vector2 coordinates in the passed array or Float32Array from the passed index.
  2160. * Returns the Vector2.
  2161. */
  2162. Vector2.prototype.toArray = function (array, index) {
  2163. if (index === void 0) { index = 0; }
  2164. array[index] = this.x;
  2165. array[index + 1] = this.y;
  2166. return this;
  2167. };
  2168. /**
  2169. * Returns a new array with 2 elements : the Vector2 coordinates.
  2170. */
  2171. Vector2.prototype.asArray = function () {
  2172. var result = new Array();
  2173. this.toArray(result, 0);
  2174. return result;
  2175. };
  2176. /**
  2177. * Sets the Vector2 coordinates with the passed Vector2 coordinates.
  2178. * Returns the updated Vector2.
  2179. */
  2180. Vector2.prototype.copyFrom = function (source) {
  2181. this.x = source.x;
  2182. this.y = source.y;
  2183. return this;
  2184. };
  2185. /**
  2186. * Sets the Vector2 coordinates with the passed floats.
  2187. * Returns the updated Vector2.
  2188. */
  2189. Vector2.prototype.copyFromFloats = function (x, y) {
  2190. this.x = x;
  2191. this.y = y;
  2192. return this;
  2193. };
  2194. /**
  2195. * Sets the Vector2 coordinates with the passed floats.
  2196. * Returns the updated Vector2.
  2197. */
  2198. Vector2.prototype.set = function (x, y) {
  2199. return this.copyFromFloats(x, y);
  2200. };
  2201. /**
  2202. * Returns a new Vector2 set with the addition of the current Vector2 and the passed one coordinates.
  2203. */
  2204. Vector2.prototype.add = function (otherVector) {
  2205. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  2206. };
  2207. /**
  2208. * Sets the "result" coordinates with the addition of the current Vector2 and the passed one coordinates.
  2209. * Returns the Vector2.
  2210. */
  2211. Vector2.prototype.addToRef = function (otherVector, result) {
  2212. result.x = this.x + otherVector.x;
  2213. result.y = this.y + otherVector.y;
  2214. return this;
  2215. };
  2216. /**
  2217. * Set the Vector2 coordinates by adding the passed Vector2 coordinates.
  2218. * Returns the updated Vector2.
  2219. */
  2220. Vector2.prototype.addInPlace = function (otherVector) {
  2221. this.x += otherVector.x;
  2222. this.y += otherVector.y;
  2223. return this;
  2224. };
  2225. /**
  2226. * Returns a new Vector2 by adding the current Vector2 coordinates to the passed Vector3 x, y coordinates.
  2227. */
  2228. Vector2.prototype.addVector3 = function (otherVector) {
  2229. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  2230. };
  2231. /**
  2232. * Returns a new Vector2 set with the subtracted coordinates of the passed one from the current Vector2.
  2233. */
  2234. Vector2.prototype.subtract = function (otherVector) {
  2235. return new Vector2(this.x - otherVector.x, this.y - otherVector.y);
  2236. };
  2237. /**
  2238. * Sets the "result" coordinates with the subtraction of the passed one from the current Vector2 coordinates.
  2239. * Returns the Vector2.
  2240. */
  2241. Vector2.prototype.subtractToRef = function (otherVector, result) {
  2242. result.x = this.x - otherVector.x;
  2243. result.y = this.y - otherVector.y;
  2244. return this;
  2245. };
  2246. /**
  2247. * Sets the current Vector2 coordinates by subtracting from it the passed one coordinates.
  2248. * Returns the updated Vector2.
  2249. */
  2250. Vector2.prototype.subtractInPlace = function (otherVector) {
  2251. this.x -= otherVector.x;
  2252. this.y -= otherVector.y;
  2253. return this;
  2254. };
  2255. /**
  2256. * Multiplies in place the current Vector2 coordinates by the passed ones.
  2257. * Returns the updated Vector2.
  2258. */
  2259. Vector2.prototype.multiplyInPlace = function (otherVector) {
  2260. this.x *= otherVector.x;
  2261. this.y *= otherVector.y;
  2262. return this;
  2263. };
  2264. /**
  2265. * Returns a new Vector2 set with the multiplication of the current Vector2 and the passed one coordinates.
  2266. */
  2267. Vector2.prototype.multiply = function (otherVector) {
  2268. return new Vector2(this.x * otherVector.x, this.y * otherVector.y);
  2269. };
  2270. /**
  2271. * Sets "result" coordinates with the multiplication of the current Vector2 and the passed one coordinates.
  2272. * Returns the Vector2.
  2273. */
  2274. Vector2.prototype.multiplyToRef = function (otherVector, result) {
  2275. result.x = this.x * otherVector.x;
  2276. result.y = this.y * otherVector.y;
  2277. return this;
  2278. };
  2279. /**
  2280. * Returns a new Vector2 set with the Vector2 coordinates multiplied by the passed floats.
  2281. */
  2282. Vector2.prototype.multiplyByFloats = function (x, y) {
  2283. return new Vector2(this.x * x, this.y * y);
  2284. };
  2285. /**
  2286. * Returns a new Vector2 set with the Vector2 coordinates divided by the passed one coordinates.
  2287. */
  2288. Vector2.prototype.divide = function (otherVector) {
  2289. return new Vector2(this.x / otherVector.x, this.y / otherVector.y);
  2290. };
  2291. /**
  2292. * Sets the "result" coordinates with the Vector2 divided by the passed one coordinates.
  2293. * Returns the Vector2.
  2294. */
  2295. Vector2.prototype.divideToRef = function (otherVector, result) {
  2296. result.x = this.x / otherVector.x;
  2297. result.y = this.y / otherVector.y;
  2298. return this;
  2299. };
  2300. /**
  2301. * Divides the current Vector3 coordinates by the passed ones.
  2302. * Returns the updated Vector3.
  2303. */
  2304. Vector2.prototype.divideInPlace = function (otherVector) {
  2305. return this.divideToRef(otherVector, this);
  2306. };
  2307. /**
  2308. * Returns a new Vector2 with current Vector2 negated coordinates.
  2309. */
  2310. Vector2.prototype.negate = function () {
  2311. return new Vector2(-this.x, -this.y);
  2312. };
  2313. /**
  2314. * Multiply the Vector2 coordinates by scale.
  2315. * Returns the updated Vector2.
  2316. */
  2317. Vector2.prototype.scaleInPlace = function (scale) {
  2318. this.x *= scale;
  2319. this.y *= scale;
  2320. return this;
  2321. };
  2322. /**
  2323. * Returns a new Vector2 scaled by "scale" from the current Vector2.
  2324. */
  2325. Vector2.prototype.scale = function (scale) {
  2326. return new Vector2(this.x * scale, this.y * scale);
  2327. };
  2328. /**
  2329. * Boolean : True if the passed vector coordinates strictly equal the current Vector2 ones.
  2330. */
  2331. Vector2.prototype.equals = function (otherVector) {
  2332. return otherVector && this.x === otherVector.x && this.y === otherVector.y;
  2333. };
  2334. /**
  2335. * Boolean : True if the passed vector coordinates are close to the current ones by a distance of epsilon.
  2336. */
  2337. Vector2.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  2338. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  2339. return otherVector && BABYLON.Scalar.WithinEpsilon(this.x, otherVector.x, epsilon) && BABYLON.Scalar.WithinEpsilon(this.y, otherVector.y, epsilon);
  2340. };
  2341. // Properties
  2342. /**
  2343. * Returns the vector length (float).
  2344. */
  2345. Vector2.prototype.length = function () {
  2346. return Math.sqrt(this.x * this.x + this.y * this.y);
  2347. };
  2348. /**
  2349. * Returns the vector squared length (float);
  2350. */
  2351. Vector2.prototype.lengthSquared = function () {
  2352. return (this.x * this.x + this.y * this.y);
  2353. };
  2354. // Methods
  2355. /**
  2356. * Normalize the vector.
  2357. * Returns the updated Vector2.
  2358. */
  2359. Vector2.prototype.normalize = function () {
  2360. var len = this.length();
  2361. if (len === 0)
  2362. return this;
  2363. var num = 1.0 / len;
  2364. this.x *= num;
  2365. this.y *= num;
  2366. return this;
  2367. };
  2368. /**
  2369. * Returns a new Vector2 copied from the Vector2.
  2370. */
  2371. Vector2.prototype.clone = function () {
  2372. return new Vector2(this.x, this.y);
  2373. };
  2374. // Statics
  2375. /**
  2376. * Returns a new Vector2(0, 0)
  2377. */
  2378. Vector2.Zero = function () {
  2379. return new Vector2(0, 0);
  2380. };
  2381. /**
  2382. * Returns a new Vector2(1, 1)
  2383. */
  2384. Vector2.One = function () {
  2385. return new Vector2(1, 1);
  2386. };
  2387. /**
  2388. * Returns a new Vector2 set from the passed index element of the passed array.
  2389. */
  2390. Vector2.FromArray = function (array, offset) {
  2391. if (offset === void 0) { offset = 0; }
  2392. return new Vector2(array[offset], array[offset + 1]);
  2393. };
  2394. /**
  2395. * Sets "result" from the passed index element of the passed array.
  2396. */
  2397. Vector2.FromArrayToRef = function (array, offset, result) {
  2398. result.x = array[offset];
  2399. result.y = array[offset + 1];
  2400. };
  2401. /**
  2402. * Retuns a new Vector2 located for "amount" (float) on the CatmullRom spline defined by the passed four Vector2.
  2403. */
  2404. Vector2.CatmullRom = function (value1, value2, value3, value4, amount) {
  2405. var squared = amount * amount;
  2406. var cubed = amount * squared;
  2407. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) +
  2408. (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) +
  2409. ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  2410. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) +
  2411. (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) +
  2412. ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  2413. return new Vector2(x, y);
  2414. };
  2415. /**
  2416. * Returns a new Vector2 set with same the coordinates than "value" ones if the vector "value" is in the square defined by "min" and "max".
  2417. * If a coordinate of "value" is lower than "min" coordinates, the returned Vector2 is given this "min" coordinate.
  2418. * If a coordinate of "value" is greater than "max" coordinates, the returned Vector2 is given this "max" coordinate.
  2419. */
  2420. Vector2.Clamp = function (value, min, max) {
  2421. var x = value.x;
  2422. x = (x > max.x) ? max.x : x;
  2423. x = (x < min.x) ? min.x : x;
  2424. var y = value.y;
  2425. y = (y > max.y) ? max.y : y;
  2426. y = (y < min.y) ? min.y : y;
  2427. return new Vector2(x, y);
  2428. };
  2429. /**
  2430. * Returns a new Vector2 located for "amount" (float) on the Hermite spline defined by the vectors "value1", "value3", "tangent1", "tangent2".
  2431. */
  2432. Vector2.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  2433. var squared = amount * amount;
  2434. var cubed = amount * squared;
  2435. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  2436. var part2 = (-2.0 * cubed) + (3.0 * squared);
  2437. var part3 = (cubed - (2.0 * squared)) + amount;
  2438. var part4 = cubed - squared;
  2439. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  2440. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  2441. return new Vector2(x, y);
  2442. };
  2443. /**
  2444. * Returns a new Vector2 located for "amount" (float) on the linear interpolation between the vector "start" adn the vector "end".
  2445. */
  2446. Vector2.Lerp = function (start, end, amount) {
  2447. var x = start.x + ((end.x - start.x) * amount);
  2448. var y = start.y + ((end.y - start.y) * amount);
  2449. return new Vector2(x, y);
  2450. };
  2451. /**
  2452. * Returns the dot product (float) of the vector "left" and the vector "right".
  2453. */
  2454. Vector2.Dot = function (left, right) {
  2455. return left.x * right.x + left.y * right.y;
  2456. };
  2457. /**
  2458. * Returns a new Vector2 equal to the normalized passed vector.
  2459. */
  2460. Vector2.Normalize = function (vector) {
  2461. var newVector = vector.clone();
  2462. newVector.normalize();
  2463. return newVector;
  2464. };
  2465. /**
  2466. * Returns a new Vecto2 set with the minimal coordinate values from the "left" and "right" vectors.
  2467. */
  2468. Vector2.Minimize = function (left, right) {
  2469. var x = (left.x < right.x) ? left.x : right.x;
  2470. var y = (left.y < right.y) ? left.y : right.y;
  2471. return new Vector2(x, y);
  2472. };
  2473. /**
  2474. * Returns a new Vecto2 set with the maximal coordinate values from the "left" and "right" vectors.
  2475. */
  2476. Vector2.Maximize = function (left, right) {
  2477. var x = (left.x > right.x) ? left.x : right.x;
  2478. var y = (left.y > right.y) ? left.y : right.y;
  2479. return new Vector2(x, y);
  2480. };
  2481. /**
  2482. * Returns a new Vecto2 set with the transformed coordinates of the passed vector by the passed transformation matrix.
  2483. */
  2484. Vector2.Transform = function (vector, transformation) {
  2485. var r = Vector2.Zero();
  2486. Vector2.TransformToRef(vector, transformation, r);
  2487. return r;
  2488. };
  2489. /**
  2490. * Transforms the passed vector coordinates by the passed transformation matrix and stores the result in the vector "result" coordinates.
  2491. */
  2492. Vector2.TransformToRef = function (vector, transformation, result) {
  2493. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + transformation.m[12];
  2494. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + transformation.m[13];
  2495. result.x = x;
  2496. result.y = y;
  2497. };
  2498. /**
  2499. * Boolean : True if the point "p" is in the triangle defined by the vertors "p0", "p1", "p2"
  2500. */
  2501. Vector2.PointInTriangle = function (p, p0, p1, p2) {
  2502. var a = 1 / 2 * (-p1.y * p2.x + p0.y * (-p1.x + p2.x) + p0.x * (p1.y - p2.y) + p1.x * p2.y);
  2503. var sign = a < 0 ? -1 : 1;
  2504. var s = (p0.y * p2.x - p0.x * p2.y + (p2.y - p0.y) * p.x + (p0.x - p2.x) * p.y) * sign;
  2505. var t = (p0.x * p1.y - p0.y * p1.x + (p0.y - p1.y) * p.x + (p1.x - p0.x) * p.y) * sign;
  2506. return s > 0 && t > 0 && (s + t) < 2 * a * sign;
  2507. };
  2508. /**
  2509. * Returns the distance (float) between the vectors "value1" and "value2".
  2510. */
  2511. Vector2.Distance = function (value1, value2) {
  2512. return Math.sqrt(Vector2.DistanceSquared(value1, value2));
  2513. };
  2514. /**
  2515. * Returns the squared distance (float) between the vectors "value1" and "value2".
  2516. */
  2517. Vector2.DistanceSquared = function (value1, value2) {
  2518. var x = value1.x - value2.x;
  2519. var y = value1.y - value2.y;
  2520. return (x * x) + (y * y);
  2521. };
  2522. /**
  2523. * Returns a new Vecto2 located at the center of the vectors "value1" and "value2".
  2524. */
  2525. Vector2.Center = function (value1, value2) {
  2526. var center = value1.add(value2);
  2527. center.scaleInPlace(0.5);
  2528. return center;
  2529. };
  2530. /**
  2531. * Returns the shortest distance (float) between the point "p" and the segment defined by the two points "segA" and "segB".
  2532. */
  2533. Vector2.DistanceOfPointFromSegment = function (p, segA, segB) {
  2534. var l2 = Vector2.DistanceSquared(segA, segB);
  2535. if (l2 === 0.0) {
  2536. return Vector2.Distance(p, segA);
  2537. }
  2538. var v = segB.subtract(segA);
  2539. var t = Math.max(0, Math.min(1, Vector2.Dot(p.subtract(segA), v) / l2));
  2540. var proj = segA.add(v.multiplyByFloats(t, t));
  2541. return Vector2.Distance(p, proj);
  2542. };
  2543. return Vector2;
  2544. }());
  2545. BABYLON.Vector2 = Vector2;
  2546. /**
  2547. * Classed used to store (x,y,z) vector representation
  2548. * A Vector3 is the main object used in 3D geometry
  2549. * It can represent etiher the coordinates of a point the space, either a direction
  2550. * Reminder: Babylon.js uses a left handed forward facing system
  2551. */
  2552. var Vector3 = /** @class */ (function () {
  2553. /**
  2554. * Creates a new Vector3 object from the passed x, y, z (floats) coordinates.
  2555. * @param x defines the first coordinates (on X axis)
  2556. * @param y defines the second coordinates (on Y axis)
  2557. * @param z defines the third coordinates (on Z axis)
  2558. */
  2559. function Vector3(
  2560. /**
  2561. * Defines the first coordinates (on X axis)
  2562. */
  2563. x,
  2564. /**
  2565. * Defines the second coordinates (on Y axis)
  2566. */
  2567. y,
  2568. /**
  2569. * Defines the third coordinates (on Z axis)
  2570. */
  2571. z) {
  2572. this.x = x;
  2573. this.y = y;
  2574. this.z = z;
  2575. }
  2576. /**
  2577. * Creates a string representation of the Vector3
  2578. * @returns a string with the Vector3 coordinates.
  2579. */
  2580. Vector3.prototype.toString = function () {
  2581. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + "}";
  2582. };
  2583. /**
  2584. * Gets the class name
  2585. * @returns the string "Vector3"
  2586. */
  2587. Vector3.prototype.getClassName = function () {
  2588. return "Vector3";
  2589. };
  2590. /**
  2591. * Creates the Vector3 hash code
  2592. * @returns a number which tends to be unique between Vector3 instances
  2593. */
  2594. Vector3.prototype.getHashCode = function () {
  2595. var hash = this.x || 0;
  2596. hash = (hash * 397) ^ (this.y || 0);
  2597. hash = (hash * 397) ^ (this.z || 0);
  2598. return hash;
  2599. };
  2600. // Operators
  2601. /**
  2602. * Creates an array containing three elements : the coordinates of the Vector3
  2603. * @returns a new array of numbers
  2604. */
  2605. Vector3.prototype.asArray = function () {
  2606. var result = [];
  2607. this.toArray(result, 0);
  2608. return result;
  2609. };
  2610. /**
  2611. * Populates the passed array or Float32Array from the passed index with the successive coordinates of the Vector3
  2612. * @param array defines the destination array
  2613. * @param index defines the offset in the destination array
  2614. * @returns the current Vector3
  2615. */
  2616. Vector3.prototype.toArray = function (array, index) {
  2617. if (index === void 0) { index = 0; }
  2618. array[index] = this.x;
  2619. array[index + 1] = this.y;
  2620. array[index + 2] = this.z;
  2621. return this;
  2622. };
  2623. /**
  2624. * Converts the current Vector3 into a quaternion (considering that the Vector3 contains Euler angles representation of a rotation)
  2625. * @returns a new Quaternion object, computed from the Vector3 coordinates
  2626. */
  2627. Vector3.prototype.toQuaternion = function () {
  2628. var result = new Quaternion(0.0, 0.0, 0.0, 1.0);
  2629. var cosxPlusz = Math.cos((this.x + this.z) * 0.5);
  2630. var sinxPlusz = Math.sin((this.x + this.z) * 0.5);
  2631. var coszMinusx = Math.cos((this.z - this.x) * 0.5);
  2632. var sinzMinusx = Math.sin((this.z - this.x) * 0.5);
  2633. var cosy = Math.cos(this.y * 0.5);
  2634. var siny = Math.sin(this.y * 0.5);
  2635. result.x = coszMinusx * siny;
  2636. result.y = -sinzMinusx * siny;
  2637. result.z = sinxPlusz * cosy;
  2638. result.w = cosxPlusz * cosy;
  2639. return result;
  2640. };
  2641. /**
  2642. * Adds the passed vector to the current Vector3
  2643. * @param otherVector defines the second operand
  2644. * @returns the current updated Vector3
  2645. */
  2646. Vector3.prototype.addInPlace = function (otherVector) {
  2647. this.x += otherVector.x;
  2648. this.y += otherVector.y;
  2649. this.z += otherVector.z;
  2650. return this;
  2651. };
  2652. /**
  2653. * Gets a new Vector3, result of the addition the current Vector3 and the passed vector
  2654. * @param otherVector defines the second operand
  2655. * @returns the resulting Vector3
  2656. */
  2657. Vector3.prototype.add = function (otherVector) {
  2658. return new Vector3(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z);
  2659. };
  2660. /**
  2661. * Adds the current Vector3 to the passed one and stores the result in the vector "result"
  2662. * @param otherVector defines the second operand
  2663. * @param result defines the Vector3 object where to store the result
  2664. * @returns the current Vector3
  2665. */
  2666. Vector3.prototype.addToRef = function (otherVector, result) {
  2667. result.x = this.x + otherVector.x;
  2668. result.y = this.y + otherVector.y;
  2669. result.z = this.z + otherVector.z;
  2670. return this;
  2671. };
  2672. /**
  2673. * Subtract the passed vector from the current Vector3
  2674. * @param otherVector defines the second operand
  2675. * @returns the current updated Vector3
  2676. */
  2677. Vector3.prototype.subtractInPlace = function (otherVector) {
  2678. this.x -= otherVector.x;
  2679. this.y -= otherVector.y;
  2680. this.z -= otherVector.z;
  2681. return this;
  2682. };
  2683. /**
  2684. * Returns a new Vector3, result of the subtraction of the passed vector from the current Vector3
  2685. * @param otherVector defines the second operand
  2686. * @returns the resulting Vector3
  2687. */
  2688. Vector3.prototype.subtract = function (otherVector) {
  2689. return new Vector3(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z);
  2690. };
  2691. /**
  2692. * Subtracts the passed vector from the current Vector3 and stores the result in the vector "result".
  2693. * @param otherVector defines the second operand
  2694. * @param result defines the Vector3 object where to store the result
  2695. * @returns the current Vector3
  2696. */
  2697. Vector3.prototype.subtractToRef = function (otherVector, result) {
  2698. result.x = this.x - otherVector.x;
  2699. result.y = this.y - otherVector.y;
  2700. result.z = this.z - otherVector.z;
  2701. return this;
  2702. };
  2703. /**
  2704. * Returns a new Vector3 set with the subtraction of the passed floats from the current Vector3 coordinates
  2705. * @param x defines the x coordinate of the operand
  2706. * @param y defines the y coordinate of the operand
  2707. * @param z defines the z coordinate of the operand
  2708. * @returns the resulting Vector3
  2709. */
  2710. Vector3.prototype.subtractFromFloats = function (x, y, z) {
  2711. return new Vector3(this.x - x, this.y - y, this.z - z);
  2712. };
  2713. /**
  2714. * Subtracts the passed floats from the current Vector3 coordinates and set the passed vector "result" with this result
  2715. * @param x defines the x coordinate of the operand
  2716. * @param y defines the y coordinate of the operand
  2717. * @param z defines the z coordinate of the operand
  2718. * @param result defines the Vector3 object where to store the result
  2719. * @returns the current Vector3
  2720. */
  2721. Vector3.prototype.subtractFromFloatsToRef = function (x, y, z, result) {
  2722. result.x = this.x - x;
  2723. result.y = this.y - y;
  2724. result.z = this.z - z;
  2725. return this;
  2726. };
  2727. /**
  2728. * Gets a new Vector3 set with the current Vector3 negated coordinates
  2729. * @returns a new Vector3
  2730. */
  2731. Vector3.prototype.negate = function () {
  2732. return new Vector3(-this.x, -this.y, -this.z);
  2733. };
  2734. /**
  2735. * Multiplies the Vector3 coordinates by the float "scale"
  2736. * @param scale defines the multiplier factor
  2737. * @returns the current updated Vector3
  2738. */
  2739. Vector3.prototype.scaleInPlace = function (scale) {
  2740. this.x *= scale;
  2741. this.y *= scale;
  2742. this.z *= scale;
  2743. return this;
  2744. };
  2745. /**
  2746. * Returns a new Vector3 set with the current Vector3 coordinates multiplied by the float "scale"
  2747. * @param scale defines the multiplier factor
  2748. * @returns a new Vector3
  2749. */
  2750. Vector3.prototype.scale = function (scale) {
  2751. return new Vector3(this.x * scale, this.y * scale, this.z * scale);
  2752. };
  2753. /**
  2754. * Multiplies the current Vector3 coordinates by the float "scale" and stores the result in the passed vector "result" coordinates
  2755. * @param scale defines the multiplier factor
  2756. * @param result defines the Vector3 object where to store the result
  2757. * @returns the current Vector3
  2758. */
  2759. Vector3.prototype.scaleToRef = function (scale, result) {
  2760. result.x = this.x * scale;
  2761. result.y = this.y * scale;
  2762. result.z = this.z * scale;
  2763. return this;
  2764. };
  2765. /**
  2766. * Returns true if the current Vector3 and the passed vector coordinates are strictly equal
  2767. * @param otherVector defines the second operand
  2768. * @returns true if both vectors are equals
  2769. */
  2770. Vector3.prototype.equals = function (otherVector) {
  2771. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z;
  2772. };
  2773. /**
  2774. * Returns true if the current Vector3 and the passed vector coordinates are distant less than epsilon
  2775. * @param otherVector defines the second operand
  2776. * @param epsilon defines the minimal distance to define values as equals
  2777. * @returns true if both vectors are distant less than epsilon
  2778. */
  2779. Vector3.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  2780. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  2781. return otherVector && BABYLON.Scalar.WithinEpsilon(this.x, otherVector.x, epsilon) && BABYLON.Scalar.WithinEpsilon(this.y, otherVector.y, epsilon) && BABYLON.Scalar.WithinEpsilon(this.z, otherVector.z, epsilon);
  2782. };
  2783. /**
  2784. * Returns true if the current Vector3 coordinates equals the passed floats
  2785. * @param x defines the x coordinate of the operand
  2786. * @param y defines the y coordinate of the operand
  2787. * @param z defines the z coordinate of the operand
  2788. * @returns true if both vectors are equals
  2789. */
  2790. Vector3.prototype.equalsToFloats = function (x, y, z) {
  2791. return this.x === x && this.y === y && this.z === z;
  2792. };
  2793. /**
  2794. * Multiplies the current Vector3 coordinates by the passed ones
  2795. * @param otherVector defines the second operand
  2796. * @returns the current updated Vector3
  2797. */
  2798. Vector3.prototype.multiplyInPlace = function (otherVector) {
  2799. this.x *= otherVector.x;
  2800. this.y *= otherVector.y;
  2801. this.z *= otherVector.z;
  2802. return this;
  2803. };
  2804. /**
  2805. * Returns a new Vector3, result of the multiplication of the current Vector3 by the passed vector
  2806. * @param otherVector defines the second operand
  2807. * @returns the new Vector3
  2808. */
  2809. Vector3.prototype.multiply = function (otherVector) {
  2810. return new Vector3(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z);
  2811. };
  2812. /**
  2813. * Multiplies the current Vector3 by the passed one and stores the result in the passed vector "result"
  2814. * @param otherVector defines the second operand
  2815. * @param result defines the Vector3 object where to store the result
  2816. * @returns the current Vector3
  2817. */
  2818. Vector3.prototype.multiplyToRef = function (otherVector, result) {
  2819. result.x = this.x * otherVector.x;
  2820. result.y = this.y * otherVector.y;
  2821. result.z = this.z * otherVector.z;
  2822. return this;
  2823. };
  2824. /**
  2825. * Returns a new Vector3 set with the result of the mulliplication of the current Vector3 coordinates by the passed floats
  2826. * @param x defines the x coordinate of the operand
  2827. * @param y defines the y coordinate of the operand
  2828. * @param z defines the z coordinate of the operand
  2829. * @returns the new Vector3
  2830. */
  2831. Vector3.prototype.multiplyByFloats = function (x, y, z) {
  2832. return new Vector3(this.x * x, this.y * y, this.z * z);
  2833. };
  2834. /**
  2835. * Returns a new Vector3 set with the result of the division of the current Vector3 coordinates by the passed ones
  2836. * @param otherVector defines the second operand
  2837. * @returns the new Vector3
  2838. */
  2839. Vector3.prototype.divide = function (otherVector) {
  2840. return new Vector3(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z);
  2841. };
  2842. /**
  2843. * Divides the current Vector3 coordinates by the passed ones and stores the result in the passed vector "result"
  2844. * @param otherVector defines the second operand
  2845. * @param result defines the Vector3 object where to store the result
  2846. * @returns the current Vector3
  2847. */
  2848. Vector3.prototype.divideToRef = function (otherVector, result) {
  2849. result.x = this.x / otherVector.x;
  2850. result.y = this.y / otherVector.y;
  2851. result.z = this.z / otherVector.z;
  2852. return this;
  2853. };
  2854. /**
  2855. * Divides the current Vector3 coordinates by the passed ones.
  2856. * @param otherVector defines the second operand
  2857. * @returns the current updated Vector3
  2858. */
  2859. Vector3.prototype.divideInPlace = function (otherVector) {
  2860. return this.divideToRef(otherVector, this);
  2861. };
  2862. /**
  2863. * Updates the current Vector3 with the minimal coordinate values between its and the passed vector ones
  2864. * @param other defines the second operand
  2865. * @returns the current updated Vector3
  2866. */
  2867. Vector3.prototype.minimizeInPlace = function (other) {
  2868. if (other.x < this.x)
  2869. this.x = other.x;
  2870. if (other.y < this.y)
  2871. this.y = other.y;
  2872. if (other.z < this.z)
  2873. this.z = other.z;
  2874. return this;
  2875. };
  2876. /**
  2877. * Updates the current Vector3 with the maximal coordinate values between its and the passed vector ones.
  2878. * @param other defines the second operand
  2879. * @returns the current updated Vector3
  2880. */
  2881. Vector3.prototype.maximizeInPlace = function (other) {
  2882. if (other.x > this.x)
  2883. this.x = other.x;
  2884. if (other.y > this.y)
  2885. this.y = other.y;
  2886. if (other.z > this.z)
  2887. this.z = other.z;
  2888. return this;
  2889. };
  2890. Object.defineProperty(Vector3.prototype, "isNonUniform", {
  2891. /**
  2892. * Gets a boolean indicating that the vector is non uniform meaning x, y or z are not all the same
  2893. */
  2894. get: function () {
  2895. var absX = Math.abs(this.x);
  2896. var absY = Math.abs(this.y);
  2897. if (absX !== absY) {
  2898. return true;
  2899. }
  2900. var absZ = Math.abs(this.z);
  2901. if (absX !== absZ) {
  2902. return true;
  2903. }
  2904. if (absY !== absZ) {
  2905. return true;
  2906. }
  2907. return false;
  2908. },
  2909. enumerable: true,
  2910. configurable: true
  2911. });
  2912. // Properties
  2913. /**
  2914. * Gets the length of the Vector3
  2915. * @returns the length of the Vecto3
  2916. */
  2917. Vector3.prototype.length = function () {
  2918. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z);
  2919. };
  2920. /**
  2921. * Gets the squared length of the Vector3
  2922. * @returns squared length of the Vector3
  2923. */
  2924. Vector3.prototype.lengthSquared = function () {
  2925. return (this.x * this.x + this.y * this.y + this.z * this.z);
  2926. };
  2927. /**
  2928. * Normalize the current Vector3.
  2929. * Please note that this is an in place operation.
  2930. * @returns the current updated Vector3
  2931. */
  2932. Vector3.prototype.normalize = function () {
  2933. var len = this.length();
  2934. if (len === 0 || len === 1.0)
  2935. return this;
  2936. var num = 1.0 / len;
  2937. this.x *= num;
  2938. this.y *= num;
  2939. this.z *= num;
  2940. return this;
  2941. };
  2942. /**
  2943. * Normalize the current Vector3 to a new vector
  2944. * @returns the new Vector3
  2945. */
  2946. Vector3.prototype.normalizeToNew = function () {
  2947. var normalized = new Vector3(0, 0, 0);
  2948. this.normalizeToRef(normalized);
  2949. return normalized;
  2950. };
  2951. /**
  2952. * Normalize the current Vector3 to the reference
  2953. * @param reference define the Vector3 to update
  2954. * @returns the updated Vector3
  2955. */
  2956. Vector3.prototype.normalizeToRef = function (reference) {
  2957. var len = this.length();
  2958. if (len === 0 || len === 1.0) {
  2959. reference.set(this.x, this.y, this.z);
  2960. return reference;
  2961. }
  2962. var scale = 1.0 / len;
  2963. this.scaleToRef(scale, reference);
  2964. return reference;
  2965. };
  2966. /**
  2967. * Creates a new Vector3 copied from the current Vector3
  2968. * @returns the new Vector3
  2969. */
  2970. Vector3.prototype.clone = function () {
  2971. return new Vector3(this.x, this.y, this.z);
  2972. };
  2973. /**
  2974. * Copies the passed vector coordinates to the current Vector3 ones
  2975. * @param source defines the source Vector3
  2976. * @returns the current updated Vector3
  2977. */
  2978. Vector3.prototype.copyFrom = function (source) {
  2979. this.x = source.x;
  2980. this.y = source.y;
  2981. this.z = source.z;
  2982. return this;
  2983. };
  2984. /**
  2985. * Copies the passed floats to the current Vector3 coordinates
  2986. * @param x defines the x coordinate of the operand
  2987. * @param y defines the y coordinate of the operand
  2988. * @param z defines the z coordinate of the operand
  2989. * @returns the current updated Vector3
  2990. */
  2991. Vector3.prototype.copyFromFloats = function (x, y, z) {
  2992. this.x = x;
  2993. this.y = y;
  2994. this.z = z;
  2995. return this;
  2996. };
  2997. /**
  2998. * Copies the passed floats to the current Vector3 coordinates
  2999. * @param x defines the x coordinate of the operand
  3000. * @param y defines the y coordinate of the operand
  3001. * @param z defines the z coordinate of the operand
  3002. * @returns the current updated Vector3
  3003. */
  3004. Vector3.prototype.set = function (x, y, z) {
  3005. return this.copyFromFloats(x, y, z);
  3006. };
  3007. // Statics
  3008. /**
  3009. * Get the clip factor between two vectors
  3010. * @param vector0 defines the first operand
  3011. * @param vector1 defines the second operand
  3012. * @param axis defines the axis to use
  3013. * @param size defines the size along the axis
  3014. * @returns the clip factor
  3015. */
  3016. Vector3.GetClipFactor = function (vector0, vector1, axis, size) {
  3017. var d0 = Vector3.Dot(vector0, axis) - size;
  3018. var d1 = Vector3.Dot(vector1, axis) - size;
  3019. var s = d0 / (d0 - d1);
  3020. return s;
  3021. };
  3022. /**
  3023. * Get angle between two vectors
  3024. * @param vector0 angle between vector0 and vector1
  3025. * @param vector1 angle between vector0 and vector1
  3026. * @param normal direction of the normal
  3027. * @return the angle between vector0 and vector1
  3028. */
  3029. Vector3.GetAngleBetweenVectors = function (vector0, vector1, normal) {
  3030. var v0 = vector0.clone().normalize();
  3031. var v1 = vector1.clone().normalize();
  3032. var dot = Vector3.Dot(v0, v1);
  3033. var n = Vector3.Cross(v0, v1);
  3034. if (Vector3.Dot(n, normal) > 0) {
  3035. return Math.acos(dot);
  3036. }
  3037. return -Math.acos(dot);
  3038. };
  3039. /**
  3040. * Returns a new Vector3 set from the index "offset" of the passed array
  3041. * @param array defines the source array
  3042. * @param offset defines the offset in the source array
  3043. * @returns the new Vector3
  3044. */
  3045. Vector3.FromArray = function (array, offset) {
  3046. if (!offset) {
  3047. offset = 0;
  3048. }
  3049. return new Vector3(array[offset], array[offset + 1], array[offset + 2]);
  3050. };
  3051. /**
  3052. * Returns a new Vector3 set from the index "offset" of the passed Float32Array
  3053. * This function is deprecated. Use FromArray instead
  3054. * @param array defines the source array
  3055. * @param offset defines the offset in the source array
  3056. * @returns the new Vector3
  3057. */
  3058. Vector3.FromFloatArray = function (array, offset) {
  3059. return Vector3.FromArray(array, offset);
  3060. };
  3061. /**
  3062. * Sets the passed vector "result" with the element values from the index "offset" of the passed array
  3063. * @param array defines the source array
  3064. * @param offset defines the offset in the source array
  3065. * @param result defines the Vector3 where to store the result
  3066. */
  3067. Vector3.FromArrayToRef = function (array, offset, result) {
  3068. result.x = array[offset];
  3069. result.y = array[offset + 1];
  3070. result.z = array[offset + 2];
  3071. };
  3072. /**
  3073. * Sets the passed vector "result" with the element values from the index "offset" of the passed Float32Array
  3074. * This function is deprecated. Use FromArrayToRef instead.
  3075. * @param array defines the source array
  3076. * @param offset defines the offset in the source array
  3077. * @param result defines the Vector3 where to store the result
  3078. */
  3079. Vector3.FromFloatArrayToRef = function (array, offset, result) {
  3080. return Vector3.FromArrayToRef(array, offset, result);
  3081. };
  3082. /**
  3083. * Sets the passed vector "result" with the passed floats.
  3084. * @param x defines the x coordinate of the source
  3085. * @param y defines the y coordinate of the source
  3086. * @param z defines the z coordinate of the source
  3087. * @param result defines the Vector3 where to store the result
  3088. */
  3089. Vector3.FromFloatsToRef = function (x, y, z, result) {
  3090. result.x = x;
  3091. result.y = y;
  3092. result.z = z;
  3093. };
  3094. /**
  3095. * Returns a new Vector3 set to (0.0, 0.0, 0.0)
  3096. * @returns a new empty Vector3
  3097. */
  3098. Vector3.Zero = function () {
  3099. return new Vector3(0.0, 0.0, 0.0);
  3100. };
  3101. /**
  3102. * Returns a new Vector3 set to (1.0, 1.0, 1.0)
  3103. * @returns a new unit Vector3
  3104. */
  3105. Vector3.One = function () {
  3106. return new Vector3(1.0, 1.0, 1.0);
  3107. };
  3108. /**
  3109. * Returns a new Vector3 set to (0.0, 1.0, 0.0)
  3110. * @returns a new up Vector3
  3111. */
  3112. Vector3.Up = function () {
  3113. return new Vector3(0.0, 1.0, 0.0);
  3114. };
  3115. /**
  3116. * Returns a new Vector3 set to (0.0, 0.0, 1.0)
  3117. * @returns a new forward Vector3
  3118. */
  3119. Vector3.Forward = function () {
  3120. return new Vector3(0.0, 0.0, 1.0);
  3121. };
  3122. /**
  3123. * Returns a new Vector3 set to (1.0, 0.0, 0.0)
  3124. * @returns a new right Vector3
  3125. */
  3126. Vector3.Right = function () {
  3127. return new Vector3(1.0, 0.0, 0.0);
  3128. };
  3129. /**
  3130. * Returns a new Vector3 set to (-1.0, 0.0, 0.0)
  3131. * @returns a new left Vector3
  3132. */
  3133. Vector3.Left = function () {
  3134. return new Vector3(-1.0, 0.0, 0.0);
  3135. };
  3136. /**
  3137. * Returns a new Vector3 set with the result of the transformation by the passed matrix of the passed vector.
  3138. * This method computes tranformed coordinates only, not transformed direction vectors (ie. it takes translation in account)
  3139. * @param vector defines the Vector3 to transform
  3140. * @param transformation defines the transformation matrix
  3141. * @returns the transformed Vector3
  3142. */
  3143. Vector3.TransformCoordinates = function (vector, transformation) {
  3144. var result = Vector3.Zero();
  3145. Vector3.TransformCoordinatesToRef(vector, transformation, result);
  3146. return result;
  3147. };
  3148. /**
  3149. * Sets the passed vector "result" coordinates with the result of the transformation by the passed matrix of the passed vector
  3150. * This method computes tranformed coordinates only, not transformed direction vectors (ie. it takes translation in account)
  3151. * @param vector defines the Vector3 to transform
  3152. * @param transformation defines the transformation matrix
  3153. * @param result defines the Vector3 where to store the result
  3154. */
  3155. Vector3.TransformCoordinatesToRef = function (vector, transformation, result) {
  3156. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]) + transformation.m[12];
  3157. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]) + transformation.m[13];
  3158. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]) + transformation.m[14];
  3159. var w = (vector.x * transformation.m[3]) + (vector.y * transformation.m[7]) + (vector.z * transformation.m[11]) + transformation.m[15];
  3160. result.x = x / w;
  3161. result.y = y / w;
  3162. result.z = z / w;
  3163. };
  3164. /**
  3165. * Sets the passed vector "result" coordinates with the result of the transformation by the passed matrix of the passed floats (x, y, z)
  3166. * This method computes tranformed coordinates only, not transformed direction vectors
  3167. * @param x define the x coordinate of the source vector
  3168. * @param y define the y coordinate of the source vector
  3169. * @param z define the z coordinate of the source vector
  3170. * @param transformation defines the transformation matrix
  3171. * @param result defines the Vector3 where to store the result
  3172. */
  3173. Vector3.TransformCoordinatesFromFloatsToRef = function (x, y, z, transformation, result) {
  3174. var rx = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]) + transformation.m[12];
  3175. var ry = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]) + transformation.m[13];
  3176. var rz = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]) + transformation.m[14];
  3177. var rw = (x * transformation.m[3]) + (y * transformation.m[7]) + (z * transformation.m[11]) + transformation.m[15];
  3178. result.x = rx / rw;
  3179. result.y = ry / rw;
  3180. result.z = rz / rw;
  3181. };
  3182. /**
  3183. * Returns a new Vector3 set with the result of the normal transformation by the passed matrix of the passed vector
  3184. * This methods computes transformed normalized direction vectors only (ie. it does not apply translation)
  3185. * @param vector defines the Vector3 to transform
  3186. * @param transformation defines the transformation matrix
  3187. * @returns the new Vector3
  3188. */
  3189. Vector3.TransformNormal = function (vector, transformation) {
  3190. var result = Vector3.Zero();
  3191. Vector3.TransformNormalToRef(vector, transformation, result);
  3192. return result;
  3193. };
  3194. /**
  3195. * Sets the passed vector "result" with the result of the normal transformation by the passed matrix of the passed vector
  3196. * This methods computes transformed normalized direction vectors only (ie. it does not apply translation)
  3197. * @param vector defines the Vector3 to transform
  3198. * @param transformation defines the transformation matrix
  3199. * @param result defines the Vector3 where to store the result
  3200. */
  3201. Vector3.TransformNormalToRef = function (vector, transformation, result) {
  3202. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]);
  3203. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]);
  3204. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]);
  3205. result.x = x;
  3206. result.y = y;
  3207. result.z = z;
  3208. };
  3209. /**
  3210. * Sets the passed vector "result" with the result of the normal transformation by the passed matrix of the passed floats (x, y, z)
  3211. * This methods computes transformed normalized direction vectors only (ie. it does not apply translation)
  3212. * @param x define the x coordinate of the source vector
  3213. * @param y define the y coordinate of the source vector
  3214. * @param z define the z coordinate of the source vector
  3215. * @param transformation defines the transformation matrix
  3216. * @param result defines the Vector3 where to store the result
  3217. */
  3218. Vector3.TransformNormalFromFloatsToRef = function (x, y, z, transformation, result) {
  3219. result.x = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]);
  3220. result.y = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]);
  3221. result.z = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]);
  3222. };
  3223. /**
  3224. * Returns a new Vector3 located for "amount" on the CatmullRom interpolation spline defined by the vectors "value1", "value2", "value3", "value4"
  3225. * @param value1 defines the first control point
  3226. * @param value2 defines the second control point
  3227. * @param value3 defines the third control point
  3228. * @param value4 defines the fourth control point
  3229. * @param amount defines the amount on the spline to use
  3230. * @returns the new Vector3
  3231. */
  3232. Vector3.CatmullRom = function (value1, value2, value3, value4, amount) {
  3233. var squared = amount * amount;
  3234. var cubed = amount * squared;
  3235. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) +
  3236. (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) +
  3237. ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  3238. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) +
  3239. (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) +
  3240. ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  3241. var z = 0.5 * ((((2.0 * value2.z) + ((-value1.z + value3.z) * amount)) +
  3242. (((((2.0 * value1.z) - (5.0 * value2.z)) + (4.0 * value3.z)) - value4.z) * squared)) +
  3243. ((((-value1.z + (3.0 * value2.z)) - (3.0 * value3.z)) + value4.z) * cubed));
  3244. return new Vector3(x, y, z);
  3245. };
  3246. /**
  3247. * Returns a new Vector3 set with the coordinates of "value", if the vector "value" is in the cube defined by the vectors "min" and "max"
  3248. * If a coordinate value of "value" is lower than one of the "min" coordinate, then this "value" coordinate is set with the "min" one
  3249. * If a coordinate value of "value" is greater than one of the "max" coordinate, then this "value" coordinate is set with the "max" one
  3250. * @param value defines the current value
  3251. * @param min defines the lower range value
  3252. * @param max defines the upper range value
  3253. * @returns the new Vector3
  3254. */
  3255. Vector3.Clamp = function (value, min, max) {
  3256. var x = value.x;
  3257. x = (x > max.x) ? max.x : x;
  3258. x = (x < min.x) ? min.x : x;
  3259. var y = value.y;
  3260. y = (y > max.y) ? max.y : y;
  3261. y = (y < min.y) ? min.y : y;
  3262. var z = value.z;
  3263. z = (z > max.z) ? max.z : z;
  3264. z = (z < min.z) ? min.z : z;
  3265. return new Vector3(x, y, z);
  3266. };
  3267. /**
  3268. * Returns a new Vector3 located for "amount" (float) on the Hermite interpolation spline defined by the vectors "value1", "tangent1", "value2", "tangent2"
  3269. * @param value1 defines the first control point
  3270. * @param tangent1 defines the first tangent vector
  3271. * @param value2 defines the second control point
  3272. * @param tangent2 defines the second tangent vector
  3273. * @param amount defines the amount on the interpolation spline (between 0 and 1)
  3274. * @returns the new Vector3
  3275. */
  3276. Vector3.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  3277. var squared = amount * amount;
  3278. var cubed = amount * squared;
  3279. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  3280. var part2 = (-2.0 * cubed) + (3.0 * squared);
  3281. var part3 = (cubed - (2.0 * squared)) + amount;
  3282. var part4 = cubed - squared;
  3283. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  3284. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  3285. var z = (((value1.z * part1) + (value2.z * part2)) + (tangent1.z * part3)) + (tangent2.z * part4);
  3286. return new Vector3(x, y, z);
  3287. };
  3288. /**
  3289. * Returns a new Vector3 located for "amount" (float) on the linear interpolation between the vectors "start" and "end"
  3290. * @param start defines the start value
  3291. * @param end defines the end value
  3292. * @param amount max defines amount between both (between 0 and 1)
  3293. * @returns the new Vector3
  3294. */
  3295. Vector3.Lerp = function (start, end, amount) {
  3296. var result = new Vector3(0, 0, 0);
  3297. Vector3.LerpToRef(start, end, amount, result);
  3298. return result;
  3299. };
  3300. /**
  3301. * Sets the passed vector "result" with the result of the linear interpolation from the vector "start" for "amount" to the vector "end"
  3302. * @param start defines the start value
  3303. * @param end defines the end value
  3304. * @param amount max defines amount between both (between 0 and 1)
  3305. * @param result defines the Vector3 where to store the result
  3306. */
  3307. Vector3.LerpToRef = function (start, end, amount, result) {
  3308. result.x = start.x + ((end.x - start.x) * amount);
  3309. result.y = start.y + ((end.y - start.y) * amount);
  3310. result.z = start.z + ((end.z - start.z) * amount);
  3311. };
  3312. /**
  3313. * Returns the dot product (float) between the vectors "left" and "right"
  3314. * @param left defines the left operand
  3315. * @param right defines the right operand
  3316. * @returns the dot product
  3317. */
  3318. Vector3.Dot = function (left, right) {
  3319. return (left.x * right.x + left.y * right.y + left.z * right.z);
  3320. };
  3321. /**
  3322. * Returns a new Vector3 as the cross product of the vectors "left" and "right"
  3323. * The cross product is then orthogonal to both "left" and "right"
  3324. * @param left defines the left operand
  3325. * @param right defines the right operand
  3326. * @returns the cross product
  3327. */
  3328. Vector3.Cross = function (left, right) {
  3329. var result = Vector3.Zero();
  3330. Vector3.CrossToRef(left, right, result);
  3331. return result;
  3332. };
  3333. /**
  3334. * Sets the passed vector "result" with the cross product of "left" and "right"
  3335. * The cross product is then orthogonal to both "left" and "right"
  3336. * @param left defines the left operand
  3337. * @param right defines the right operand
  3338. * @param result defines the Vector3 where to store the result
  3339. */
  3340. Vector3.CrossToRef = function (left, right, result) {
  3341. MathTmp.Vector3[0].x = left.y * right.z - left.z * right.y;
  3342. MathTmp.Vector3[0].y = left.z * right.x - left.x * right.z;
  3343. MathTmp.Vector3[0].z = left.x * right.y - left.y * right.x;
  3344. result.copyFrom(MathTmp.Vector3[0]);
  3345. };
  3346. /**
  3347. * Returns a new Vector3 as the normalization of the passed vector
  3348. * @param vector defines the Vector3 to normalize
  3349. * @returns the new Vector3
  3350. */
  3351. Vector3.Normalize = function (vector) {
  3352. var result = Vector3.Zero();
  3353. Vector3.NormalizeToRef(vector, result);
  3354. return result;
  3355. };
  3356. /**
  3357. * Sets the passed vector "result" with the normalization of the passed first vector
  3358. * @param vector defines the Vector3 to normalize
  3359. * @param result defines the Vector3 where to store the result
  3360. */
  3361. Vector3.NormalizeToRef = function (vector, result) {
  3362. result.copyFrom(vector);
  3363. result.normalize();
  3364. };
  3365. /**
  3366. * Project a Vector3 onto screen space
  3367. * @param vector defines the Vector3 to project
  3368. * @param world defines the world matrix to use
  3369. * @param transform defines the transform (view x projection) matrix to use
  3370. * @param viewport defines the screen viewport to use
  3371. * @returns the new Vector3
  3372. */
  3373. Vector3.Project = function (vector, world, transform, viewport) {
  3374. var cw = viewport.width;
  3375. var ch = viewport.height;
  3376. var cx = viewport.x;
  3377. var cy = viewport.y;
  3378. var viewportMatrix = Vector3._viewportMatrixCache ? Vector3._viewportMatrixCache : (Vector3._viewportMatrixCache = new Matrix());
  3379. Matrix.FromValuesToRef(cw / 2.0, 0, 0, 0, 0, -ch / 2.0, 0, 0, 0, 0, 0.5, 0, cx + cw / 2.0, ch / 2.0 + cy, 0.5, 1, viewportMatrix);
  3380. var matrix = MathTmp.Matrix[0];
  3381. world.multiplyToRef(transform, matrix);
  3382. matrix.multiplyToRef(viewportMatrix, matrix);
  3383. return Vector3.TransformCoordinates(vector, matrix);
  3384. };
  3385. /**
  3386. * Unproject from screen space to object space
  3387. * @param source defines the screen space Vector3 to use
  3388. * @param viewportWidth defines the current width of the viewport
  3389. * @param viewportHeight defines the current height of the viewport
  3390. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  3391. * @param transform defines the transform (view x projection) matrix to use
  3392. * @returns the new Vector3
  3393. */
  3394. Vector3.UnprojectFromTransform = function (source, viewportWidth, viewportHeight, world, transform) {
  3395. var matrix = MathTmp.Matrix[0];
  3396. world.multiplyToRef(transform, matrix);
  3397. matrix.invert();
  3398. source.x = source.x / viewportWidth * 2 - 1;
  3399. source.y = -(source.y / viewportHeight * 2 - 1);
  3400. var vector = Vector3.TransformCoordinates(source, matrix);
  3401. var num = source.x * matrix.m[3] + source.y * matrix.m[7] + source.z * matrix.m[11] + matrix.m[15];
  3402. if (BABYLON.Scalar.WithinEpsilon(num, 1.0)) {
  3403. vector = vector.scale(1.0 / num);
  3404. }
  3405. return vector;
  3406. };
  3407. /**
  3408. * Unproject from screen space to object space
  3409. * @param source defines the screen space Vector3 to use
  3410. * @param viewportWidth defines the current width of the viewport
  3411. * @param viewportHeight defines the current height of the viewport
  3412. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  3413. * @param view defines the view matrix to use
  3414. * @param projection defines the projection matrix to use
  3415. * @returns the new Vector3
  3416. */
  3417. Vector3.Unproject = function (source, viewportWidth, viewportHeight, world, view, projection) {
  3418. var result = Vector3.Zero();
  3419. Vector3.UnprojectToRef(source, viewportWidth, viewportHeight, world, view, projection, result);
  3420. return result;
  3421. };
  3422. /**
  3423. * Unproject from screen space to object space
  3424. * @param source defines the screen space Vector3 to use
  3425. * @param viewportWidth defines the current width of the viewport
  3426. * @param viewportHeight defines the current height of the viewport
  3427. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  3428. * @param view defines the view matrix to use
  3429. * @param projection defines the projection matrix to use
  3430. * @param result defines the Vector3 where to store the result
  3431. */
  3432. Vector3.UnprojectToRef = function (source, viewportWidth, viewportHeight, world, view, projection, result) {
  3433. Vector3.UnprojectFloatsToRef(source.x, source.y, source.z, viewportWidth, viewportHeight, world, view, projection, result);
  3434. };
  3435. /**
  3436. * Unproject from screen space to object space
  3437. * @param sourceX defines the screen space x coordinate to use
  3438. * @param sourceY defines the screen space y coordinate to use
  3439. * @param sourceZ defines the screen space z coordinate to use
  3440. * @param viewportWidth defines the current width of the viewport
  3441. * @param viewportHeight defines the current height of the viewport
  3442. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  3443. * @param view defines the view matrix to use
  3444. * @param projection defines the projection matrix to use
  3445. * @param result defines the Vector3 where to store the result
  3446. */
  3447. Vector3.UnprojectFloatsToRef = function (sourceX, sourceY, sourceZ, viewportWidth, viewportHeight, world, view, projection, result) {
  3448. var matrix = MathTmp.Matrix[0];
  3449. world.multiplyToRef(view, matrix);
  3450. matrix.multiplyToRef(projection, matrix);
  3451. matrix.invert();
  3452. var screenSource = MathTmp.Vector3[0];
  3453. screenSource.x = sourceX / viewportWidth * 2 - 1;
  3454. screenSource.y = -(sourceY / viewportHeight * 2 - 1);
  3455. screenSource.z = 2 * sourceZ - 1.0;
  3456. Vector3.TransformCoordinatesToRef(screenSource, matrix, result);
  3457. var num = screenSource.x * matrix.m[3] + screenSource.y * matrix.m[7] + screenSource.z * matrix.m[11] + matrix.m[15];
  3458. if (BABYLON.Scalar.WithinEpsilon(num, 1.0)) {
  3459. result.scaleInPlace(1.0 / num);
  3460. }
  3461. };
  3462. /**
  3463. * Gets the minimal coordinate values between two Vector3
  3464. * @param left defines the first operand
  3465. * @param right defines the second operand
  3466. * @returns the new Vector3
  3467. */
  3468. Vector3.Minimize = function (left, right) {
  3469. var min = left.clone();
  3470. min.minimizeInPlace(right);
  3471. return min;
  3472. };
  3473. /**
  3474. * Gets the maximal coordinate values between two Vector3
  3475. * @param left defines the first operand
  3476. * @param right defines the second operand
  3477. * @returns the new Vector3
  3478. */
  3479. Vector3.Maximize = function (left, right) {
  3480. var max = left.clone();
  3481. max.maximizeInPlace(right);
  3482. return max;
  3483. };
  3484. /**
  3485. * Returns the distance between the vectors "value1" and "value2"
  3486. * @param value1 defines the first operand
  3487. * @param value2 defines the second operand
  3488. * @returns the distance
  3489. */
  3490. Vector3.Distance = function (value1, value2) {
  3491. return Math.sqrt(Vector3.DistanceSquared(value1, value2));
  3492. };
  3493. /**
  3494. * Returns the squared distance between the vectors "value1" and "value2"
  3495. * @param value1 defines the first operand
  3496. * @param value2 defines the second operand
  3497. * @returns the squared distance
  3498. */
  3499. Vector3.DistanceSquared = function (value1, value2) {
  3500. var x = value1.x - value2.x;
  3501. var y = value1.y - value2.y;
  3502. var z = value1.z - value2.z;
  3503. return (x * x) + (y * y) + (z * z);
  3504. };
  3505. /**
  3506. * Returns a new Vector3 located at the center between "value1" and "value2"
  3507. * @param value1 defines the first operand
  3508. * @param value2 defines the second operand
  3509. * @returns the new Vector3
  3510. */
  3511. Vector3.Center = function (value1, value2) {
  3512. var center = value1.add(value2);
  3513. center.scaleInPlace(0.5);
  3514. return center;
  3515. };
  3516. /**
  3517. * Given three orthogonal normalized left-handed oriented Vector3 axis in space (target system),
  3518. * RotationFromAxis() returns the rotation Euler angles (ex : rotation.x, rotation.y, rotation.z) to apply
  3519. * to something in order to rotate it from its local system to the given target system
  3520. * Note: axis1, axis2 and axis3 are normalized during this operation
  3521. * @param axis1 defines the first axis
  3522. * @param axis2 defines the second axis
  3523. * @param axis3 defines the third axis
  3524. * @returns a new Vector3
  3525. */
  3526. Vector3.RotationFromAxis = function (axis1, axis2, axis3) {
  3527. var rotation = Vector3.Zero();
  3528. Vector3.RotationFromAxisToRef(axis1, axis2, axis3, rotation);
  3529. return rotation;
  3530. };
  3531. /**
  3532. * The same than RotationFromAxis but updates the passed ref Vector3 parameter instead of returning a new Vector3
  3533. * @param axis1 defines the first axis
  3534. * @param axis2 defines the second axis
  3535. * @param axis3 defines the third axis
  3536. * @param ref defines the Vector3 where to store the result
  3537. */
  3538. Vector3.RotationFromAxisToRef = function (axis1, axis2, axis3, ref) {
  3539. var quat = MathTmp.Quaternion[0];
  3540. Quaternion.RotationQuaternionFromAxisToRef(axis1, axis2, axis3, quat);
  3541. quat.toEulerAnglesToRef(ref);
  3542. };
  3543. return Vector3;
  3544. }());
  3545. BABYLON.Vector3 = Vector3;
  3546. //Vector4 class created for EulerAngle class conversion to Quaternion
  3547. var Vector4 = /** @class */ (function () {
  3548. /**
  3549. * Creates a Vector4 object from the passed floats.
  3550. */
  3551. function Vector4(x, y, z, w) {
  3552. this.x = x;
  3553. this.y = y;
  3554. this.z = z;
  3555. this.w = w;
  3556. }
  3557. /**
  3558. * Returns the string with the Vector4 coordinates.
  3559. */
  3560. Vector4.prototype.toString = function () {
  3561. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
  3562. };
  3563. /**
  3564. * Returns the string "Vector4".
  3565. */
  3566. Vector4.prototype.getClassName = function () {
  3567. return "Vector4";
  3568. };
  3569. /**
  3570. * Returns the Vector4 hash code.
  3571. */
  3572. Vector4.prototype.getHashCode = function () {
  3573. var hash = this.x || 0;
  3574. hash = (hash * 397) ^ (this.y || 0);
  3575. hash = (hash * 397) ^ (this.z || 0);
  3576. hash = (hash * 397) ^ (this.w || 0);
  3577. return hash;
  3578. };
  3579. // Operators
  3580. /**
  3581. * Returns a new array populated with 4 elements : the Vector4 coordinates.
  3582. */
  3583. Vector4.prototype.asArray = function () {
  3584. var result = new Array();
  3585. this.toArray(result, 0);
  3586. return result;
  3587. };
  3588. /**
  3589. * Populates the passed array from the passed index with the Vector4 coordinates.
  3590. * Returns the Vector4.
  3591. */
  3592. Vector4.prototype.toArray = function (array, index) {
  3593. if (index === undefined) {
  3594. index = 0;
  3595. }
  3596. array[index] = this.x;
  3597. array[index + 1] = this.y;
  3598. array[index + 2] = this.z;
  3599. array[index + 3] = this.w;
  3600. return this;
  3601. };
  3602. /**
  3603. * Adds the passed vector to the current Vector4.
  3604. * Returns the updated Vector4.
  3605. */
  3606. Vector4.prototype.addInPlace = function (otherVector) {
  3607. this.x += otherVector.x;
  3608. this.y += otherVector.y;
  3609. this.z += otherVector.z;
  3610. this.w += otherVector.w;
  3611. return this;
  3612. };
  3613. /**
  3614. * Returns a new Vector4 as the result of the addition of the current Vector4 and the passed one.
  3615. */
  3616. Vector4.prototype.add = function (otherVector) {
  3617. return new Vector4(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z, this.w + otherVector.w);
  3618. };
  3619. /**
  3620. * Updates the passed vector "result" with the result of the addition of the current Vector4 and the passed one.
  3621. * Returns the current Vector4.
  3622. */
  3623. Vector4.prototype.addToRef = function (otherVector, result) {
  3624. result.x = this.x + otherVector.x;
  3625. result.y = this.y + otherVector.y;
  3626. result.z = this.z + otherVector.z;
  3627. result.w = this.w + otherVector.w;
  3628. return this;
  3629. };
  3630. /**
  3631. * Subtract in place the passed vector from the current Vector4.
  3632. * Returns the updated Vector4.
  3633. */
  3634. Vector4.prototype.subtractInPlace = function (otherVector) {
  3635. this.x -= otherVector.x;
  3636. this.y -= otherVector.y;
  3637. this.z -= otherVector.z;
  3638. this.w -= otherVector.w;
  3639. return this;
  3640. };
  3641. /**
  3642. * Returns a new Vector4 with the result of the subtraction of the passed vector from the current Vector4.
  3643. */
  3644. Vector4.prototype.subtract = function (otherVector) {
  3645. return new Vector4(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z, this.w - otherVector.w);
  3646. };
  3647. /**
  3648. * Sets the passed vector "result" with the result of the subtraction of the passed vector from the current Vector4.
  3649. * Returns the current Vector4.
  3650. */
  3651. Vector4.prototype.subtractToRef = function (otherVector, result) {
  3652. result.x = this.x - otherVector.x;
  3653. result.y = this.y - otherVector.y;
  3654. result.z = this.z - otherVector.z;
  3655. result.w = this.w - otherVector.w;
  3656. return this;
  3657. };
  3658. /**
  3659. * Returns a new Vector4 set with the result of the subtraction of the passed floats from the current Vector4 coordinates.
  3660. */
  3661. Vector4.prototype.subtractFromFloats = function (x, y, z, w) {
  3662. return new Vector4(this.x - x, this.y - y, this.z - z, this.w - w);
  3663. };
  3664. /**
  3665. * Sets the passed vector "result" set with the result of the subtraction of the passed floats from the current Vector4 coordinates.
  3666. * Returns the current Vector4.
  3667. */
  3668. Vector4.prototype.subtractFromFloatsToRef = function (x, y, z, w, result) {
  3669. result.x = this.x - x;
  3670. result.y = this.y - y;
  3671. result.z = this.z - z;
  3672. result.w = this.w - w;
  3673. return this;
  3674. };
  3675. /**
  3676. * Returns a new Vector4 set with the current Vector4 negated coordinates.
  3677. */
  3678. Vector4.prototype.negate = function () {
  3679. return new Vector4(-this.x, -this.y, -this.z, -this.w);
  3680. };
  3681. /**
  3682. * Multiplies the current Vector4 coordinates by scale (float).
  3683. * Returns the updated Vector4.
  3684. */
  3685. Vector4.prototype.scaleInPlace = function (scale) {
  3686. this.x *= scale;
  3687. this.y *= scale;
  3688. this.z *= scale;
  3689. this.w *= scale;
  3690. return this;
  3691. };
  3692. /**
  3693. * Returns a new Vector4 set with the current Vector4 coordinates multiplied by scale (float).
  3694. */
  3695. Vector4.prototype.scale = function (scale) {
  3696. return new Vector4(this.x * scale, this.y * scale, this.z * scale, this.w * scale);
  3697. };
  3698. /**
  3699. * Sets the passed vector "result" with the current Vector4 coordinates multiplied by scale (float).
  3700. * Returns the current Vector4.
  3701. */
  3702. Vector4.prototype.scaleToRef = function (scale, result) {
  3703. result.x = this.x * scale;
  3704. result.y = this.y * scale;
  3705. result.z = this.z * scale;
  3706. result.w = this.w * scale;
  3707. return this;
  3708. };
  3709. /**
  3710. * Boolean : True if the current Vector4 coordinates are stricly equal to the passed ones.
  3711. */
  3712. Vector4.prototype.equals = function (otherVector) {
  3713. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z && this.w === otherVector.w;
  3714. };
  3715. /**
  3716. * Boolean : True if the current Vector4 coordinates are each beneath the distance "epsilon" from the passed vector ones.
  3717. */
  3718. Vector4.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  3719. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  3720. return otherVector
  3721. && BABYLON.Scalar.WithinEpsilon(this.x, otherVector.x, epsilon)
  3722. && BABYLON.Scalar.WithinEpsilon(this.y, otherVector.y, epsilon)
  3723. && BABYLON.Scalar.WithinEpsilon(this.z, otherVector.z, epsilon)
  3724. && BABYLON.Scalar.WithinEpsilon(this.w, otherVector.w, epsilon);
  3725. };
  3726. /**
  3727. * Boolean : True if the passed floats are strictly equal to the current Vector4 coordinates.
  3728. */
  3729. Vector4.prototype.equalsToFloats = function (x, y, z, w) {
  3730. return this.x === x && this.y === y && this.z === z && this.w === w;
  3731. };
  3732. /**
  3733. * Multiplies in place the current Vector4 by the passed one.
  3734. * Returns the updated Vector4.
  3735. */
  3736. Vector4.prototype.multiplyInPlace = function (otherVector) {
  3737. this.x *= otherVector.x;
  3738. this.y *= otherVector.y;
  3739. this.z *= otherVector.z;
  3740. this.w *= otherVector.w;
  3741. return this;
  3742. };
  3743. /**
  3744. * Returns a new Vector4 set with the multiplication result of the current Vector4 and the passed one.
  3745. */
  3746. Vector4.prototype.multiply = function (otherVector) {
  3747. return new Vector4(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z, this.w * otherVector.w);
  3748. };
  3749. /**
  3750. * Updates the passed vector "result" with the multiplication result of the current Vector4 and the passed one.
  3751. * Returns the current Vector4.
  3752. */
  3753. Vector4.prototype.multiplyToRef = function (otherVector, result) {
  3754. result.x = this.x * otherVector.x;
  3755. result.y = this.y * otherVector.y;
  3756. result.z = this.z * otherVector.z;
  3757. result.w = this.w * otherVector.w;
  3758. return this;
  3759. };
  3760. /**
  3761. * Returns a new Vector4 set with the multiplication result of the passed floats and the current Vector4 coordinates.
  3762. */
  3763. Vector4.prototype.multiplyByFloats = function (x, y, z, w) {
  3764. return new Vector4(this.x * x, this.y * y, this.z * z, this.w * w);
  3765. };
  3766. /**
  3767. * Returns a new Vector4 set with the division result of the current Vector4 by the passed one.
  3768. */
  3769. Vector4.prototype.divide = function (otherVector) {
  3770. return new Vector4(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z, this.w / otherVector.w);
  3771. };
  3772. /**
  3773. * Updates the passed vector "result" with the division result of the current Vector4 by the passed one.
  3774. * Returns the current Vector4.
  3775. */
  3776. Vector4.prototype.divideToRef = function (otherVector, result) {
  3777. result.x = this.x / otherVector.x;
  3778. result.y = this.y / otherVector.y;
  3779. result.z = this.z / otherVector.z;
  3780. result.w = this.w / otherVector.w;
  3781. return this;
  3782. };
  3783. /**
  3784. * Divides the current Vector3 coordinates by the passed ones.
  3785. * @returns the updated Vector3.
  3786. */
  3787. Vector4.prototype.divideInPlace = function (otherVector) {
  3788. return this.divideToRef(otherVector, this);
  3789. };
  3790. /**
  3791. * Updates the Vector4 coordinates with the minimum values between its own and the passed vector ones
  3792. * @param other defines the second operand
  3793. * @returns the current updated Vector4
  3794. */
  3795. Vector4.prototype.minimizeInPlace = function (other) {
  3796. if (other.x < this.x)
  3797. this.x = other.x;
  3798. if (other.y < this.y)
  3799. this.y = other.y;
  3800. if (other.z < this.z)
  3801. this.z = other.z;
  3802. if (other.w < this.w)
  3803. this.w = other.w;
  3804. return this;
  3805. };
  3806. /**
  3807. * Updates the Vector4 coordinates with the maximum values between its own and the passed vector ones
  3808. * @param other defines the second operand
  3809. * @returns the current updated Vector4
  3810. */
  3811. Vector4.prototype.maximizeInPlace = function (other) {
  3812. if (other.x > this.x)
  3813. this.x = other.x;
  3814. if (other.y > this.y)
  3815. this.y = other.y;
  3816. if (other.z > this.z)
  3817. this.z = other.z;
  3818. if (other.w > this.w)
  3819. this.w = other.w;
  3820. return this;
  3821. };
  3822. // Properties
  3823. /**
  3824. * Returns the Vector4 length (float).
  3825. */
  3826. Vector4.prototype.length = function () {
  3827. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  3828. };
  3829. /**
  3830. * Returns the Vector4 squared length (float).
  3831. */
  3832. Vector4.prototype.lengthSquared = function () {
  3833. return (this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  3834. };
  3835. // Methods
  3836. /**
  3837. * Normalizes in place the Vector4.
  3838. * Returns the updated Vector4.
  3839. */
  3840. Vector4.prototype.normalize = function () {
  3841. var len = this.length();
  3842. if (len === 0)
  3843. return this;
  3844. var num = 1.0 / len;
  3845. this.x *= num;
  3846. this.y *= num;
  3847. this.z *= num;
  3848. this.w *= num;
  3849. return this;
  3850. };
  3851. /**
  3852. * Returns a new Vector3 from the Vector4 (x, y, z) coordinates.
  3853. */
  3854. Vector4.prototype.toVector3 = function () {
  3855. return new Vector3(this.x, this.y, this.z);
  3856. };
  3857. /**
  3858. * Returns a new Vector4 copied from the current one.
  3859. */
  3860. Vector4.prototype.clone = function () {
  3861. return new Vector4(this.x, this.y, this.z, this.w);
  3862. };
  3863. /**
  3864. * Updates the current Vector4 with the passed one coordinates.
  3865. * Returns the updated Vector4.
  3866. */
  3867. Vector4.prototype.copyFrom = function (source) {
  3868. this.x = source.x;
  3869. this.y = source.y;
  3870. this.z = source.z;
  3871. this.w = source.w;
  3872. return this;
  3873. };
  3874. /**
  3875. * Updates the current Vector4 coordinates with the passed floats.
  3876. * Returns the updated Vector4.
  3877. */
  3878. Vector4.prototype.copyFromFloats = function (x, y, z, w) {
  3879. this.x = x;
  3880. this.y = y;
  3881. this.z = z;
  3882. this.w = w;
  3883. return this;
  3884. };
  3885. /**
  3886. * Updates the current Vector4 coordinates with the passed floats.
  3887. * Returns the updated Vector4.
  3888. */
  3889. Vector4.prototype.set = function (x, y, z, w) {
  3890. return this.copyFromFloats(x, y, z, w);
  3891. };
  3892. // Statics
  3893. /**
  3894. * Returns a new Vector4 set from the starting index of the passed array.
  3895. */
  3896. Vector4.FromArray = function (array, offset) {
  3897. if (!offset) {
  3898. offset = 0;
  3899. }
  3900. return new Vector4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  3901. };
  3902. /**
  3903. * Updates the passed vector "result" from the starting index of the passed array.
  3904. */
  3905. Vector4.FromArrayToRef = function (array, offset, result) {
  3906. result.x = array[offset];
  3907. result.y = array[offset + 1];
  3908. result.z = array[offset + 2];
  3909. result.w = array[offset + 3];
  3910. };
  3911. /**
  3912. * Updates the passed vector "result" from the starting index of the passed Float32Array.
  3913. */
  3914. Vector4.FromFloatArrayToRef = function (array, offset, result) {
  3915. Vector4.FromArrayToRef(array, offset, result);
  3916. };
  3917. /**
  3918. * Updates the passed vector "result" coordinates from the passed floats.
  3919. */
  3920. Vector4.FromFloatsToRef = function (x, y, z, w, result) {
  3921. result.x = x;
  3922. result.y = y;
  3923. result.z = z;
  3924. result.w = w;
  3925. };
  3926. /**
  3927. * Returns a new Vector4 set to (0.0, 0.0, 0.0, 0.0)
  3928. */
  3929. Vector4.Zero = function () {
  3930. return new Vector4(0.0, 0.0, 0.0, 0.0);
  3931. };
  3932. /**
  3933. * Returns a new Vector4 set to (1.0, 1.0, 1.0, 1.0)
  3934. */
  3935. Vector4.One = function () {
  3936. return new Vector4(1.0, 1.0, 1.0, 1.0);
  3937. };
  3938. /**
  3939. * Returns a new normalized Vector4 from the passed one.
  3940. */
  3941. Vector4.Normalize = function (vector) {
  3942. var result = Vector4.Zero();
  3943. Vector4.NormalizeToRef(vector, result);
  3944. return result;
  3945. };
  3946. /**
  3947. * Updates the passed vector "result" from the normalization of the passed one.
  3948. */
  3949. Vector4.NormalizeToRef = function (vector, result) {
  3950. result.copyFrom(vector);
  3951. result.normalize();
  3952. };
  3953. Vector4.Minimize = function (left, right) {
  3954. var min = left.clone();
  3955. min.minimizeInPlace(right);
  3956. return min;
  3957. };
  3958. Vector4.Maximize = function (left, right) {
  3959. var max = left.clone();
  3960. max.maximizeInPlace(right);
  3961. return max;
  3962. };
  3963. /**
  3964. * Returns the distance (float) between the vectors "value1" and "value2".
  3965. */
  3966. Vector4.Distance = function (value1, value2) {
  3967. return Math.sqrt(Vector4.DistanceSquared(value1, value2));
  3968. };
  3969. /**
  3970. * Returns the squared distance (float) between the vectors "value1" and "value2".
  3971. */
  3972. Vector4.DistanceSquared = function (value1, value2) {
  3973. var x = value1.x - value2.x;
  3974. var y = value1.y - value2.y;
  3975. var z = value1.z - value2.z;
  3976. var w = value1.w - value2.w;
  3977. return (x * x) + (y * y) + (z * z) + (w * w);
  3978. };
  3979. /**
  3980. * Returns a new Vector4 located at the center between the vectors "value1" and "value2".
  3981. */
  3982. Vector4.Center = function (value1, value2) {
  3983. var center = value1.add(value2);
  3984. center.scaleInPlace(0.5);
  3985. return center;
  3986. };
  3987. /**
  3988. * Returns a new Vector4 set with the result of the normal transformation by the passed matrix of the passed vector.
  3989. * This methods computes transformed normalized direction vectors only.
  3990. */
  3991. Vector4.TransformNormal = function (vector, transformation) {
  3992. var result = Vector4.Zero();
  3993. Vector4.TransformNormalToRef(vector, transformation, result);
  3994. return result;
  3995. };
  3996. /**
  3997. * Sets the passed vector "result" with the result of the normal transformation by the passed matrix of the passed vector.
  3998. * This methods computes transformed normalized direction vectors only.
  3999. */
  4000. Vector4.TransformNormalToRef = function (vector, transformation, result) {
  4001. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]);
  4002. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]);
  4003. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]);
  4004. result.x = x;
  4005. result.y = y;
  4006. result.z = z;
  4007. result.w = vector.w;
  4008. };
  4009. /**
  4010. * Sets the passed vector "result" with the result of the normal transformation by the passed matrix of the passed floats (x, y, z, w).
  4011. * This methods computes transformed normalized direction vectors only.
  4012. */
  4013. Vector4.TransformNormalFromFloatsToRef = function (x, y, z, w, transformation, result) {
  4014. result.x = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]);
  4015. result.y = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]);
  4016. result.z = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]);
  4017. result.w = w;
  4018. };
  4019. return Vector4;
  4020. }());
  4021. BABYLON.Vector4 = Vector4;
  4022. var Size = /** @class */ (function () {
  4023. /**
  4024. * Creates a Size object from the passed width and height (floats).
  4025. */
  4026. function Size(width, height) {
  4027. this.width = width;
  4028. this.height = height;
  4029. }
  4030. // Returns a string with the Size width and height.
  4031. Size.prototype.toString = function () {
  4032. return "{W: " + this.width + ", H: " + this.height + "}";
  4033. };
  4034. /**
  4035. * Returns the string "Size"
  4036. */
  4037. Size.prototype.getClassName = function () {
  4038. return "Size";
  4039. };
  4040. /**
  4041. * Returns the Size hash code.
  4042. */
  4043. Size.prototype.getHashCode = function () {
  4044. var hash = this.width || 0;
  4045. hash = (hash * 397) ^ (this.height || 0);
  4046. return hash;
  4047. };
  4048. /**
  4049. * Updates the current size from the passed one.
  4050. * Returns the updated Size.
  4051. */
  4052. Size.prototype.copyFrom = function (src) {
  4053. this.width = src.width;
  4054. this.height = src.height;
  4055. };
  4056. /**
  4057. * Updates in place the current Size from the passed floats.
  4058. * Returns the updated Size.
  4059. */
  4060. Size.prototype.copyFromFloats = function (width, height) {
  4061. this.width = width;
  4062. this.height = height;
  4063. return this;
  4064. };
  4065. /**
  4066. * Updates in place the current Size from the passed floats.
  4067. * Returns the updated Size.
  4068. */
  4069. Size.prototype.set = function (width, height) {
  4070. return this.copyFromFloats(width, height);
  4071. };
  4072. /**
  4073. * Returns a new Size set with the multiplication result of the current Size and the passed floats.
  4074. */
  4075. Size.prototype.multiplyByFloats = function (w, h) {
  4076. return new Size(this.width * w, this.height * h);
  4077. };
  4078. /**
  4079. * Returns a new Size copied from the passed one.
  4080. */
  4081. Size.prototype.clone = function () {
  4082. return new Size(this.width, this.height);
  4083. };
  4084. /**
  4085. * Boolean : True if the current Size and the passed one width and height are strictly equal.
  4086. */
  4087. Size.prototype.equals = function (other) {
  4088. if (!other) {
  4089. return false;
  4090. }
  4091. return (this.width === other.width) && (this.height === other.height);
  4092. };
  4093. Object.defineProperty(Size.prototype, "surface", {
  4094. /**
  4095. * Returns the surface of the Size : width * height (float).
  4096. */
  4097. get: function () {
  4098. return this.width * this.height;
  4099. },
  4100. enumerable: true,
  4101. configurable: true
  4102. });
  4103. /**
  4104. * Returns a new Size set to (0.0, 0.0)
  4105. */
  4106. Size.Zero = function () {
  4107. return new Size(0.0, 0.0);
  4108. };
  4109. /**
  4110. * Returns a new Size set as the addition result of the current Size and the passed one.
  4111. */
  4112. Size.prototype.add = function (otherSize) {
  4113. var r = new Size(this.width + otherSize.width, this.height + otherSize.height);
  4114. return r;
  4115. };
  4116. /**
  4117. * Returns a new Size set as the subtraction result of the passed one from the current Size.
  4118. */
  4119. Size.prototype.subtract = function (otherSize) {
  4120. var r = new Size(this.width - otherSize.width, this.height - otherSize.height);
  4121. return r;
  4122. };
  4123. /**
  4124. * Returns a new Size set at the linear interpolation "amount" between "start" and "end".
  4125. */
  4126. Size.Lerp = function (start, end, amount) {
  4127. var w = start.width + ((end.width - start.width) * amount);
  4128. var h = start.height + ((end.height - start.height) * amount);
  4129. return new Size(w, h);
  4130. };
  4131. return Size;
  4132. }());
  4133. BABYLON.Size = Size;
  4134. var Quaternion = /** @class */ (function () {
  4135. /**
  4136. * Creates a new Quaternion from the passed floats.
  4137. */
  4138. function Quaternion(x, y, z, w) {
  4139. if (x === void 0) { x = 0.0; }
  4140. if (y === void 0) { y = 0.0; }
  4141. if (z === void 0) { z = 0.0; }
  4142. if (w === void 0) { w = 1.0; }
  4143. this.x = x;
  4144. this.y = y;
  4145. this.z = z;
  4146. this.w = w;
  4147. }
  4148. /**
  4149. * Returns a string with the Quaternion coordinates.
  4150. */
  4151. Quaternion.prototype.toString = function () {
  4152. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
  4153. };
  4154. /**
  4155. * Returns the string "Quaternion".
  4156. */
  4157. Quaternion.prototype.getClassName = function () {
  4158. return "Quaternion";
  4159. };
  4160. /**
  4161. * Returns the Quaternion hash code.
  4162. */
  4163. Quaternion.prototype.getHashCode = function () {
  4164. var hash = this.x || 0;
  4165. hash = (hash * 397) ^ (this.y || 0);
  4166. hash = (hash * 397) ^ (this.z || 0);
  4167. hash = (hash * 397) ^ (this.w || 0);
  4168. return hash;
  4169. };
  4170. /**
  4171. * Returns a new array populated with 4 elements : the Quaternion coordinates.
  4172. */
  4173. Quaternion.prototype.asArray = function () {
  4174. return [this.x, this.y, this.z, this.w];
  4175. };
  4176. /**
  4177. * Boolean : True if the current Quaterion and the passed one coordinates are strictly equal.
  4178. */
  4179. Quaternion.prototype.equals = function (otherQuaternion) {
  4180. return otherQuaternion && this.x === otherQuaternion.x && this.y === otherQuaternion.y && this.z === otherQuaternion.z && this.w === otherQuaternion.w;
  4181. };
  4182. /**
  4183. * Returns a new Quaternion copied from the current one.
  4184. */
  4185. Quaternion.prototype.clone = function () {
  4186. return new Quaternion(this.x, this.y, this.z, this.w);
  4187. };
  4188. /**
  4189. * Updates the current Quaternion from the passed one coordinates.
  4190. * Returns the updated Quaterion.
  4191. */
  4192. Quaternion.prototype.copyFrom = function (other) {
  4193. this.x = other.x;
  4194. this.y = other.y;
  4195. this.z = other.z;
  4196. this.w = other.w;
  4197. return this;
  4198. };
  4199. /**
  4200. * Updates the current Quaternion from the passed float coordinates.
  4201. * Returns the updated Quaterion.
  4202. */
  4203. Quaternion.prototype.copyFromFloats = function (x, y, z, w) {
  4204. this.x = x;
  4205. this.y = y;
  4206. this.z = z;
  4207. this.w = w;
  4208. return this;
  4209. };
  4210. /**
  4211. * Updates the current Quaternion from the passed float coordinates.
  4212. * Returns the updated Quaterion.
  4213. */
  4214. Quaternion.prototype.set = function (x, y, z, w) {
  4215. return this.copyFromFloats(x, y, z, w);
  4216. };
  4217. /**
  4218. * Returns a new Quaternion as the addition result of the passed one and the current Quaternion.
  4219. */
  4220. Quaternion.prototype.add = function (other) {
  4221. return new Quaternion(this.x + other.x, this.y + other.y, this.z + other.z, this.w + other.w);
  4222. };
  4223. /**
  4224. * Returns a new Quaternion as the subtraction result of the passed one from the current Quaternion.
  4225. */
  4226. Quaternion.prototype.subtract = function (other) {
  4227. return new Quaternion(this.x - other.x, this.y - other.y, this.z - other.z, this.w - other.w);
  4228. };
  4229. /**
  4230. * Returns a new Quaternion set by multiplying the current Quaterion coordinates by the float "scale".
  4231. */
  4232. Quaternion.prototype.scale = function (value) {
  4233. return new Quaternion(this.x * value, this.y * value, this.z * value, this.w * value);
  4234. };
  4235. /**
  4236. * Returns a new Quaternion set as the quaternion mulplication result of the current one with the passed one "q1".
  4237. */
  4238. Quaternion.prototype.multiply = function (q1) {
  4239. var result = new Quaternion(0, 0, 0, 1.0);
  4240. this.multiplyToRef(q1, result);
  4241. return result;
  4242. };
  4243. /**
  4244. * Sets the passed "result" as the quaternion mulplication result of the current one with the passed one "q1".
  4245. * Returns the current Quaternion.
  4246. */
  4247. Quaternion.prototype.multiplyToRef = function (q1, result) {
  4248. var x = this.x * q1.w + this.y * q1.z - this.z * q1.y + this.w * q1.x;
  4249. var y = -this.x * q1.z + this.y * q1.w + this.z * q1.x + this.w * q1.y;
  4250. var z = this.x * q1.y - this.y * q1.x + this.z * q1.w + this.w * q1.z;
  4251. var w = -this.x * q1.x - this.y * q1.y - this.z * q1.z + this.w * q1.w;
  4252. result.copyFromFloats(x, y, z, w);
  4253. return this;
  4254. };
  4255. /**
  4256. * Updates the current Quaternion with the quaternion mulplication result of itself with the passed one "q1".
  4257. * Returns the updated Quaternion.
  4258. */
  4259. Quaternion.prototype.multiplyInPlace = function (q1) {
  4260. this.multiplyToRef(q1, this);
  4261. return this;
  4262. };
  4263. /**
  4264. * Sets the passed "ref" with the conjugation of the current Quaternion.
  4265. * Returns the current Quaternion.
  4266. */
  4267. Quaternion.prototype.conjugateToRef = function (ref) {
  4268. ref.copyFromFloats(-this.x, -this.y, -this.z, this.w);
  4269. return this;
  4270. };
  4271. /**
  4272. * Conjugates in place the current Quaternion.
  4273. * Returns the updated Quaternion.
  4274. */
  4275. Quaternion.prototype.conjugateInPlace = function () {
  4276. this.x *= -1;
  4277. this.y *= -1;
  4278. this.z *= -1;
  4279. return this;
  4280. };
  4281. /**
  4282. * Returns a new Quaternion as the conjugate of the current Quaternion.
  4283. */
  4284. Quaternion.prototype.conjugate = function () {
  4285. var result = new Quaternion(-this.x, -this.y, -this.z, this.w);
  4286. return result;
  4287. };
  4288. /**
  4289. * Returns the Quaternion length (float).
  4290. */
  4291. Quaternion.prototype.length = function () {
  4292. return Math.sqrt((this.x * this.x) + (this.y * this.y) + (this.z * this.z) + (this.w * this.w));
  4293. };
  4294. /**
  4295. * Normalize in place the current Quaternion.
  4296. * Returns the updated Quaternion.
  4297. */
  4298. Quaternion.prototype.normalize = function () {
  4299. var length = 1.0 / this.length();
  4300. this.x *= length;
  4301. this.y *= length;
  4302. this.z *= length;
  4303. this.w *= length;
  4304. return this;
  4305. };
  4306. /**
  4307. * Returns a new Vector3 set with the Euler angles translated from the current Quaternion.
  4308. */
  4309. Quaternion.prototype.toEulerAngles = function (order) {
  4310. if (order === void 0) { order = "YZX"; }
  4311. var result = Vector3.Zero();
  4312. this.toEulerAnglesToRef(result, order);
  4313. return result;
  4314. };
  4315. /**
  4316. * Sets the passed vector3 "result" with the Euler angles translated from the current Quaternion.
  4317. * Returns the current Quaternion.
  4318. */
  4319. Quaternion.prototype.toEulerAnglesToRef = function (result, order) {
  4320. if (order === void 0) { order = "YZX"; }
  4321. var qz = this.z;
  4322. var qx = this.x;
  4323. var qy = this.y;
  4324. var qw = this.w;
  4325. var sqw = qw * qw;
  4326. var sqz = qz * qz;
  4327. var sqx = qx * qx;
  4328. var sqy = qy * qy;
  4329. var zAxisY = qy * qz - qx * qw;
  4330. var limit = .4999999;
  4331. if (zAxisY < -limit) {
  4332. result.y = 2 * Math.atan2(qy, qw);
  4333. result.x = Math.PI / 2;
  4334. result.z = 0;
  4335. }
  4336. else if (zAxisY > limit) {
  4337. result.y = 2 * Math.atan2(qy, qw);
  4338. result.x = -Math.PI / 2;
  4339. result.z = 0;
  4340. }
  4341. else {
  4342. result.z = Math.atan2(2.0 * (qx * qy + qz * qw), (-sqz - sqx + sqy + sqw));
  4343. result.x = Math.asin(-2.0 * (qz * qy - qx * qw));
  4344. result.y = Math.atan2(2.0 * (qz * qx + qy * qw), (sqz - sqx - sqy + sqw));
  4345. }
  4346. return this;
  4347. };
  4348. /**
  4349. * Updates the passed rotation matrix with the current Quaternion values.
  4350. * Returns the current Quaternion.
  4351. */
  4352. Quaternion.prototype.toRotationMatrix = function (result) {
  4353. var xx = this.x * this.x;
  4354. var yy = this.y * this.y;
  4355. var zz = this.z * this.z;
  4356. var xy = this.x * this.y;
  4357. var zw = this.z * this.w;
  4358. var zx = this.z * this.x;
  4359. var yw = this.y * this.w;
  4360. var yz = this.y * this.z;
  4361. var xw = this.x * this.w;
  4362. result.m[0] = 1.0 - (2.0 * (yy + zz));
  4363. result.m[1] = 2.0 * (xy + zw);
  4364. result.m[2] = 2.0 * (zx - yw);
  4365. result.m[3] = 0;
  4366. result.m[4] = 2.0 * (xy - zw);
  4367. result.m[5] = 1.0 - (2.0 * (zz + xx));
  4368. result.m[6] = 2.0 * (yz + xw);
  4369. result.m[7] = 0;
  4370. result.m[8] = 2.0 * (zx + yw);
  4371. result.m[9] = 2.0 * (yz - xw);
  4372. result.m[10] = 1.0 - (2.0 * (yy + xx));
  4373. result.m[11] = 0;
  4374. result.m[12] = 0;
  4375. result.m[13] = 0;
  4376. result.m[14] = 0;
  4377. result.m[15] = 1.0;
  4378. result._markAsUpdated();
  4379. return this;
  4380. };
  4381. /**
  4382. * Updates the current Quaternion from the passed rotation matrix values.
  4383. * Returns the updated Quaternion.
  4384. */
  4385. Quaternion.prototype.fromRotationMatrix = function (matrix) {
  4386. Quaternion.FromRotationMatrixToRef(matrix, this);
  4387. return this;
  4388. };
  4389. // Statics
  4390. /**
  4391. * Returns a new Quaternion set from the passed rotation matrix values.
  4392. */
  4393. Quaternion.FromRotationMatrix = function (matrix) {
  4394. var result = new Quaternion();
  4395. Quaternion.FromRotationMatrixToRef(matrix, result);
  4396. return result;
  4397. };
  4398. /**
  4399. * Updates the passed quaternion "result" with the passed rotation matrix values.
  4400. */
  4401. Quaternion.FromRotationMatrixToRef = function (matrix, result) {
  4402. var data = matrix.m;
  4403. var m11 = data[0], m12 = data[4], m13 = data[8];
  4404. var m21 = data[1], m22 = data[5], m23 = data[9];
  4405. var m31 = data[2], m32 = data[6], m33 = data[10];
  4406. var trace = m11 + m22 + m33;
  4407. var s;
  4408. if (trace > 0) {
  4409. s = 0.5 / Math.sqrt(trace + 1.0);
  4410. result.w = 0.25 / s;
  4411. result.x = (m32 - m23) * s;
  4412. result.y = (m13 - m31) * s;
  4413. result.z = (m21 - m12) * s;
  4414. }
  4415. else if (m11 > m22 && m11 > m33) {
  4416. s = 2.0 * Math.sqrt(1.0 + m11 - m22 - m33);
  4417. result.w = (m32 - m23) / s;
  4418. result.x = 0.25 * s;
  4419. result.y = (m12 + m21) / s;
  4420. result.z = (m13 + m31) / s;
  4421. }
  4422. else if (m22 > m33) {
  4423. s = 2.0 * Math.sqrt(1.0 + m22 - m11 - m33);
  4424. result.w = (m13 - m31) / s;
  4425. result.x = (m12 + m21) / s;
  4426. result.y = 0.25 * s;
  4427. result.z = (m23 + m32) / s;
  4428. }
  4429. else {
  4430. s = 2.0 * Math.sqrt(1.0 + m33 - m11 - m22);
  4431. result.w = (m21 - m12) / s;
  4432. result.x = (m13 + m31) / s;
  4433. result.y = (m23 + m32) / s;
  4434. result.z = 0.25 * s;
  4435. }
  4436. };
  4437. /**
  4438. * Returns a new Quaternion set to (0.0, 0.0, 0.0).
  4439. */
  4440. Quaternion.Zero = function () {
  4441. return new Quaternion(0.0, 0.0, 0.0, 0.0);
  4442. };
  4443. /**
  4444. * Returns a new Quaternion as the inverted current Quaternion.
  4445. */
  4446. Quaternion.Inverse = function (q) {
  4447. return new Quaternion(-q.x, -q.y, -q.z, q.w);
  4448. };
  4449. /**
  4450. * Returns the identity Quaternion.
  4451. */
  4452. Quaternion.Identity = function () {
  4453. return new Quaternion(0.0, 0.0, 0.0, 1.0);
  4454. };
  4455. Quaternion.IsIdentity = function (quaternion) {
  4456. return quaternion && quaternion.x === 0 && quaternion.y === 0 && quaternion.z === 0 && quaternion.w === 1;
  4457. };
  4458. /**
  4459. * Returns a new Quaternion set from the passed axis (Vector3) and angle in radians (float).
  4460. */
  4461. Quaternion.RotationAxis = function (axis, angle) {
  4462. return Quaternion.RotationAxisToRef(axis, angle, new Quaternion());
  4463. };
  4464. /**
  4465. * Sets the passed quaternion "result" from the passed axis (Vector3) and angle in radians (float).
  4466. */
  4467. Quaternion.RotationAxisToRef = function (axis, angle, result) {
  4468. var sin = Math.sin(angle / 2);
  4469. axis.normalize();
  4470. result.w = Math.cos(angle / 2);
  4471. result.x = axis.x * sin;
  4472. result.y = axis.y * sin;
  4473. result.z = axis.z * sin;
  4474. return result;
  4475. };
  4476. /**
  4477. * Retuns a new Quaternion set from the starting index of the passed array.
  4478. */
  4479. Quaternion.FromArray = function (array, offset) {
  4480. if (!offset) {
  4481. offset = 0;
  4482. }
  4483. return new Quaternion(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  4484. };
  4485. /**
  4486. * Returns a new Quaternion set from the passed Euler float angles (y, x, z).
  4487. */
  4488. Quaternion.RotationYawPitchRoll = function (yaw, pitch, roll) {
  4489. var q = new Quaternion();
  4490. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, q);
  4491. return q;
  4492. };
  4493. /**
  4494. * Sets the passed quaternion "result" from the passed float Euler angles (y, x, z).
  4495. */
  4496. Quaternion.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  4497. // Produces a quaternion from Euler angles in the z-y-x orientation (Tait-Bryan angles)
  4498. var halfRoll = roll * 0.5;
  4499. var halfPitch = pitch * 0.5;
  4500. var halfYaw = yaw * 0.5;
  4501. var sinRoll = Math.sin(halfRoll);
  4502. var cosRoll = Math.cos(halfRoll);
  4503. var sinPitch = Math.sin(halfPitch);
  4504. var cosPitch = Math.cos(halfPitch);
  4505. var sinYaw = Math.sin(halfYaw);
  4506. var cosYaw = Math.cos(halfYaw);
  4507. result.x = (cosYaw * sinPitch * cosRoll) + (sinYaw * cosPitch * sinRoll);
  4508. result.y = (sinYaw * cosPitch * cosRoll) - (cosYaw * sinPitch * sinRoll);
  4509. result.z = (cosYaw * cosPitch * sinRoll) - (sinYaw * sinPitch * cosRoll);
  4510. result.w = (cosYaw * cosPitch * cosRoll) + (sinYaw * sinPitch * sinRoll);
  4511. };
  4512. /**
  4513. * Returns a new Quaternion from the passed float Euler angles expressed in z-x-z orientation
  4514. */
  4515. Quaternion.RotationAlphaBetaGamma = function (alpha, beta, gamma) {
  4516. var result = new Quaternion();
  4517. Quaternion.RotationAlphaBetaGammaToRef(alpha, beta, gamma, result);
  4518. return result;
  4519. };
  4520. /**
  4521. * Sets the passed quaternion "result" from the passed float Euler angles expressed in z-x-z orientation
  4522. */
  4523. Quaternion.RotationAlphaBetaGammaToRef = function (alpha, beta, gamma, result) {
  4524. // Produces a quaternion from Euler angles in the z-x-z orientation
  4525. var halfGammaPlusAlpha = (gamma + alpha) * 0.5;
  4526. var halfGammaMinusAlpha = (gamma - alpha) * 0.5;
  4527. var halfBeta = beta * 0.5;
  4528. result.x = Math.cos(halfGammaMinusAlpha) * Math.sin(halfBeta);
  4529. result.y = Math.sin(halfGammaMinusAlpha) * Math.sin(halfBeta);
  4530. result.z = Math.sin(halfGammaPlusAlpha) * Math.cos(halfBeta);
  4531. result.w = Math.cos(halfGammaPlusAlpha) * Math.cos(halfBeta);
  4532. };
  4533. /**
  4534. * Returns a new Quaternion as the quaternion rotation value to reach the target (axis1, axis2, axis3) orientation as a rotated XYZ system.
  4535. * cf to Vector3.RotationFromAxis() documentation.
  4536. * Note : axis1, axis2 and axis3 are normalized during this operation.
  4537. */
  4538. Quaternion.RotationQuaternionFromAxis = function (axis1, axis2, axis3, ref) {
  4539. var quat = new Quaternion(0.0, 0.0, 0.0, 0.0);
  4540. Quaternion.RotationQuaternionFromAxisToRef(axis1, axis2, axis3, quat);
  4541. return quat;
  4542. };
  4543. /**
  4544. * Sets the passed quaternion "ref" with the quaternion rotation value to reach the target (axis1, axis2, axis3) orientation as a rotated XYZ system.
  4545. * cf to Vector3.RotationFromAxis() documentation.
  4546. * Note : axis1, axis2 and axis3 are normalized during this operation.
  4547. */
  4548. Quaternion.RotationQuaternionFromAxisToRef = function (axis1, axis2, axis3, ref) {
  4549. var rotMat = MathTmp.Matrix[0];
  4550. Matrix.FromXYZAxesToRef(axis1.normalize(), axis2.normalize(), axis3.normalize(), rotMat);
  4551. Quaternion.FromRotationMatrixToRef(rotMat, ref);
  4552. };
  4553. Quaternion.Slerp = function (left, right, amount) {
  4554. var result = Quaternion.Identity();
  4555. Quaternion.SlerpToRef(left, right, amount, result);
  4556. return result;
  4557. };
  4558. Quaternion.SlerpToRef = function (left, right, amount, result) {
  4559. var num2;
  4560. var num3;
  4561. var num = amount;
  4562. var num4 = (((left.x * right.x) + (left.y * right.y)) + (left.z * right.z)) + (left.w * right.w);
  4563. var flag = false;
  4564. if (num4 < 0) {
  4565. flag = true;
  4566. num4 = -num4;
  4567. }
  4568. if (num4 > 0.999999) {
  4569. num3 = 1 - num;
  4570. num2 = flag ? -num : num;
  4571. }
  4572. else {
  4573. var num5 = Math.acos(num4);
  4574. var num6 = (1.0 / Math.sin(num5));
  4575. num3 = (Math.sin((1.0 - num) * num5)) * num6;
  4576. num2 = flag ? ((-Math.sin(num * num5)) * num6) : ((Math.sin(num * num5)) * num6);
  4577. }
  4578. result.x = (num3 * left.x) + (num2 * right.x);
  4579. result.y = (num3 * left.y) + (num2 * right.y);
  4580. result.z = (num3 * left.z) + (num2 * right.z);
  4581. result.w = (num3 * left.w) + (num2 * right.w);
  4582. };
  4583. /**
  4584. * Returns a new Quaternion located for "amount" (float) on the Hermite interpolation spline defined by the vectors "value1", "tangent1", "value2", "tangent2".
  4585. */
  4586. Quaternion.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  4587. var squared = amount * amount;
  4588. var cubed = amount * squared;
  4589. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  4590. var part2 = (-2.0 * cubed) + (3.0 * squared);
  4591. var part3 = (cubed - (2.0 * squared)) + amount;
  4592. var part4 = cubed - squared;
  4593. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  4594. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  4595. var z = (((value1.z * part1) + (value2.z * part2)) + (tangent1.z * part3)) + (tangent2.z * part4);
  4596. var w = (((value1.w * part1) + (value2.w * part2)) + (tangent1.w * part3)) + (tangent2.w * part4);
  4597. return new Quaternion(x, y, z, w);
  4598. };
  4599. return Quaternion;
  4600. }());
  4601. BABYLON.Quaternion = Quaternion;
  4602. var Matrix = /** @class */ (function () {
  4603. function Matrix() {
  4604. this._isIdentity = false;
  4605. this._isIdentityDirty = true;
  4606. this.m = new Float32Array(16);
  4607. this._markAsUpdated();
  4608. }
  4609. Matrix.prototype._markAsUpdated = function () {
  4610. this.updateFlag = Matrix._updateFlagSeed++;
  4611. this._isIdentityDirty = true;
  4612. };
  4613. // Properties
  4614. /**
  4615. * Boolean : True is the matrix is the identity matrix
  4616. */
  4617. Matrix.prototype.isIdentity = function (considerAsTextureMatrix) {
  4618. if (considerAsTextureMatrix === void 0) { considerAsTextureMatrix = false; }
  4619. if (this._isIdentityDirty) {
  4620. this._isIdentityDirty = false;
  4621. if (this.m[0] !== 1.0 || this.m[5] !== 1.0 || this.m[15] !== 1.0) {
  4622. this._isIdentity = false;
  4623. }
  4624. else if (this.m[1] !== 0.0 || this.m[2] !== 0.0 || this.m[3] !== 0.0 ||
  4625. this.m[4] !== 0.0 || this.m[6] !== 0.0 || this.m[7] !== 0.0 ||
  4626. this.m[8] !== 0.0 || this.m[9] !== 0.0 || this.m[11] !== 0.0 ||
  4627. this.m[12] !== 0.0 || this.m[13] !== 0.0 || this.m[14] !== 0.0) {
  4628. this._isIdentity = false;
  4629. }
  4630. else {
  4631. this._isIdentity = true;
  4632. }
  4633. if (!considerAsTextureMatrix && this.m[10] !== 1.0) {
  4634. this._isIdentity = false;
  4635. }
  4636. }
  4637. return this._isIdentity;
  4638. };
  4639. /**
  4640. * Returns the matrix determinant (float).
  4641. */
  4642. Matrix.prototype.determinant = function () {
  4643. var temp1 = (this.m[10] * this.m[15]) - (this.m[11] * this.m[14]);
  4644. var temp2 = (this.m[9] * this.m[15]) - (this.m[11] * this.m[13]);
  4645. var temp3 = (this.m[9] * this.m[14]) - (this.m[10] * this.m[13]);
  4646. var temp4 = (this.m[8] * this.m[15]) - (this.m[11] * this.m[12]);
  4647. var temp5 = (this.m[8] * this.m[14]) - (this.m[10] * this.m[12]);
  4648. var temp6 = (this.m[8] * this.m[13]) - (this.m[9] * this.m[12]);
  4649. return ((((this.m[0] * (((this.m[5] * temp1) - (this.m[6] * temp2)) + (this.m[7] * temp3))) - (this.m[1] * (((this.m[4] * temp1) -
  4650. (this.m[6] * temp4)) + (this.m[7] * temp5)))) + (this.m[2] * (((this.m[4] * temp2) - (this.m[5] * temp4)) + (this.m[7] * temp6)))) -
  4651. (this.m[3] * (((this.m[4] * temp3) - (this.m[5] * temp5)) + (this.m[6] * temp6))));
  4652. };
  4653. // Methods
  4654. /**
  4655. * Returns the matrix underlying array.
  4656. */
  4657. Matrix.prototype.toArray = function () {
  4658. return this.m;
  4659. };
  4660. /**
  4661. * Returns the matrix underlying array.
  4662. */
  4663. Matrix.prototype.asArray = function () {
  4664. return this.toArray();
  4665. };
  4666. /**
  4667. * Inverts in place the Matrix.
  4668. * Returns the Matrix inverted.
  4669. */
  4670. Matrix.prototype.invert = function () {
  4671. this.invertToRef(this);
  4672. return this;
  4673. };
  4674. /**
  4675. * Sets all the matrix elements to zero.
  4676. * Returns the Matrix.
  4677. */
  4678. Matrix.prototype.reset = function () {
  4679. for (var index = 0; index < 16; index++) {
  4680. this.m[index] = 0.0;
  4681. }
  4682. this._markAsUpdated();
  4683. return this;
  4684. };
  4685. /**
  4686. * Returns a new Matrix as the addition result of the current Matrix and the passed one.
  4687. */
  4688. Matrix.prototype.add = function (other) {
  4689. var result = new Matrix();
  4690. this.addToRef(other, result);
  4691. return result;
  4692. };
  4693. /**
  4694. * Sets the passed matrix "result" with the ddition result of the current Matrix and the passed one.
  4695. * Returns the Matrix.
  4696. */
  4697. Matrix.prototype.addToRef = function (other, result) {
  4698. for (var index = 0; index < 16; index++) {
  4699. result.m[index] = this.m[index] + other.m[index];
  4700. }
  4701. result._markAsUpdated();
  4702. return this;
  4703. };
  4704. /**
  4705. * Adds in place the passed matrix to the current Matrix.
  4706. * Returns the updated Matrix.
  4707. */
  4708. Matrix.prototype.addToSelf = function (other) {
  4709. for (var index = 0; index < 16; index++) {
  4710. this.m[index] += other.m[index];
  4711. }
  4712. this._markAsUpdated();
  4713. return this;
  4714. };
  4715. /**
  4716. * Sets the passed matrix with the current inverted Matrix.
  4717. * Returns the unmodified current Matrix.
  4718. */
  4719. Matrix.prototype.invertToRef = function (other) {
  4720. var l1 = this.m[0];
  4721. var l2 = this.m[1];
  4722. var l3 = this.m[2];
  4723. var l4 = this.m[3];
  4724. var l5 = this.m[4];
  4725. var l6 = this.m[5];
  4726. var l7 = this.m[6];
  4727. var l8 = this.m[7];
  4728. var l9 = this.m[8];
  4729. var l10 = this.m[9];
  4730. var l11 = this.m[10];
  4731. var l12 = this.m[11];
  4732. var l13 = this.m[12];
  4733. var l14 = this.m[13];
  4734. var l15 = this.m[14];
  4735. var l16 = this.m[15];
  4736. var l17 = (l11 * l16) - (l12 * l15);
  4737. var l18 = (l10 * l16) - (l12 * l14);
  4738. var l19 = (l10 * l15) - (l11 * l14);
  4739. var l20 = (l9 * l16) - (l12 * l13);
  4740. var l21 = (l9 * l15) - (l11 * l13);
  4741. var l22 = (l9 * l14) - (l10 * l13);
  4742. var l23 = ((l6 * l17) - (l7 * l18)) + (l8 * l19);
  4743. var l24 = -(((l5 * l17) - (l7 * l20)) + (l8 * l21));
  4744. var l25 = ((l5 * l18) - (l6 * l20)) + (l8 * l22);
  4745. var l26 = -(((l5 * l19) - (l6 * l21)) + (l7 * l22));
  4746. var l27 = 1.0 / ((((l1 * l23) + (l2 * l24)) + (l3 * l25)) + (l4 * l26));
  4747. var l28 = (l7 * l16) - (l8 * l15);
  4748. var l29 = (l6 * l16) - (l8 * l14);
  4749. var l30 = (l6 * l15) - (l7 * l14);
  4750. var l31 = (l5 * l16) - (l8 * l13);
  4751. var l32 = (l5 * l15) - (l7 * l13);
  4752. var l33 = (l5 * l14) - (l6 * l13);
  4753. var l34 = (l7 * l12) - (l8 * l11);
  4754. var l35 = (l6 * l12) - (l8 * l10);
  4755. var l36 = (l6 * l11) - (l7 * l10);
  4756. var l37 = (l5 * l12) - (l8 * l9);
  4757. var l38 = (l5 * l11) - (l7 * l9);
  4758. var l39 = (l5 * l10) - (l6 * l9);
  4759. other.m[0] = l23 * l27;
  4760. other.m[4] = l24 * l27;
  4761. other.m[8] = l25 * l27;
  4762. other.m[12] = l26 * l27;
  4763. other.m[1] = -(((l2 * l17) - (l3 * l18)) + (l4 * l19)) * l27;
  4764. other.m[5] = (((l1 * l17) - (l3 * l20)) + (l4 * l21)) * l27;
  4765. other.m[9] = -(((l1 * l18) - (l2 * l20)) + (l4 * l22)) * l27;
  4766. other.m[13] = (((l1 * l19) - (l2 * l21)) + (l3 * l22)) * l27;
  4767. other.m[2] = (((l2 * l28) - (l3 * l29)) + (l4 * l30)) * l27;
  4768. other.m[6] = -(((l1 * l28) - (l3 * l31)) + (l4 * l32)) * l27;
  4769. other.m[10] = (((l1 * l29) - (l2 * l31)) + (l4 * l33)) * l27;
  4770. other.m[14] = -(((l1 * l30) - (l2 * l32)) + (l3 * l33)) * l27;
  4771. other.m[3] = -(((l2 * l34) - (l3 * l35)) + (l4 * l36)) * l27;
  4772. other.m[7] = (((l1 * l34) - (l3 * l37)) + (l4 * l38)) * l27;
  4773. other.m[11] = -(((l1 * l35) - (l2 * l37)) + (l4 * l39)) * l27;
  4774. other.m[15] = (((l1 * l36) - (l2 * l38)) + (l3 * l39)) * l27;
  4775. other._markAsUpdated();
  4776. return this;
  4777. };
  4778. /**
  4779. * Inserts the translation vector (using 3 x floats) in the current Matrix.
  4780. * Returns the updated Matrix.
  4781. */
  4782. Matrix.prototype.setTranslationFromFloats = function (x, y, z) {
  4783. this.m[12] = x;
  4784. this.m[13] = y;
  4785. this.m[14] = z;
  4786. this._markAsUpdated();
  4787. return this;
  4788. };
  4789. /**
  4790. * Inserts the translation vector in the current Matrix.
  4791. * Returns the updated Matrix.
  4792. */
  4793. Matrix.prototype.setTranslation = function (vector3) {
  4794. this.m[12] = vector3.x;
  4795. this.m[13] = vector3.y;
  4796. this.m[14] = vector3.z;
  4797. this._markAsUpdated();
  4798. return this;
  4799. };
  4800. /**
  4801. * Returns a new Vector3 as the extracted translation from the Matrix.
  4802. */
  4803. Matrix.prototype.getTranslation = function () {
  4804. return new Vector3(this.m[12], this.m[13], this.m[14]);
  4805. };
  4806. /**
  4807. * Fill a Vector3 with the extracted translation from the Matrix.
  4808. */
  4809. Matrix.prototype.getTranslationToRef = function (result) {
  4810. result.x = this.m[12];
  4811. result.y = this.m[13];
  4812. result.z = this.m[14];
  4813. return this;
  4814. };
  4815. /**
  4816. * Remove rotation and scaling part from the Matrix.
  4817. * Returns the updated Matrix.
  4818. */
  4819. Matrix.prototype.removeRotationAndScaling = function () {
  4820. this.setRowFromFloats(0, 1, 0, 0, 0);
  4821. this.setRowFromFloats(1, 0, 1, 0, 0);
  4822. this.setRowFromFloats(2, 0, 0, 1, 0);
  4823. return this;
  4824. };
  4825. /**
  4826. * Returns a new Matrix set with the multiplication result of the current Matrix and the passed one.
  4827. */
  4828. Matrix.prototype.multiply = function (other) {
  4829. var result = new Matrix();
  4830. this.multiplyToRef(other, result);
  4831. return result;
  4832. };
  4833. /**
  4834. * Updates the current Matrix from the passed one values.
  4835. * Returns the updated Matrix.
  4836. */
  4837. Matrix.prototype.copyFrom = function (other) {
  4838. for (var index = 0; index < 16; index++) {
  4839. this.m[index] = other.m[index];
  4840. }
  4841. this._markAsUpdated();
  4842. return this;
  4843. };
  4844. /**
  4845. * Populates the passed array from the starting index with the Matrix values.
  4846. * Returns the Matrix.
  4847. */
  4848. Matrix.prototype.copyToArray = function (array, offset) {
  4849. if (offset === void 0) { offset = 0; }
  4850. for (var index = 0; index < 16; index++) {
  4851. array[offset + index] = this.m[index];
  4852. }
  4853. return this;
  4854. };
  4855. /**
  4856. * Sets the passed matrix "result" with the multiplication result of the current Matrix and the passed one.
  4857. */
  4858. Matrix.prototype.multiplyToRef = function (other, result) {
  4859. this.multiplyToArray(other, result.m, 0);
  4860. result._markAsUpdated();
  4861. return this;
  4862. };
  4863. /**
  4864. * Sets the Float32Array "result" from the passed index "offset" with the multiplication result of the current Matrix and the passed one.
  4865. */
  4866. Matrix.prototype.multiplyToArray = function (other, result, offset) {
  4867. var tm0 = this.m[0];
  4868. var tm1 = this.m[1];
  4869. var tm2 = this.m[2];
  4870. var tm3 = this.m[3];
  4871. var tm4 = this.m[4];
  4872. var tm5 = this.m[5];
  4873. var tm6 = this.m[6];
  4874. var tm7 = this.m[7];
  4875. var tm8 = this.m[8];
  4876. var tm9 = this.m[9];
  4877. var tm10 = this.m[10];
  4878. var tm11 = this.m[11];
  4879. var tm12 = this.m[12];
  4880. var tm13 = this.m[13];
  4881. var tm14 = this.m[14];
  4882. var tm15 = this.m[15];
  4883. var om0 = other.m[0];
  4884. var om1 = other.m[1];
  4885. var om2 = other.m[2];
  4886. var om3 = other.m[3];
  4887. var om4 = other.m[4];
  4888. var om5 = other.m[5];
  4889. var om6 = other.m[6];
  4890. var om7 = other.m[7];
  4891. var om8 = other.m[8];
  4892. var om9 = other.m[9];
  4893. var om10 = other.m[10];
  4894. var om11 = other.m[11];
  4895. var om12 = other.m[12];
  4896. var om13 = other.m[13];
  4897. var om14 = other.m[14];
  4898. var om15 = other.m[15];
  4899. result[offset] = tm0 * om0 + tm1 * om4 + tm2 * om8 + tm3 * om12;
  4900. result[offset + 1] = tm0 * om1 + tm1 * om5 + tm2 * om9 + tm3 * om13;
  4901. result[offset + 2] = tm0 * om2 + tm1 * om6 + tm2 * om10 + tm3 * om14;
  4902. result[offset + 3] = tm0 * om3 + tm1 * om7 + tm2 * om11 + tm3 * om15;
  4903. result[offset + 4] = tm4 * om0 + tm5 * om4 + tm6 * om8 + tm7 * om12;
  4904. result[offset + 5] = tm4 * om1 + tm5 * om5 + tm6 * om9 + tm7 * om13;
  4905. result[offset + 6] = tm4 * om2 + tm5 * om6 + tm6 * om10 + tm7 * om14;
  4906. result[offset + 7] = tm4 * om3 + tm5 * om7 + tm6 * om11 + tm7 * om15;
  4907. result[offset + 8] = tm8 * om0 + tm9 * om4 + tm10 * om8 + tm11 * om12;
  4908. result[offset + 9] = tm8 * om1 + tm9 * om5 + tm10 * om9 + tm11 * om13;
  4909. result[offset + 10] = tm8 * om2 + tm9 * om6 + tm10 * om10 + tm11 * om14;
  4910. result[offset + 11] = tm8 * om3 + tm9 * om7 + tm10 * om11 + tm11 * om15;
  4911. result[offset + 12] = tm12 * om0 + tm13 * om4 + tm14 * om8 + tm15 * om12;
  4912. result[offset + 13] = tm12 * om1 + tm13 * om5 + tm14 * om9 + tm15 * om13;
  4913. result[offset + 14] = tm12 * om2 + tm13 * om6 + tm14 * om10 + tm15 * om14;
  4914. result[offset + 15] = tm12 * om3 + tm13 * om7 + tm14 * om11 + tm15 * om15;
  4915. return this;
  4916. };
  4917. /**
  4918. * Boolean : True is the current Matrix and the passed one values are strictly equal.
  4919. */
  4920. Matrix.prototype.equals = function (value) {
  4921. return value &&
  4922. (this.m[0] === value.m[0] && this.m[1] === value.m[1] && this.m[2] === value.m[2] && this.m[3] === value.m[3] &&
  4923. this.m[4] === value.m[4] && this.m[5] === value.m[5] && this.m[6] === value.m[6] && this.m[7] === value.m[7] &&
  4924. this.m[8] === value.m[8] && this.m[9] === value.m[9] && this.m[10] === value.m[10] && this.m[11] === value.m[11] &&
  4925. this.m[12] === value.m[12] && this.m[13] === value.m[13] && this.m[14] === value.m[14] && this.m[15] === value.m[15]);
  4926. };
  4927. /**
  4928. * Returns a new Matrix from the current Matrix.
  4929. */
  4930. Matrix.prototype.clone = function () {
  4931. return Matrix.FromValues(this.m[0], this.m[1], this.m[2], this.m[3], this.m[4], this.m[5], this.m[6], this.m[7], this.m[8], this.m[9], this.m[10], this.m[11], this.m[12], this.m[13], this.m[14], this.m[15]);
  4932. };
  4933. /**
  4934. * Returns the string "Matrix"
  4935. */
  4936. Matrix.prototype.getClassName = function () {
  4937. return "Matrix";
  4938. };
  4939. /**
  4940. * Returns the Matrix hash code.
  4941. */
  4942. Matrix.prototype.getHashCode = function () {
  4943. var hash = this.m[0] || 0;
  4944. for (var i = 1; i < 16; i++) {
  4945. hash = (hash * 397) ^ (this.m[i] || 0);
  4946. }
  4947. return hash;
  4948. };
  4949. /**
  4950. * Decomposes the current Matrix into :
  4951. * - a scale vector3 passed as a reference to update,
  4952. * - a rotation quaternion passed as a reference to update,
  4953. * - a translation vector3 passed as a reference to update.
  4954. * Returns the true if operation was successful.
  4955. */
  4956. Matrix.prototype.decompose = function (scale, rotation, translation) {
  4957. translation.x = this.m[12];
  4958. translation.y = this.m[13];
  4959. translation.z = this.m[14];
  4960. scale.x = Math.sqrt(this.m[0] * this.m[0] + this.m[1] * this.m[1] + this.m[2] * this.m[2]);
  4961. scale.y = Math.sqrt(this.m[4] * this.m[4] + this.m[5] * this.m[5] + this.m[6] * this.m[6]);
  4962. scale.z = Math.sqrt(this.m[8] * this.m[8] + this.m[9] * this.m[9] + this.m[10] * this.m[10]);
  4963. if (this.determinant() <= 0) {
  4964. scale.y *= -1;
  4965. }
  4966. if (scale.x === 0 || scale.y === 0 || scale.z === 0) {
  4967. rotation.x = 0;
  4968. rotation.y = 0;
  4969. rotation.z = 0;
  4970. rotation.w = 1;
  4971. return false;
  4972. }
  4973. Matrix.FromValuesToRef(this.m[0] / scale.x, this.m[1] / scale.x, this.m[2] / scale.x, 0, this.m[4] / scale.y, this.m[5] / scale.y, this.m[6] / scale.y, 0, this.m[8] / scale.z, this.m[9] / scale.z, this.m[10] / scale.z, 0, 0, 0, 0, 1, MathTmp.Matrix[0]);
  4974. Quaternion.FromRotationMatrixToRef(MathTmp.Matrix[0], rotation);
  4975. return true;
  4976. };
  4977. /**
  4978. * Writes to the given matrix a normal matrix, computed from this one (using values from identity matrix for fourth row and column).
  4979. * @param ref matrix to store the result
  4980. */
  4981. Matrix.prototype.toNormalMatrix = function (ref) {
  4982. this.invertToRef(ref);
  4983. ref.transpose();
  4984. var m = ref.m;
  4985. Matrix.FromValuesToRef(m[0], m[1], m[2], 0, m[4], m[5], m[6], 0, m[8], m[9], m[10], 0, 0, 0, 0, 1, ref);
  4986. };
  4987. /**
  4988. * Returns a new Matrix as the extracted rotation matrix from the current one.
  4989. */
  4990. Matrix.prototype.getRotationMatrix = function () {
  4991. var result = Matrix.Identity();
  4992. this.getRotationMatrixToRef(result);
  4993. return result;
  4994. };
  4995. /**
  4996. * Extracts the rotation matrix from the current one and sets it as the passed "result".
  4997. * Returns the current Matrix.
  4998. */
  4999. Matrix.prototype.getRotationMatrixToRef = function (result) {
  5000. var m = this.m;
  5001. var xs = m[0] * m[1] * m[2] * m[3] < 0 ? -1 : 1;
  5002. var ys = m[4] * m[5] * m[6] * m[7] < 0 ? -1 : 1;
  5003. var zs = m[8] * m[9] * m[10] * m[11] < 0 ? -1 : 1;
  5004. var sx = xs * Math.sqrt(m[0] * m[0] + m[1] * m[1] + m[2] * m[2]);
  5005. var sy = ys * Math.sqrt(m[4] * m[4] + m[5] * m[5] + m[6] * m[6]);
  5006. var sz = zs * Math.sqrt(m[8] * m[8] + m[9] * m[9] + m[10] * m[10]);
  5007. Matrix.FromValuesToRef(m[0] / sx, m[1] / sx, m[2] / sx, 0, m[4] / sy, m[5] / sy, m[6] / sy, 0, m[8] / sz, m[9] / sz, m[10] / sz, 0, 0, 0, 0, 1, result);
  5008. return this;
  5009. };
  5010. // Statics
  5011. /**
  5012. * Returns a new Matrix set from the starting index of the passed array.
  5013. */
  5014. Matrix.FromArray = function (array, offset) {
  5015. var result = new Matrix();
  5016. if (!offset) {
  5017. offset = 0;
  5018. }
  5019. Matrix.FromArrayToRef(array, offset, result);
  5020. return result;
  5021. };
  5022. /**
  5023. * Sets the passed "result" matrix from the starting index of the passed array.
  5024. */
  5025. Matrix.FromArrayToRef = function (array, offset, result) {
  5026. for (var index = 0; index < 16; index++) {
  5027. result.m[index] = array[index + offset];
  5028. }
  5029. result._markAsUpdated();
  5030. };
  5031. /**
  5032. * Sets the passed "result" matrix from the starting index of the passed Float32Array by multiplying each element by the float "scale".
  5033. */
  5034. Matrix.FromFloat32ArrayToRefScaled = function (array, offset, scale, result) {
  5035. for (var index = 0; index < 16; index++) {
  5036. result.m[index] = array[index + offset] * scale;
  5037. }
  5038. result._markAsUpdated();
  5039. };
  5040. /**
  5041. * Sets the passed matrix "result" with the 16 passed floats.
  5042. */
  5043. Matrix.FromValuesToRef = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44, result) {
  5044. result.m[0] = initialM11;
  5045. result.m[1] = initialM12;
  5046. result.m[2] = initialM13;
  5047. result.m[3] = initialM14;
  5048. result.m[4] = initialM21;
  5049. result.m[5] = initialM22;
  5050. result.m[6] = initialM23;
  5051. result.m[7] = initialM24;
  5052. result.m[8] = initialM31;
  5053. result.m[9] = initialM32;
  5054. result.m[10] = initialM33;
  5055. result.m[11] = initialM34;
  5056. result.m[12] = initialM41;
  5057. result.m[13] = initialM42;
  5058. result.m[14] = initialM43;
  5059. result.m[15] = initialM44;
  5060. result._markAsUpdated();
  5061. };
  5062. /**
  5063. * Returns the index-th row of the current matrix as a new Vector4.
  5064. */
  5065. Matrix.prototype.getRow = function (index) {
  5066. if (index < 0 || index > 3) {
  5067. return null;
  5068. }
  5069. var i = index * 4;
  5070. return new Vector4(this.m[i + 0], this.m[i + 1], this.m[i + 2], this.m[i + 3]);
  5071. };
  5072. /**
  5073. * Sets the index-th row of the current matrix with the passed Vector4 values.
  5074. * Returns the updated Matrix.
  5075. */
  5076. Matrix.prototype.setRow = function (index, row) {
  5077. if (index < 0 || index > 3) {
  5078. return this;
  5079. }
  5080. var i = index * 4;
  5081. this.m[i + 0] = row.x;
  5082. this.m[i + 1] = row.y;
  5083. this.m[i + 2] = row.z;
  5084. this.m[i + 3] = row.w;
  5085. this._markAsUpdated();
  5086. return this;
  5087. };
  5088. /**
  5089. * Compute the transpose of the matrix.
  5090. * Returns a new Matrix.
  5091. */
  5092. Matrix.prototype.transpose = function () {
  5093. return Matrix.Transpose(this);
  5094. };
  5095. /**
  5096. * Compute the transpose of the matrix.
  5097. * Returns the current matrix.
  5098. */
  5099. Matrix.prototype.transposeToRef = function (result) {
  5100. Matrix.TransposeToRef(this, result);
  5101. return this;
  5102. };
  5103. /**
  5104. * Sets the index-th row of the current matrix with the passed 4 x float values.
  5105. * Returns the updated Matrix.
  5106. */
  5107. Matrix.prototype.setRowFromFloats = function (index, x, y, z, w) {
  5108. if (index < 0 || index > 3) {
  5109. return this;
  5110. }
  5111. var i = index * 4;
  5112. this.m[i + 0] = x;
  5113. this.m[i + 1] = y;
  5114. this.m[i + 2] = z;
  5115. this.m[i + 3] = w;
  5116. this._markAsUpdated();
  5117. return this;
  5118. };
  5119. Object.defineProperty(Matrix, "IdentityReadOnly", {
  5120. /**
  5121. * Static identity matrix to be used as readonly matrix
  5122. * Must not be updated.
  5123. */
  5124. get: function () {
  5125. return Matrix._identityReadOnly;
  5126. },
  5127. enumerable: true,
  5128. configurable: true
  5129. });
  5130. /**
  5131. * Returns a new Matrix set from the 16 passed floats.
  5132. */
  5133. Matrix.FromValues = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44) {
  5134. var result = new Matrix();
  5135. result.m[0] = initialM11;
  5136. result.m[1] = initialM12;
  5137. result.m[2] = initialM13;
  5138. result.m[3] = initialM14;
  5139. result.m[4] = initialM21;
  5140. result.m[5] = initialM22;
  5141. result.m[6] = initialM23;
  5142. result.m[7] = initialM24;
  5143. result.m[8] = initialM31;
  5144. result.m[9] = initialM32;
  5145. result.m[10] = initialM33;
  5146. result.m[11] = initialM34;
  5147. result.m[12] = initialM41;
  5148. result.m[13] = initialM42;
  5149. result.m[14] = initialM43;
  5150. result.m[15] = initialM44;
  5151. return result;
  5152. };
  5153. /**
  5154. * Returns a new Matrix composed by the passed scale (vector3), rotation (quaternion) and translation (vector3).
  5155. */
  5156. Matrix.Compose = function (scale, rotation, translation) {
  5157. var result = Matrix.Identity();
  5158. Matrix.ComposeToRef(scale, rotation, translation, result);
  5159. return result;
  5160. };
  5161. /**
  5162. * Update a Matrix with values composed by the passed scale (vector3), rotation (quaternion) and translation (vector3).
  5163. */
  5164. Matrix.ComposeToRef = function (scale, rotation, translation, result) {
  5165. Matrix.FromValuesToRef(scale.x, 0, 0, 0, 0, scale.y, 0, 0, 0, 0, scale.z, 0, 0, 0, 0, 1, MathTmp.Matrix[1]);
  5166. rotation.toRotationMatrix(MathTmp.Matrix[0]);
  5167. MathTmp.Matrix[1].multiplyToRef(MathTmp.Matrix[0], result);
  5168. result.setTranslation(translation);
  5169. };
  5170. /**
  5171. * Returns a new indentity Matrix.
  5172. */
  5173. Matrix.Identity = function () {
  5174. return Matrix.FromValues(1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0);
  5175. };
  5176. /**
  5177. * Sets the passed "result" as an identity matrix.
  5178. */
  5179. Matrix.IdentityToRef = function (result) {
  5180. Matrix.FromValuesToRef(1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, result);
  5181. };
  5182. /**
  5183. * Returns a new zero Matrix.
  5184. */
  5185. Matrix.Zero = function () {
  5186. return Matrix.FromValues(0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0);
  5187. };
  5188. /**
  5189. * Returns a new rotation matrix for "angle" radians around the X axis.
  5190. */
  5191. Matrix.RotationX = function (angle) {
  5192. var result = new Matrix();
  5193. Matrix.RotationXToRef(angle, result);
  5194. return result;
  5195. };
  5196. /**
  5197. * Returns a new Matrix as the passed inverted one.
  5198. */
  5199. Matrix.Invert = function (source) {
  5200. var result = new Matrix();
  5201. source.invertToRef(result);
  5202. return result;
  5203. };
  5204. /**
  5205. * Sets the passed matrix "result" as a rotation matrix for "angle" radians around the X axis.
  5206. */
  5207. Matrix.RotationXToRef = function (angle, result) {
  5208. var s = Math.sin(angle);
  5209. var c = Math.cos(angle);
  5210. result.m[0] = 1.0;
  5211. result.m[15] = 1.0;
  5212. result.m[5] = c;
  5213. result.m[10] = c;
  5214. result.m[9] = -s;
  5215. result.m[6] = s;
  5216. result.m[1] = 0.0;
  5217. result.m[2] = 0.0;
  5218. result.m[3] = 0.0;
  5219. result.m[4] = 0.0;
  5220. result.m[7] = 0.0;
  5221. result.m[8] = 0.0;
  5222. result.m[11] = 0.0;
  5223. result.m[12] = 0.0;
  5224. result.m[13] = 0.0;
  5225. result.m[14] = 0.0;
  5226. result._markAsUpdated();
  5227. };
  5228. /**
  5229. * Returns a new rotation matrix for "angle" radians around the Y axis.
  5230. */
  5231. Matrix.RotationY = function (angle) {
  5232. var result = new Matrix();
  5233. Matrix.RotationYToRef(angle, result);
  5234. return result;
  5235. };
  5236. /**
  5237. * Sets the passed matrix "result" as a rotation matrix for "angle" radians around the Y axis.
  5238. */
  5239. Matrix.RotationYToRef = function (angle, result) {
  5240. var s = Math.sin(angle);
  5241. var c = Math.cos(angle);
  5242. result.m[5] = 1.0;
  5243. result.m[15] = 1.0;
  5244. result.m[0] = c;
  5245. result.m[2] = -s;
  5246. result.m[8] = s;
  5247. result.m[10] = c;
  5248. result.m[1] = 0.0;
  5249. result.m[3] = 0.0;
  5250. result.m[4] = 0.0;
  5251. result.m[6] = 0.0;
  5252. result.m[7] = 0.0;
  5253. result.m[9] = 0.0;
  5254. result.m[11] = 0.0;
  5255. result.m[12] = 0.0;
  5256. result.m[13] = 0.0;
  5257. result.m[14] = 0.0;
  5258. result._markAsUpdated();
  5259. };
  5260. /**
  5261. * Returns a new rotation matrix for "angle" radians around the Z axis.
  5262. */
  5263. Matrix.RotationZ = function (angle) {
  5264. var result = new Matrix();
  5265. Matrix.RotationZToRef(angle, result);
  5266. return result;
  5267. };
  5268. /**
  5269. * Sets the passed matrix "result" as a rotation matrix for "angle" radians around the Z axis.
  5270. */
  5271. Matrix.RotationZToRef = function (angle, result) {
  5272. var s = Math.sin(angle);
  5273. var c = Math.cos(angle);
  5274. result.m[10] = 1.0;
  5275. result.m[15] = 1.0;
  5276. result.m[0] = c;
  5277. result.m[1] = s;
  5278. result.m[4] = -s;
  5279. result.m[5] = c;
  5280. result.m[2] = 0.0;
  5281. result.m[3] = 0.0;
  5282. result.m[6] = 0.0;
  5283. result.m[7] = 0.0;
  5284. result.m[8] = 0.0;
  5285. result.m[9] = 0.0;
  5286. result.m[11] = 0.0;
  5287. result.m[12] = 0.0;
  5288. result.m[13] = 0.0;
  5289. result.m[14] = 0.0;
  5290. result._markAsUpdated();
  5291. };
  5292. /**
  5293. * Returns a new rotation matrix for "angle" radians around the passed axis.
  5294. */
  5295. Matrix.RotationAxis = function (axis, angle) {
  5296. var result = Matrix.Zero();
  5297. Matrix.RotationAxisToRef(axis, angle, result);
  5298. return result;
  5299. };
  5300. /**
  5301. * Sets the passed matrix "result" as a rotation matrix for "angle" radians around the passed axis.
  5302. */
  5303. Matrix.RotationAxisToRef = function (axis, angle, result) {
  5304. var s = Math.sin(-angle);
  5305. var c = Math.cos(-angle);
  5306. var c1 = 1 - c;
  5307. axis.normalize();
  5308. result.m[0] = (axis.x * axis.x) * c1 + c;
  5309. result.m[1] = (axis.x * axis.y) * c1 - (axis.z * s);
  5310. result.m[2] = (axis.x * axis.z) * c1 + (axis.y * s);
  5311. result.m[3] = 0.0;
  5312. result.m[4] = (axis.y * axis.x) * c1 + (axis.z * s);
  5313. result.m[5] = (axis.y * axis.y) * c1 + c;
  5314. result.m[6] = (axis.y * axis.z) * c1 - (axis.x * s);
  5315. result.m[7] = 0.0;
  5316. result.m[8] = (axis.z * axis.x) * c1 - (axis.y * s);
  5317. result.m[9] = (axis.z * axis.y) * c1 + (axis.x * s);
  5318. result.m[10] = (axis.z * axis.z) * c1 + c;
  5319. result.m[11] = 0.0;
  5320. result.m[15] = 1.0;
  5321. result._markAsUpdated();
  5322. };
  5323. /**
  5324. * Returns a new Matrix as a rotation matrix from the Euler angles (y, x, z).
  5325. */
  5326. Matrix.RotationYawPitchRoll = function (yaw, pitch, roll) {
  5327. var result = new Matrix();
  5328. Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, result);
  5329. return result;
  5330. };
  5331. /**
  5332. * Sets the passed matrix "result" as a rotation matrix from the Euler angles (y, x, z).
  5333. */
  5334. Matrix.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  5335. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, this._tempQuaternion);
  5336. this._tempQuaternion.toRotationMatrix(result);
  5337. };
  5338. /**
  5339. * Returns a new Matrix as a scaling matrix from the passed floats (x, y, z).
  5340. */
  5341. Matrix.Scaling = function (x, y, z) {
  5342. var result = Matrix.Zero();
  5343. Matrix.ScalingToRef(x, y, z, result);
  5344. return result;
  5345. };
  5346. /**
  5347. * Sets the passed matrix "result" as a scaling matrix from the passed floats (x, y, z).
  5348. */
  5349. Matrix.ScalingToRef = function (x, y, z, result) {
  5350. result.m[0] = x;
  5351. result.m[1] = 0.0;
  5352. result.m[2] = 0.0;
  5353. result.m[3] = 0.0;
  5354. result.m[4] = 0.0;
  5355. result.m[5] = y;
  5356. result.m[6] = 0.0;
  5357. result.m[7] = 0.0;
  5358. result.m[8] = 0.0;
  5359. result.m[9] = 0.0;
  5360. result.m[10] = z;
  5361. result.m[11] = 0.0;
  5362. result.m[12] = 0.0;
  5363. result.m[13] = 0.0;
  5364. result.m[14] = 0.0;
  5365. result.m[15] = 1.0;
  5366. result._markAsUpdated();
  5367. };
  5368. /**
  5369. * Returns a new Matrix as a translation matrix from the passed floats (x, y, z).
  5370. */
  5371. Matrix.Translation = function (x, y, z) {
  5372. var result = Matrix.Identity();
  5373. Matrix.TranslationToRef(x, y, z, result);
  5374. return result;
  5375. };
  5376. /**
  5377. * Sets the passed matrix "result" as a translation matrix from the passed floats (x, y, z).
  5378. */
  5379. Matrix.TranslationToRef = function (x, y, z, result) {
  5380. Matrix.FromValuesToRef(1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, x, y, z, 1.0, result);
  5381. };
  5382. /**
  5383. * Returns a new Matrix whose values are the interpolated values for "gradien" (float) between the ones of the matrices "startValue" and "endValue".
  5384. */
  5385. Matrix.Lerp = function (startValue, endValue, gradient) {
  5386. var result = Matrix.Zero();
  5387. for (var index = 0; index < 16; index++) {
  5388. result.m[index] = startValue.m[index] * (1.0 - gradient) + endValue.m[index] * gradient;
  5389. }
  5390. result._markAsUpdated();
  5391. return result;
  5392. };
  5393. /**
  5394. * Returns a new Matrix whose values are computed by :
  5395. * - decomposing the the "startValue" and "endValue" matrices into their respective scale, rotation and translation matrices,
  5396. * - interpolating for "gradient" (float) the values between each of these decomposed matrices between the start and the end,
  5397. * - recomposing a new matrix from these 3 interpolated scale, rotation and translation matrices.
  5398. */
  5399. Matrix.DecomposeLerp = function (startValue, endValue, gradient) {
  5400. var startScale = new Vector3(0, 0, 0);
  5401. var startRotation = new Quaternion();
  5402. var startTranslation = new Vector3(0, 0, 0);
  5403. startValue.decompose(startScale, startRotation, startTranslation);
  5404. var endScale = new Vector3(0, 0, 0);
  5405. var endRotation = new Quaternion();
  5406. var endTranslation = new Vector3(0, 0, 0);
  5407. endValue.decompose(endScale, endRotation, endTranslation);
  5408. var resultScale = Vector3.Lerp(startScale, endScale, gradient);
  5409. var resultRotation = Quaternion.Slerp(startRotation, endRotation, gradient);
  5410. var resultTranslation = Vector3.Lerp(startTranslation, endTranslation, gradient);
  5411. return Matrix.Compose(resultScale, resultRotation, resultTranslation);
  5412. };
  5413. /**
  5414. * Returns a new rotation Matrix used to rotate a mesh so as it looks at the target Vector3, from the eye Vector3, the UP vector3 being orientated like "up".
  5415. * This methods works for a Left-Handed system.
  5416. */
  5417. Matrix.LookAtLH = function (eye, target, up) {
  5418. var result = Matrix.Zero();
  5419. Matrix.LookAtLHToRef(eye, target, up, result);
  5420. return result;
  5421. };
  5422. /**
  5423. * Sets the passed "result" Matrix as a rotation matrix used to rotate a mesh so as it looks at the target Vector3, from the eye Vector3, the UP vector3 being orientated like "up".
  5424. * This methods works for a Left-Handed system.
  5425. */
  5426. Matrix.LookAtLHToRef = function (eye, target, up, result) {
  5427. // Z axis
  5428. target.subtractToRef(eye, this._zAxis);
  5429. this._zAxis.normalize();
  5430. // X axis
  5431. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  5432. if (this._xAxis.lengthSquared() === 0) {
  5433. this._xAxis.x = 1.0;
  5434. }
  5435. else {
  5436. this._xAxis.normalize();
  5437. }
  5438. // Y axis
  5439. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  5440. this._yAxis.normalize();
  5441. // Eye angles
  5442. var ex = -Vector3.Dot(this._xAxis, eye);
  5443. var ey = -Vector3.Dot(this._yAxis, eye);
  5444. var ez = -Vector3.Dot(this._zAxis, eye);
  5445. return Matrix.FromValuesToRef(this._xAxis.x, this._yAxis.x, this._zAxis.x, 0, this._xAxis.y, this._yAxis.y, this._zAxis.y, 0, this._xAxis.z, this._yAxis.z, this._zAxis.z, 0, ex, ey, ez, 1, result);
  5446. };
  5447. /**
  5448. * Returns a new rotation Matrix used to rotate a mesh so as it looks at the target Vector3, from the eye Vector3, the UP vector3 being orientated like "up".
  5449. * This methods works for a Right-Handed system.
  5450. */
  5451. Matrix.LookAtRH = function (eye, target, up) {
  5452. var result = Matrix.Zero();
  5453. Matrix.LookAtRHToRef(eye, target, up, result);
  5454. return result;
  5455. };
  5456. /**
  5457. * Sets the passed "result" Matrix as a rotation matrix used to rotate a mesh so as it looks at the target Vector3, from the eye Vector3, the UP vector3 being orientated like "up".
  5458. * This methods works for a Left-Handed system.
  5459. */
  5460. Matrix.LookAtRHToRef = function (eye, target, up, result) {
  5461. // Z axis
  5462. eye.subtractToRef(target, this._zAxis);
  5463. this._zAxis.normalize();
  5464. // X axis
  5465. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  5466. if (this._xAxis.lengthSquared() === 0) {
  5467. this._xAxis.x = 1.0;
  5468. }
  5469. else {
  5470. this._xAxis.normalize();
  5471. }
  5472. // Y axis
  5473. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  5474. this._yAxis.normalize();
  5475. // Eye angles
  5476. var ex = -Vector3.Dot(this._xAxis, eye);
  5477. var ey = -Vector3.Dot(this._yAxis, eye);
  5478. var ez = -Vector3.Dot(this._zAxis, eye);
  5479. return Matrix.FromValuesToRef(this._xAxis.x, this._yAxis.x, this._zAxis.x, 0, this._xAxis.y, this._yAxis.y, this._zAxis.y, 0, this._xAxis.z, this._yAxis.z, this._zAxis.z, 0, ex, ey, ez, 1, result);
  5480. };
  5481. /**
  5482. * Returns a new Matrix as a left-handed orthographic projection matrix computed from the passed floats : width and height of the projection plane, z near and far limits.
  5483. */
  5484. Matrix.OrthoLH = function (width, height, znear, zfar) {
  5485. var matrix = Matrix.Zero();
  5486. Matrix.OrthoLHToRef(width, height, znear, zfar, matrix);
  5487. return matrix;
  5488. };
  5489. /**
  5490. * Sets the passed matrix "result" as a left-handed orthographic projection matrix computed from the passed floats : width and height of the projection plane, z near and far limits.
  5491. */
  5492. Matrix.OrthoLHToRef = function (width, height, znear, zfar, result) {
  5493. var n = znear;
  5494. var f = zfar;
  5495. var a = 2.0 / width;
  5496. var b = 2.0 / height;
  5497. var c = 2.0 / (f - n);
  5498. var d = -(f + n) / (f - n);
  5499. Matrix.FromValuesToRef(a, 0.0, 0.0, 0.0, 0.0, b, 0.0, 0.0, 0.0, 0.0, c, 0.0, 0.0, 0.0, d, 1.0, result);
  5500. };
  5501. /**
  5502. * Returns a new Matrix as a left-handed orthographic projection matrix computed from the passed floats : left, right, top and bottom being the coordinates of the projection plane, z near and far limits.
  5503. */
  5504. Matrix.OrthoOffCenterLH = function (left, right, bottom, top, znear, zfar) {
  5505. var matrix = Matrix.Zero();
  5506. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, matrix);
  5507. return matrix;
  5508. };
  5509. /**
  5510. * Sets the passed matrix "result" as a left-handed orthographic projection matrix computed from the passed floats : left, right, top and bottom being the coordinates of the projection plane, z near and far limits.
  5511. */
  5512. Matrix.OrthoOffCenterLHToRef = function (left, right, bottom, top, znear, zfar, result) {
  5513. var n = znear;
  5514. var f = zfar;
  5515. var a = 2.0 / (right - left);
  5516. var b = 2.0 / (top - bottom);
  5517. var c = 2.0 / (f - n);
  5518. var d = -(f + n) / (f - n);
  5519. var i0 = (left + right) / (left - right);
  5520. var i1 = (top + bottom) / (bottom - top);
  5521. Matrix.FromValuesToRef(a, 0.0, 0.0, 0.0, 0.0, b, 0.0, 0.0, 0.0, 0.0, c, 0.0, i0, i1, d, 1.0, result);
  5522. };
  5523. /**
  5524. * Returns a new Matrix as a right-handed orthographic projection matrix computed from the passed floats : left, right, top and bottom being the coordinates of the projection plane, z near and far limits.
  5525. */
  5526. Matrix.OrthoOffCenterRH = function (left, right, bottom, top, znear, zfar) {
  5527. var matrix = Matrix.Zero();
  5528. Matrix.OrthoOffCenterRHToRef(left, right, bottom, top, znear, zfar, matrix);
  5529. return matrix;
  5530. };
  5531. /**
  5532. * Sets the passed matrix "result" as a right-handed orthographic projection matrix computed from the passed floats : left, right, top and bottom being the coordinates of the projection plane, z near and far limits.
  5533. */
  5534. Matrix.OrthoOffCenterRHToRef = function (left, right, bottom, top, znear, zfar, result) {
  5535. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, result);
  5536. result.m[10] *= -1.0;
  5537. };
  5538. /**
  5539. * Returns a new Matrix as a left-handed perspective projection matrix computed from the passed floats : width and height of the projection plane, z near and far limits.
  5540. */
  5541. Matrix.PerspectiveLH = function (width, height, znear, zfar) {
  5542. var matrix = Matrix.Zero();
  5543. var n = znear;
  5544. var f = zfar;
  5545. var a = 2.0 * n / width;
  5546. var b = 2.0 * n / height;
  5547. var c = (f + n) / (f - n);
  5548. var d = -2.0 * f * n / (f - n);
  5549. Matrix.FromValuesToRef(a, 0.0, 0.0, 0.0, 0.0, b, 0.0, 0.0, 0.0, 0.0, c, 1.0, 0.0, 0.0, d, 0.0, matrix);
  5550. return matrix;
  5551. };
  5552. /**
  5553. * Returns a new Matrix as a left-handed perspective projection matrix computed from the passed floats : vertical angle of view (fov), width/height ratio (aspect), z near and far limits.
  5554. */
  5555. Matrix.PerspectiveFovLH = function (fov, aspect, znear, zfar) {
  5556. var matrix = Matrix.Zero();
  5557. Matrix.PerspectiveFovLHToRef(fov, aspect, znear, zfar, matrix);
  5558. return matrix;
  5559. };
  5560. /**
  5561. * Sets the passed matrix "result" as a left-handed perspective projection matrix computed from the passed floats : vertical angle of view (fov), width/height ratio (aspect), z near and far limits.
  5562. */
  5563. Matrix.PerspectiveFovLHToRef = function (fov, aspect, znear, zfar, result, isVerticalFovFixed) {
  5564. if (isVerticalFovFixed === void 0) { isVerticalFovFixed = true; }
  5565. var n = znear;
  5566. var f = zfar;
  5567. var t = 1.0 / (Math.tan(fov * 0.5));
  5568. var a = isVerticalFovFixed ? (t / aspect) : t;
  5569. var b = isVerticalFovFixed ? t : (t * aspect);
  5570. var c = (f + n) / (f - n);
  5571. var d = -2.0 * f * n / (f - n);
  5572. Matrix.FromValuesToRef(a, 0.0, 0.0, 0.0, 0.0, b, 0.0, 0.0, 0.0, 0.0, c, 1.0, 0.0, 0.0, d, 0.0, result);
  5573. };
  5574. /**
  5575. * Returns a new Matrix as a right-handed perspective projection matrix computed from the passed floats : vertical angle of view (fov), width/height ratio (aspect), z near and far limits.
  5576. */
  5577. Matrix.PerspectiveFovRH = function (fov, aspect, znear, zfar) {
  5578. var matrix = Matrix.Zero();
  5579. Matrix.PerspectiveFovRHToRef(fov, aspect, znear, zfar, matrix);
  5580. return matrix;
  5581. };
  5582. /**
  5583. * Sets the passed matrix "result" as a right-handed perspective projection matrix computed from the passed floats : vertical angle of view (fov), width/height ratio (aspect), z near and far limits.
  5584. */
  5585. Matrix.PerspectiveFovRHToRef = function (fov, aspect, znear, zfar, result, isVerticalFovFixed) {
  5586. //alternatively this could be expressed as:
  5587. // m = PerspectiveFovLHToRef
  5588. // m[10] *= -1.0;
  5589. // m[11] *= -1.0;
  5590. if (isVerticalFovFixed === void 0) { isVerticalFovFixed = true; }
  5591. var n = znear;
  5592. var f = zfar;
  5593. var t = 1.0 / (Math.tan(fov * 0.5));
  5594. var a = isVerticalFovFixed ? (t / aspect) : t;
  5595. var b = isVerticalFovFixed ? t : (t * aspect);
  5596. var c = -(f + n) / (f - n);
  5597. var d = -2 * f * n / (f - n);
  5598. Matrix.FromValuesToRef(a, 0.0, 0.0, 0.0, 0.0, b, 0.0, 0.0, 0.0, 0.0, c, -1.0, 0.0, 0.0, d, 0.0, result);
  5599. };
  5600. /**
  5601. * Sets the passed matrix "result" as a left-handed perspective projection matrix for WebVR computed from the passed floats : vertical angle of view (fov), width/height ratio (aspect), z near and far limits.
  5602. */
  5603. Matrix.PerspectiveFovWebVRToRef = function (fov, znear, zfar, result, rightHanded) {
  5604. if (rightHanded === void 0) { rightHanded = false; }
  5605. var rightHandedFactor = rightHanded ? -1 : 1;
  5606. var upTan = Math.tan(fov.upDegrees * Math.PI / 180.0);
  5607. var downTan = Math.tan(fov.downDegrees * Math.PI / 180.0);
  5608. var leftTan = Math.tan(fov.leftDegrees * Math.PI / 180.0);
  5609. var rightTan = Math.tan(fov.rightDegrees * Math.PI / 180.0);
  5610. var xScale = 2.0 / (leftTan + rightTan);
  5611. var yScale = 2.0 / (upTan + downTan);
  5612. result.m[0] = xScale;
  5613. result.m[1] = result.m[2] = result.m[3] = result.m[4] = 0.0;
  5614. result.m[5] = yScale;
  5615. result.m[6] = result.m[7] = 0.0;
  5616. result.m[8] = ((leftTan - rightTan) * xScale * 0.5); // * rightHandedFactor;
  5617. result.m[9] = -((upTan - downTan) * yScale * 0.5); // * rightHandedFactor;
  5618. //result.m[10] = -(znear + zfar) / (zfar - znear) * rightHandedFactor;
  5619. result.m[10] = -zfar / (znear - zfar);
  5620. result.m[11] = 1.0 * rightHandedFactor;
  5621. result.m[12] = result.m[13] = result.m[15] = 0.0;
  5622. result.m[14] = -(2.0 * zfar * znear) / (zfar - znear);
  5623. // result.m[14] = (znear * zfar) / (znear - zfar);
  5624. result._markAsUpdated();
  5625. };
  5626. /**
  5627. * Returns the final transformation matrix : world * view * projection * viewport
  5628. */
  5629. Matrix.GetFinalMatrix = function (viewport, world, view, projection, zmin, zmax) {
  5630. var cw = viewport.width;
  5631. var ch = viewport.height;
  5632. var cx = viewport.x;
  5633. var cy = viewport.y;
  5634. var viewportMatrix = Matrix.FromValues(cw / 2.0, 0.0, 0.0, 0.0, 0.0, -ch / 2.0, 0.0, 0.0, 0.0, 0.0, zmax - zmin, 0.0, cx + cw / 2.0, ch / 2.0 + cy, zmin, 1);
  5635. return world.multiply(view).multiply(projection).multiply(viewportMatrix);
  5636. };
  5637. /**
  5638. * Returns a new Float32Array array with 4 elements : the 2x2 matrix extracted from the passed Matrix.
  5639. */
  5640. Matrix.GetAsMatrix2x2 = function (matrix) {
  5641. return new Float32Array([
  5642. matrix.m[0], matrix.m[1],
  5643. matrix.m[4], matrix.m[5]
  5644. ]);
  5645. };
  5646. /**
  5647. * Returns a new Float32Array array with 9 elements : the 3x3 matrix extracted from the passed Matrix.
  5648. */
  5649. Matrix.GetAsMatrix3x3 = function (matrix) {
  5650. return new Float32Array([
  5651. matrix.m[0], matrix.m[1], matrix.m[2],
  5652. matrix.m[4], matrix.m[5], matrix.m[6],
  5653. matrix.m[8], matrix.m[9], matrix.m[10]
  5654. ]);
  5655. };
  5656. /**
  5657. * Compute the transpose of the passed Matrix.
  5658. * Returns a new Matrix.
  5659. */
  5660. Matrix.Transpose = function (matrix) {
  5661. var result = new Matrix();
  5662. Matrix.TransposeToRef(matrix, result);
  5663. return result;
  5664. };
  5665. /**
  5666. * Compute the transpose of the passed Matrix and store it in the result matrix.
  5667. */
  5668. Matrix.TransposeToRef = function (matrix, result) {
  5669. result.m[0] = matrix.m[0];
  5670. result.m[1] = matrix.m[4];
  5671. result.m[2] = matrix.m[8];
  5672. result.m[3] = matrix.m[12];
  5673. result.m[4] = matrix.m[1];
  5674. result.m[5] = matrix.m[5];
  5675. result.m[6] = matrix.m[9];
  5676. result.m[7] = matrix.m[13];
  5677. result.m[8] = matrix.m[2];
  5678. result.m[9] = matrix.m[6];
  5679. result.m[10] = matrix.m[10];
  5680. result.m[11] = matrix.m[14];
  5681. result.m[12] = matrix.m[3];
  5682. result.m[13] = matrix.m[7];
  5683. result.m[14] = matrix.m[11];
  5684. result.m[15] = matrix.m[15];
  5685. };
  5686. /**
  5687. * Returns a new Matrix as the reflection matrix across the passed plane.
  5688. */
  5689. Matrix.Reflection = function (plane) {
  5690. var matrix = new Matrix();
  5691. Matrix.ReflectionToRef(plane, matrix);
  5692. return matrix;
  5693. };
  5694. /**
  5695. * Sets the passed matrix "result" as the reflection matrix across the passed plane.
  5696. */
  5697. Matrix.ReflectionToRef = function (plane, result) {
  5698. plane.normalize();
  5699. var x = plane.normal.x;
  5700. var y = plane.normal.y;
  5701. var z = plane.normal.z;
  5702. var temp = -2 * x;
  5703. var temp2 = -2 * y;
  5704. var temp3 = -2 * z;
  5705. result.m[0] = (temp * x) + 1;
  5706. result.m[1] = temp2 * x;
  5707. result.m[2] = temp3 * x;
  5708. result.m[3] = 0.0;
  5709. result.m[4] = temp * y;
  5710. result.m[5] = (temp2 * y) + 1;
  5711. result.m[6] = temp3 * y;
  5712. result.m[7] = 0.0;
  5713. result.m[8] = temp * z;
  5714. result.m[9] = temp2 * z;
  5715. result.m[10] = (temp3 * z) + 1;
  5716. result.m[11] = 0.0;
  5717. result.m[12] = temp * plane.d;
  5718. result.m[13] = temp2 * plane.d;
  5719. result.m[14] = temp3 * plane.d;
  5720. result.m[15] = 1.0;
  5721. result._markAsUpdated();
  5722. };
  5723. /**
  5724. * Sets the passed matrix "mat" as a rotation matrix composed from the 3 passed left handed axis.
  5725. */
  5726. Matrix.FromXYZAxesToRef = function (xaxis, yaxis, zaxis, result) {
  5727. result.m[0] = xaxis.x;
  5728. result.m[1] = xaxis.y;
  5729. result.m[2] = xaxis.z;
  5730. result.m[3] = 0.0;
  5731. result.m[4] = yaxis.x;
  5732. result.m[5] = yaxis.y;
  5733. result.m[6] = yaxis.z;
  5734. result.m[7] = 0.0;
  5735. result.m[8] = zaxis.x;
  5736. result.m[9] = zaxis.y;
  5737. result.m[10] = zaxis.z;
  5738. result.m[11] = 0.0;
  5739. result.m[12] = 0.0;
  5740. result.m[13] = 0.0;
  5741. result.m[14] = 0.0;
  5742. result.m[15] = 1.0;
  5743. result._markAsUpdated();
  5744. };
  5745. /**
  5746. * Sets the passed matrix "result" as a rotation matrix according to the passed quaternion.
  5747. */
  5748. Matrix.FromQuaternionToRef = function (quat, result) {
  5749. var xx = quat.x * quat.x;
  5750. var yy = quat.y * quat.y;
  5751. var zz = quat.z * quat.z;
  5752. var xy = quat.x * quat.y;
  5753. var zw = quat.z * quat.w;
  5754. var zx = quat.z * quat.x;
  5755. var yw = quat.y * quat.w;
  5756. var yz = quat.y * quat.z;
  5757. var xw = quat.x * quat.w;
  5758. result.m[0] = 1.0 - (2.0 * (yy + zz));
  5759. result.m[1] = 2.0 * (xy + zw);
  5760. result.m[2] = 2.0 * (zx - yw);
  5761. result.m[3] = 0.0;
  5762. result.m[4] = 2.0 * (xy - zw);
  5763. result.m[5] = 1.0 - (2.0 * (zz + xx));
  5764. result.m[6] = 2.0 * (yz + xw);
  5765. result.m[7] = 0.0;
  5766. result.m[8] = 2.0 * (zx + yw);
  5767. result.m[9] = 2.0 * (yz - xw);
  5768. result.m[10] = 1.0 - (2.0 * (yy + xx));
  5769. result.m[11] = 0.0;
  5770. result.m[12] = 0.0;
  5771. result.m[13] = 0.0;
  5772. result.m[14] = 0.0;
  5773. result.m[15] = 1.0;
  5774. result._markAsUpdated();
  5775. };
  5776. Matrix._tempQuaternion = new Quaternion();
  5777. Matrix._xAxis = Vector3.Zero();
  5778. Matrix._yAxis = Vector3.Zero();
  5779. Matrix._zAxis = Vector3.Zero();
  5780. Matrix._updateFlagSeed = 0;
  5781. Matrix._identityReadOnly = Matrix.Identity();
  5782. return Matrix;
  5783. }());
  5784. BABYLON.Matrix = Matrix;
  5785. var Plane = /** @class */ (function () {
  5786. /**
  5787. * Creates a Plane object according to the passed floats a, b, c, d and the plane equation : ax + by + cz + d = 0
  5788. */
  5789. function Plane(a, b, c, d) {
  5790. this.normal = new Vector3(a, b, c);
  5791. this.d = d;
  5792. }
  5793. /**
  5794. * Returns the plane coordinates as a new array of 4 elements [a, b, c, d].
  5795. */
  5796. Plane.prototype.asArray = function () {
  5797. return [this.normal.x, this.normal.y, this.normal.z, this.d];
  5798. };
  5799. // Methods
  5800. /**
  5801. * Returns a new plane copied from the current Plane.
  5802. */
  5803. Plane.prototype.clone = function () {
  5804. return new Plane(this.normal.x, this.normal.y, this.normal.z, this.d);
  5805. };
  5806. /**
  5807. * Returns the string "Plane".
  5808. */
  5809. Plane.prototype.getClassName = function () {
  5810. return "Plane";
  5811. };
  5812. /**
  5813. * Returns the Plane hash code.
  5814. */
  5815. Plane.prototype.getHashCode = function () {
  5816. var hash = this.normal.getHashCode();
  5817. hash = (hash * 397) ^ (this.d || 0);
  5818. return hash;
  5819. };
  5820. /**
  5821. * Normalize the current Plane in place.
  5822. * Returns the updated Plane.
  5823. */
  5824. Plane.prototype.normalize = function () {
  5825. var norm = (Math.sqrt((this.normal.x * this.normal.x) + (this.normal.y * this.normal.y) + (this.normal.z * this.normal.z)));
  5826. var magnitude = 0.0;
  5827. if (norm !== 0) {
  5828. magnitude = 1.0 / norm;
  5829. }
  5830. this.normal.x *= magnitude;
  5831. this.normal.y *= magnitude;
  5832. this.normal.z *= magnitude;
  5833. this.d *= magnitude;
  5834. return this;
  5835. };
  5836. /**
  5837. * Returns a new Plane as the result of the transformation of the current Plane by the passed matrix.
  5838. */
  5839. Plane.prototype.transform = function (transformation) {
  5840. var transposedMatrix = Matrix.Transpose(transformation);
  5841. var x = this.normal.x;
  5842. var y = this.normal.y;
  5843. var z = this.normal.z;
  5844. var d = this.d;
  5845. var normalX = (((x * transposedMatrix.m[0]) + (y * transposedMatrix.m[1])) + (z * transposedMatrix.m[2])) + (d * transposedMatrix.m[3]);
  5846. var normalY = (((x * transposedMatrix.m[4]) + (y * transposedMatrix.m[5])) + (z * transposedMatrix.m[6])) + (d * transposedMatrix.m[7]);
  5847. var normalZ = (((x * transposedMatrix.m[8]) + (y * transposedMatrix.m[9])) + (z * transposedMatrix.m[10])) + (d * transposedMatrix.m[11]);
  5848. var finalD = (((x * transposedMatrix.m[12]) + (y * transposedMatrix.m[13])) + (z * transposedMatrix.m[14])) + (d * transposedMatrix.m[15]);
  5849. return new Plane(normalX, normalY, normalZ, finalD);
  5850. };
  5851. /**
  5852. * Returns the dot product (float) of the point coordinates and the plane normal.
  5853. */
  5854. Plane.prototype.dotCoordinate = function (point) {
  5855. return ((((this.normal.x * point.x) + (this.normal.y * point.y)) + (this.normal.z * point.z)) + this.d);
  5856. };
  5857. /**
  5858. * Updates the current Plane from the plane defined by the three passed points.
  5859. * Returns the updated Plane.
  5860. */
  5861. Plane.prototype.copyFromPoints = function (point1, point2, point3) {
  5862. var x1 = point2.x - point1.x;
  5863. var y1 = point2.y - point1.y;
  5864. var z1 = point2.z - point1.z;
  5865. var x2 = point3.x - point1.x;
  5866. var y2 = point3.y - point1.y;
  5867. var z2 = point3.z - point1.z;
  5868. var yz = (y1 * z2) - (z1 * y2);
  5869. var xz = (z1 * x2) - (x1 * z2);
  5870. var xy = (x1 * y2) - (y1 * x2);
  5871. var pyth = (Math.sqrt((yz * yz) + (xz * xz) + (xy * xy)));
  5872. var invPyth;
  5873. if (pyth !== 0) {
  5874. invPyth = 1.0 / pyth;
  5875. }
  5876. else {
  5877. invPyth = 0.0;
  5878. }
  5879. this.normal.x = yz * invPyth;
  5880. this.normal.y = xz * invPyth;
  5881. this.normal.z = xy * invPyth;
  5882. this.d = -((this.normal.x * point1.x) + (this.normal.y * point1.y) + (this.normal.z * point1.z));
  5883. return this;
  5884. };
  5885. /**
  5886. * Boolean : True is the vector "direction" is the same side than the plane normal.
  5887. */
  5888. Plane.prototype.isFrontFacingTo = function (direction, epsilon) {
  5889. var dot = Vector3.Dot(this.normal, direction);
  5890. return (dot <= epsilon);
  5891. };
  5892. /**
  5893. * Returns the signed distance (float) from the passed point to the Plane.
  5894. */
  5895. Plane.prototype.signedDistanceTo = function (point) {
  5896. return Vector3.Dot(point, this.normal) + this.d;
  5897. };
  5898. // Statics
  5899. /**
  5900. * Returns a new Plane from the passed array.
  5901. */
  5902. Plane.FromArray = function (array) {
  5903. return new Plane(array[0], array[1], array[2], array[3]);
  5904. };
  5905. /**
  5906. * Returns a new Plane defined by the three passed points.
  5907. */
  5908. Plane.FromPoints = function (point1, point2, point3) {
  5909. var result = new Plane(0.0, 0.0, 0.0, 0.0);
  5910. result.copyFromPoints(point1, point2, point3);
  5911. return result;
  5912. };
  5913. /**
  5914. * Returns a new Plane the normal vector to this plane at the passed origin point.
  5915. * Note : the vector "normal" is updated because normalized.
  5916. */
  5917. Plane.FromPositionAndNormal = function (origin, normal) {
  5918. var result = new Plane(0.0, 0.0, 0.0, 0.0);
  5919. normal.normalize();
  5920. result.normal = normal;
  5921. result.d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  5922. return result;
  5923. };
  5924. /**
  5925. * Returns the signed distance between the plane defined by the normal vector at the "origin"" point and the passed other point.
  5926. */
  5927. Plane.SignedDistanceToPlaneFromPositionAndNormal = function (origin, normal, point) {
  5928. var d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  5929. return Vector3.Dot(point, normal) + d;
  5930. };
  5931. return Plane;
  5932. }());
  5933. BABYLON.Plane = Plane;
  5934. var Viewport = /** @class */ (function () {
  5935. /**
  5936. * Creates a Viewport object located at (x, y) and sized (width, height).
  5937. */
  5938. function Viewport(x, y, width, height) {
  5939. this.x = x;
  5940. this.y = y;
  5941. this.width = width;
  5942. this.height = height;
  5943. }
  5944. Viewport.prototype.toGlobal = function (renderWidthOrEngine, renderHeight) {
  5945. if (renderWidthOrEngine.getRenderWidth) {
  5946. var engine = renderWidthOrEngine;
  5947. return this.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  5948. }
  5949. var renderWidth = renderWidthOrEngine;
  5950. return new Viewport(this.x * renderWidth, this.y * renderHeight, this.width * renderWidth, this.height * renderHeight);
  5951. };
  5952. /**
  5953. * Returns a new Viewport copied from the current one.
  5954. */
  5955. Viewport.prototype.clone = function () {
  5956. return new Viewport(this.x, this.y, this.width, this.height);
  5957. };
  5958. return Viewport;
  5959. }());
  5960. BABYLON.Viewport = Viewport;
  5961. var Frustum = /** @class */ (function () {
  5962. function Frustum() {
  5963. }
  5964. /**
  5965. * Returns a new array of 6 Frustum planes computed by the passed transformation matrix.
  5966. */
  5967. Frustum.GetPlanes = function (transform) {
  5968. var frustumPlanes = [];
  5969. for (var index = 0; index < 6; index++) {
  5970. frustumPlanes.push(new Plane(0.0, 0.0, 0.0, 0.0));
  5971. }
  5972. Frustum.GetPlanesToRef(transform, frustumPlanes);
  5973. return frustumPlanes;
  5974. };
  5975. Frustum.GetNearPlaneToRef = function (transform, frustumPlane) {
  5976. frustumPlane.normal.x = transform.m[3] + transform.m[2];
  5977. frustumPlane.normal.y = transform.m[7] + transform.m[6];
  5978. frustumPlane.normal.z = transform.m[11] + transform.m[10];
  5979. frustumPlane.d = transform.m[15] + transform.m[14];
  5980. frustumPlane.normalize();
  5981. };
  5982. Frustum.GetFarPlaneToRef = function (transform, frustumPlane) {
  5983. frustumPlane.normal.x = transform.m[3] - transform.m[2];
  5984. frustumPlane.normal.y = transform.m[7] - transform.m[6];
  5985. frustumPlane.normal.z = transform.m[11] - transform.m[10];
  5986. frustumPlane.d = transform.m[15] - transform.m[14];
  5987. frustumPlane.normalize();
  5988. };
  5989. Frustum.GetLeftPlaneToRef = function (transform, frustumPlane) {
  5990. frustumPlane.normal.x = transform.m[3] + transform.m[0];
  5991. frustumPlane.normal.y = transform.m[7] + transform.m[4];
  5992. frustumPlane.normal.z = transform.m[11] + transform.m[8];
  5993. frustumPlane.d = transform.m[15] + transform.m[12];
  5994. frustumPlane.normalize();
  5995. };
  5996. Frustum.GetRightPlaneToRef = function (transform, frustumPlane) {
  5997. frustumPlane.normal.x = transform.m[3] - transform.m[0];
  5998. frustumPlane.normal.y = transform.m[7] - transform.m[4];
  5999. frustumPlane.normal.z = transform.m[11] - transform.m[8];
  6000. frustumPlane.d = transform.m[15] - transform.m[12];
  6001. frustumPlane.normalize();
  6002. };
  6003. Frustum.GetTopPlaneToRef = function (transform, frustumPlane) {
  6004. frustumPlane.normal.x = transform.m[3] - transform.m[1];
  6005. frustumPlane.normal.y = transform.m[7] - transform.m[5];
  6006. frustumPlane.normal.z = transform.m[11] - transform.m[9];
  6007. frustumPlane.d = transform.m[15] - transform.m[13];
  6008. frustumPlane.normalize();
  6009. };
  6010. Frustum.GetBottomPlaneToRef = function (transform, frustumPlane) {
  6011. frustumPlane.normal.x = transform.m[3] + transform.m[1];
  6012. frustumPlane.normal.y = transform.m[7] + transform.m[5];
  6013. frustumPlane.normal.z = transform.m[11] + transform.m[9];
  6014. frustumPlane.d = transform.m[15] + transform.m[13];
  6015. frustumPlane.normalize();
  6016. };
  6017. /**
  6018. * Sets the passed array "frustumPlanes" with the 6 Frustum planes computed by the passed transformation matrix.
  6019. */
  6020. Frustum.GetPlanesToRef = function (transform, frustumPlanes) {
  6021. // Near
  6022. Frustum.GetNearPlaneToRef(transform, frustumPlanes[0]);
  6023. // Far
  6024. Frustum.GetFarPlaneToRef(transform, frustumPlanes[1]);
  6025. // Left
  6026. Frustum.GetLeftPlaneToRef(transform, frustumPlanes[2]);
  6027. // Right
  6028. Frustum.GetRightPlaneToRef(transform, frustumPlanes[3]);
  6029. // Top
  6030. Frustum.GetTopPlaneToRef(transform, frustumPlanes[4]);
  6031. // Bottom
  6032. Frustum.GetBottomPlaneToRef(transform, frustumPlanes[5]);
  6033. };
  6034. return Frustum;
  6035. }());
  6036. BABYLON.Frustum = Frustum;
  6037. var Space;
  6038. (function (Space) {
  6039. Space[Space["LOCAL"] = 0] = "LOCAL";
  6040. Space[Space["WORLD"] = 1] = "WORLD";
  6041. Space[Space["BONE"] = 2] = "BONE";
  6042. })(Space = BABYLON.Space || (BABYLON.Space = {}));
  6043. var Axis = /** @class */ (function () {
  6044. function Axis() {
  6045. }
  6046. Axis.X = new Vector3(1.0, 0.0, 0.0);
  6047. Axis.Y = new Vector3(0.0, 1.0, 0.0);
  6048. Axis.Z = new Vector3(0.0, 0.0, 1.0);
  6049. return Axis;
  6050. }());
  6051. BABYLON.Axis = Axis;
  6052. ;
  6053. var BezierCurve = /** @class */ (function () {
  6054. function BezierCurve() {
  6055. }
  6056. /**
  6057. * Returns the cubic Bezier interpolated value (float) at "t" (float) from the passed x1, y1, x2, y2 floats.
  6058. */
  6059. BezierCurve.interpolate = function (t, x1, y1, x2, y2) {
  6060. // Extract X (which is equal to time here)
  6061. var f0 = 1 - 3 * x2 + 3 * x1;
  6062. var f1 = 3 * x2 - 6 * x1;
  6063. var f2 = 3 * x1;
  6064. var refinedT = t;
  6065. for (var i = 0; i < 5; i++) {
  6066. var refinedT2 = refinedT * refinedT;
  6067. var refinedT3 = refinedT2 * refinedT;
  6068. var x = f0 * refinedT3 + f1 * refinedT2 + f2 * refinedT;
  6069. var slope = 1.0 / (3.0 * f0 * refinedT2 + 2.0 * f1 * refinedT + f2);
  6070. refinedT -= (x - t) * slope;
  6071. refinedT = Math.min(1, Math.max(0, refinedT));
  6072. }
  6073. // Resolve cubic bezier for the given x
  6074. return 3 * Math.pow(1 - refinedT, 2) * refinedT * y1 +
  6075. 3 * (1 - refinedT) * Math.pow(refinedT, 2) * y2 +
  6076. Math.pow(refinedT, 3);
  6077. };
  6078. return BezierCurve;
  6079. }());
  6080. BABYLON.BezierCurve = BezierCurve;
  6081. var Orientation;
  6082. (function (Orientation) {
  6083. Orientation[Orientation["CW"] = 0] = "CW";
  6084. Orientation[Orientation["CCW"] = 1] = "CCW";
  6085. })(Orientation = BABYLON.Orientation || (BABYLON.Orientation = {}));
  6086. var Angle = /** @class */ (function () {
  6087. /**
  6088. * Creates an Angle object of "radians" radians (float).
  6089. */
  6090. function Angle(radians) {
  6091. var _this = this;
  6092. /**
  6093. * Returns the Angle value in degrees (float).
  6094. */
  6095. this.degrees = function () { return _this._radians * 180.0 / Math.PI; };
  6096. /**
  6097. * Returns the Angle value in radians (float).
  6098. */
  6099. this.radians = function () { return _this._radians; };
  6100. this._radians = radians;
  6101. if (this._radians < 0.0)
  6102. this._radians += (2.0 * Math.PI);
  6103. }
  6104. /**
  6105. * Returns a new Angle object valued with the angle value in radians between the two passed vectors.
  6106. */
  6107. Angle.BetweenTwoPoints = function (a, b) {
  6108. var delta = b.subtract(a);
  6109. var theta = Math.atan2(delta.y, delta.x);
  6110. return new Angle(theta);
  6111. };
  6112. /**
  6113. * Returns a new Angle object from the passed float in radians.
  6114. */
  6115. Angle.FromRadians = function (radians) {
  6116. return new Angle(radians);
  6117. };
  6118. /**
  6119. * Returns a new Angle object from the passed float in degrees.
  6120. */
  6121. Angle.FromDegrees = function (degrees) {
  6122. return new Angle(degrees * Math.PI / 180.0);
  6123. };
  6124. return Angle;
  6125. }());
  6126. BABYLON.Angle = Angle;
  6127. var Arc2 = /** @class */ (function () {
  6128. /**
  6129. * Creates an Arc object from the three passed points : start, middle and end.
  6130. */
  6131. function Arc2(startPoint, midPoint, endPoint) {
  6132. this.startPoint = startPoint;
  6133. this.midPoint = midPoint;
  6134. this.endPoint = endPoint;
  6135. var temp = Math.pow(midPoint.x, 2) + Math.pow(midPoint.y, 2);
  6136. var startToMid = (Math.pow(startPoint.x, 2) + Math.pow(startPoint.y, 2) - temp) / 2.;
  6137. var midToEnd = (temp - Math.pow(endPoint.x, 2) - Math.pow(endPoint.y, 2)) / 2.;
  6138. var det = (startPoint.x - midPoint.x) * (midPoint.y - endPoint.y) - (midPoint.x - endPoint.x) * (startPoint.y - midPoint.y);
  6139. this.centerPoint = new Vector2((startToMid * (midPoint.y - endPoint.y) - midToEnd * (startPoint.y - midPoint.y)) / det, ((startPoint.x - midPoint.x) * midToEnd - (midPoint.x - endPoint.x) * startToMid) / det);
  6140. this.radius = this.centerPoint.subtract(this.startPoint).length();
  6141. this.startAngle = Angle.BetweenTwoPoints(this.centerPoint, this.startPoint);
  6142. var a1 = this.startAngle.degrees();
  6143. var a2 = Angle.BetweenTwoPoints(this.centerPoint, this.midPoint).degrees();
  6144. var a3 = Angle.BetweenTwoPoints(this.centerPoint, this.endPoint).degrees();
  6145. // angles correction
  6146. if (a2 - a1 > +180.0)
  6147. a2 -= 360.0;
  6148. if (a2 - a1 < -180.0)
  6149. a2 += 360.0;
  6150. if (a3 - a2 > +180.0)
  6151. a3 -= 360.0;
  6152. if (a3 - a2 < -180.0)
  6153. a3 += 360.0;
  6154. this.orientation = (a2 - a1) < 0 ? Orientation.CW : Orientation.CCW;
  6155. this.angle = Angle.FromDegrees(this.orientation === Orientation.CW ? a1 - a3 : a3 - a1);
  6156. }
  6157. return Arc2;
  6158. }());
  6159. BABYLON.Arc2 = Arc2;
  6160. var Path2 = /** @class */ (function () {
  6161. /**
  6162. * Creates a Path2 object from the starting 2D coordinates x and y.
  6163. */
  6164. function Path2(x, y) {
  6165. this._points = new Array();
  6166. this._length = 0.0;
  6167. this.closed = false;
  6168. this._points.push(new Vector2(x, y));
  6169. }
  6170. /**
  6171. * Adds a new segment until the passed coordinates (x, y) to the current Path2.
  6172. * Returns the updated Path2.
  6173. */
  6174. Path2.prototype.addLineTo = function (x, y) {
  6175. if (this.closed) {
  6176. //Tools.Error("cannot add lines to closed paths");
  6177. return this;
  6178. }
  6179. var newPoint = new Vector2(x, y);
  6180. var previousPoint = this._points[this._points.length - 1];
  6181. this._points.push(newPoint);
  6182. this._length += newPoint.subtract(previousPoint).length();
  6183. return this;
  6184. };
  6185. /**
  6186. * Adds _numberOfSegments_ segments according to the arc definition (middle point coordinates, end point coordinates, the arc start point being the current Path2 last point) to the current Path2.
  6187. * Returns the updated Path2.
  6188. */
  6189. Path2.prototype.addArcTo = function (midX, midY, endX, endY, numberOfSegments) {
  6190. if (numberOfSegments === void 0) { numberOfSegments = 36; }
  6191. if (this.closed) {
  6192. //Tools.Error("cannot add arcs to closed paths");
  6193. return this;
  6194. }
  6195. var startPoint = this._points[this._points.length - 1];
  6196. var midPoint = new Vector2(midX, midY);
  6197. var endPoint = new Vector2(endX, endY);
  6198. var arc = new Arc2(startPoint, midPoint, endPoint);
  6199. var increment = arc.angle.radians() / numberOfSegments;
  6200. if (arc.orientation === Orientation.CW)
  6201. increment *= -1;
  6202. var currentAngle = arc.startAngle.radians() + increment;
  6203. for (var i = 0; i < numberOfSegments; i++) {
  6204. var x = Math.cos(currentAngle) * arc.radius + arc.centerPoint.x;
  6205. var y = Math.sin(currentAngle) * arc.radius + arc.centerPoint.y;
  6206. this.addLineTo(x, y);
  6207. currentAngle += increment;
  6208. }
  6209. return this;
  6210. };
  6211. /**
  6212. * Closes the Path2.
  6213. * Returns the Path2.
  6214. */
  6215. Path2.prototype.close = function () {
  6216. this.closed = true;
  6217. return this;
  6218. };
  6219. /**
  6220. * Returns the Path2 total length (float).
  6221. */
  6222. Path2.prototype.length = function () {
  6223. var result = this._length;
  6224. if (!this.closed) {
  6225. var lastPoint = this._points[this._points.length - 1];
  6226. var firstPoint = this._points[0];
  6227. result += (firstPoint.subtract(lastPoint).length());
  6228. }
  6229. return result;
  6230. };
  6231. /**
  6232. * Returns the Path2 internal array of points.
  6233. */
  6234. Path2.prototype.getPoints = function () {
  6235. return this._points;
  6236. };
  6237. /**
  6238. * Returns a new Vector2 located at a percentage of the Path2 total length on this path.
  6239. */
  6240. Path2.prototype.getPointAtLengthPosition = function (normalizedLengthPosition) {
  6241. if (normalizedLengthPosition < 0 || normalizedLengthPosition > 1) {
  6242. //Tools.Error("normalized length position should be between 0 and 1.");
  6243. return Vector2.Zero();
  6244. }
  6245. var lengthPosition = normalizedLengthPosition * this.length();
  6246. var previousOffset = 0;
  6247. for (var i = 0; i < this._points.length; i++) {
  6248. var j = (i + 1) % this._points.length;
  6249. var a = this._points[i];
  6250. var b = this._points[j];
  6251. var bToA = b.subtract(a);
  6252. var nextOffset = (bToA.length() + previousOffset);
  6253. if (lengthPosition >= previousOffset && lengthPosition <= nextOffset) {
  6254. var dir = bToA.normalize();
  6255. var localOffset = lengthPosition - previousOffset;
  6256. return new Vector2(a.x + (dir.x * localOffset), a.y + (dir.y * localOffset));
  6257. }
  6258. previousOffset = nextOffset;
  6259. }
  6260. //Tools.Error("internal error");
  6261. return Vector2.Zero();
  6262. };
  6263. /**
  6264. * Returns a new Path2 starting at the coordinates (x, y).
  6265. */
  6266. Path2.StartingAt = function (x, y) {
  6267. return new Path2(x, y);
  6268. };
  6269. return Path2;
  6270. }());
  6271. BABYLON.Path2 = Path2;
  6272. var Path3D = /** @class */ (function () {
  6273. /**
  6274. * new Path3D(path, normal, raw)
  6275. * Creates a Path3D. A Path3D is a logical math object, so not a mesh.
  6276. * please read the description in the tutorial : http://doc.babylonjs.com/tutorials/How_to_use_Path3D
  6277. * path : an array of Vector3, the curve axis of the Path3D
  6278. * normal (optional) : Vector3, the first wanted normal to the curve. Ex (0, 1, 0) for a vertical normal.
  6279. * raw (optional, default false) : boolean, if true the returned Path3D isn't normalized. Useful to depict path acceleration or speed.
  6280. */
  6281. function Path3D(path, firstNormal, raw) {
  6282. if (firstNormal === void 0) { firstNormal = null; }
  6283. this.path = path;
  6284. this._curve = new Array();
  6285. this._distances = new Array();
  6286. this._tangents = new Array();
  6287. this._normals = new Array();
  6288. this._binormals = new Array();
  6289. for (var p = 0; p < path.length; p++) {
  6290. this._curve[p] = path[p].clone(); // hard copy
  6291. }
  6292. this._raw = raw || false;
  6293. this._compute(firstNormal);
  6294. }
  6295. /**
  6296. * Returns the Path3D array of successive Vector3 designing its curve.
  6297. */
  6298. Path3D.prototype.getCurve = function () {
  6299. return this._curve;
  6300. };
  6301. /**
  6302. * Returns an array populated with tangent vectors on each Path3D curve point.
  6303. */
  6304. Path3D.prototype.getTangents = function () {
  6305. return this._tangents;
  6306. };
  6307. /**
  6308. * Returns an array populated with normal vectors on each Path3D curve point.
  6309. */
  6310. Path3D.prototype.getNormals = function () {
  6311. return this._normals;
  6312. };
  6313. /**
  6314. * Returns an array populated with binormal vectors on each Path3D curve point.
  6315. */
  6316. Path3D.prototype.getBinormals = function () {
  6317. return this._binormals;
  6318. };
  6319. /**
  6320. * Returns an array populated with distances (float) of the i-th point from the first curve point.
  6321. */
  6322. Path3D.prototype.getDistances = function () {
  6323. return this._distances;
  6324. };
  6325. /**
  6326. * Forces the Path3D tangent, normal, binormal and distance recomputation.
  6327. * Returns the same object updated.
  6328. */
  6329. Path3D.prototype.update = function (path, firstNormal) {
  6330. if (firstNormal === void 0) { firstNormal = null; }
  6331. for (var p = 0; p < path.length; p++) {
  6332. this._curve[p].x = path[p].x;
  6333. this._curve[p].y = path[p].y;
  6334. this._curve[p].z = path[p].z;
  6335. }
  6336. this._compute(firstNormal);
  6337. return this;
  6338. };
  6339. // private function compute() : computes tangents, normals and binormals
  6340. Path3D.prototype._compute = function (firstNormal) {
  6341. var l = this._curve.length;
  6342. // first and last tangents
  6343. this._tangents[0] = this._getFirstNonNullVector(0);
  6344. if (!this._raw) {
  6345. this._tangents[0].normalize();
  6346. }
  6347. this._tangents[l - 1] = this._curve[l - 1].subtract(this._curve[l - 2]);
  6348. if (!this._raw) {
  6349. this._tangents[l - 1].normalize();
  6350. }
  6351. // normals and binormals at first point : arbitrary vector with _normalVector()
  6352. var tg0 = this._tangents[0];
  6353. var pp0 = this._normalVector(this._curve[0], tg0, firstNormal);
  6354. this._normals[0] = pp0;
  6355. if (!this._raw) {
  6356. this._normals[0].normalize();
  6357. }
  6358. this._binormals[0] = Vector3.Cross(tg0, this._normals[0]);
  6359. if (!this._raw) {
  6360. this._binormals[0].normalize();
  6361. }
  6362. this._distances[0] = 0.0;
  6363. // normals and binormals : next points
  6364. var prev; // previous vector (segment)
  6365. var cur; // current vector (segment)
  6366. var curTang; // current tangent
  6367. // previous normal
  6368. var prevBinor; // previous binormal
  6369. for (var i = 1; i < l; i++) {
  6370. // tangents
  6371. prev = this._getLastNonNullVector(i);
  6372. if (i < l - 1) {
  6373. cur = this._getFirstNonNullVector(i);
  6374. this._tangents[i] = prev.add(cur);
  6375. this._tangents[i].normalize();
  6376. }
  6377. this._distances[i] = this._distances[i - 1] + prev.length();
  6378. // normals and binormals
  6379. // http://www.cs.cmu.edu/afs/andrew/scs/cs/15-462/web/old/asst2camera.html
  6380. curTang = this._tangents[i];
  6381. prevBinor = this._binormals[i - 1];
  6382. this._normals[i] = Vector3.Cross(prevBinor, curTang);
  6383. if (!this._raw) {
  6384. this._normals[i].normalize();
  6385. }
  6386. this._binormals[i] = Vector3.Cross(curTang, this._normals[i]);
  6387. if (!this._raw) {
  6388. this._binormals[i].normalize();
  6389. }
  6390. }
  6391. };
  6392. // private function getFirstNonNullVector(index)
  6393. // returns the first non null vector from index : curve[index + N].subtract(curve[index])
  6394. Path3D.prototype._getFirstNonNullVector = function (index) {
  6395. var i = 1;
  6396. var nNVector = this._curve[index + i].subtract(this._curve[index]);
  6397. while (nNVector.length() === 0 && index + i + 1 < this._curve.length) {
  6398. i++;
  6399. nNVector = this._curve[index + i].subtract(this._curve[index]);
  6400. }
  6401. return nNVector;
  6402. };
  6403. // private function getLastNonNullVector(index)
  6404. // returns the last non null vector from index : curve[index].subtract(curve[index - N])
  6405. Path3D.prototype._getLastNonNullVector = function (index) {
  6406. var i = 1;
  6407. var nLVector = this._curve[index].subtract(this._curve[index - i]);
  6408. while (nLVector.length() === 0 && index > i + 1) {
  6409. i++;
  6410. nLVector = this._curve[index].subtract(this._curve[index - i]);
  6411. }
  6412. return nLVector;
  6413. };
  6414. // private function normalVector(v0, vt, va) :
  6415. // returns an arbitrary point in the plane defined by the point v0 and the vector vt orthogonal to this plane
  6416. // if va is passed, it returns the va projection on the plane orthogonal to vt at the point v0
  6417. Path3D.prototype._normalVector = function (v0, vt, va) {
  6418. var normal0;
  6419. var tgl = vt.length();
  6420. if (tgl === 0.0) {
  6421. tgl = 1.0;
  6422. }
  6423. if (va === undefined || va === null) {
  6424. var point;
  6425. if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.y) / tgl, 1.0, BABYLON.Epsilon)) {
  6426. point = new Vector3(0.0, -1.0, 0.0);
  6427. }
  6428. else if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.x) / tgl, 1.0, BABYLON.Epsilon)) {
  6429. point = new Vector3(1.0, 0.0, 0.0);
  6430. }
  6431. else if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.z) / tgl, 1.0, BABYLON.Epsilon)) {
  6432. point = new Vector3(0.0, 0.0, 1.0);
  6433. }
  6434. else {
  6435. point = Vector3.Zero();
  6436. }
  6437. normal0 = Vector3.Cross(vt, point);
  6438. }
  6439. else {
  6440. normal0 = Vector3.Cross(vt, va);
  6441. Vector3.CrossToRef(normal0, vt, normal0);
  6442. }
  6443. normal0.normalize();
  6444. return normal0;
  6445. };
  6446. return Path3D;
  6447. }());
  6448. BABYLON.Path3D = Path3D;
  6449. var Curve3 = /** @class */ (function () {
  6450. /**
  6451. * A Curve3 object is a logical object, so not a mesh, to handle curves in the 3D geometric space.
  6452. * A Curve3 is designed from a series of successive Vector3.
  6453. * Tuto : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#curve3-object
  6454. */
  6455. function Curve3(points) {
  6456. this._length = 0.0;
  6457. this._points = points;
  6458. this._length = this._computeLength(points);
  6459. }
  6460. /**
  6461. * Returns a Curve3 object along a Quadratic Bezier curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#quadratic-bezier-curve
  6462. * @param v0 (Vector3) the origin point of the Quadratic Bezier
  6463. * @param v1 (Vector3) the control point
  6464. * @param v2 (Vector3) the end point of the Quadratic Bezier
  6465. * @param nbPoints (integer) the wanted number of points in the curve
  6466. */
  6467. Curve3.CreateQuadraticBezier = function (v0, v1, v2, nbPoints) {
  6468. nbPoints = nbPoints > 2 ? nbPoints : 3;
  6469. var bez = new Array();
  6470. var equation = function (t, val0, val1, val2) {
  6471. var res = (1.0 - t) * (1.0 - t) * val0 + 2.0 * t * (1.0 - t) * val1 + t * t * val2;
  6472. return res;
  6473. };
  6474. for (var i = 0; i <= nbPoints; i++) {
  6475. bez.push(new Vector3(equation(i / nbPoints, v0.x, v1.x, v2.x), equation(i / nbPoints, v0.y, v1.y, v2.y), equation(i / nbPoints, v0.z, v1.z, v2.z)));
  6476. }
  6477. return new Curve3(bez);
  6478. };
  6479. /**
  6480. * Returns a Curve3 object along a Cubic Bezier curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#cubic-bezier-curve
  6481. * @param v0 (Vector3) the origin point of the Cubic Bezier
  6482. * @param v1 (Vector3) the first control point
  6483. * @param v2 (Vector3) the second control point
  6484. * @param v3 (Vector3) the end point of the Cubic Bezier
  6485. * @param nbPoints (integer) the wanted number of points in the curve
  6486. */
  6487. Curve3.CreateCubicBezier = function (v0, v1, v2, v3, nbPoints) {
  6488. nbPoints = nbPoints > 3 ? nbPoints : 4;
  6489. var bez = new Array();
  6490. var equation = function (t, val0, val1, val2, val3) {
  6491. var res = (1.0 - t) * (1.0 - t) * (1.0 - t) * val0 + 3.0 * t * (1.0 - t) * (1.0 - t) * val1 + 3.0 * t * t * (1.0 - t) * val2 + t * t * t * val3;
  6492. return res;
  6493. };
  6494. for (var i = 0; i <= nbPoints; i++) {
  6495. bez.push(new Vector3(equation(i / nbPoints, v0.x, v1.x, v2.x, v3.x), equation(i / nbPoints, v0.y, v1.y, v2.y, v3.y), equation(i / nbPoints, v0.z, v1.z, v2.z, v3.z)));
  6496. }
  6497. return new Curve3(bez);
  6498. };
  6499. /**
  6500. * Returns a Curve3 object along a Hermite Spline curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#hermite-spline
  6501. * @param p1 (Vector3) the origin point of the Hermite Spline
  6502. * @param t1 (Vector3) the tangent vector at the origin point
  6503. * @param p2 (Vector3) the end point of the Hermite Spline
  6504. * @param t2 (Vector3) the tangent vector at the end point
  6505. * @param nbPoints (integer) the wanted number of points in the curve
  6506. */
  6507. Curve3.CreateHermiteSpline = function (p1, t1, p2, t2, nbPoints) {
  6508. var hermite = new Array();
  6509. var step = 1.0 / nbPoints;
  6510. for (var i = 0; i <= nbPoints; i++) {
  6511. hermite.push(Vector3.Hermite(p1, t1, p2, t2, i * step));
  6512. }
  6513. return new Curve3(hermite);
  6514. };
  6515. /**
  6516. * Returns a Curve3 object along a CatmullRom Spline curve :
  6517. * @param points (array of Vector3) the points the spline must pass through. At least, four points required.
  6518. * @param nbPoints (integer) the wanted number of points between each curve control points.
  6519. */
  6520. Curve3.CreateCatmullRomSpline = function (points, nbPoints) {
  6521. var totalPoints = new Array();
  6522. totalPoints.push(points[0].clone());
  6523. Array.prototype.push.apply(totalPoints, points);
  6524. totalPoints.push(points[points.length - 1].clone());
  6525. var catmullRom = new Array();
  6526. var step = 1.0 / nbPoints;
  6527. var amount = 0.0;
  6528. for (var i = 0; i < totalPoints.length - 3; i++) {
  6529. amount = 0;
  6530. for (var c = 0; c < nbPoints; c++) {
  6531. catmullRom.push(Vector3.CatmullRom(totalPoints[i], totalPoints[i + 1], totalPoints[i + 2], totalPoints[i + 3], amount));
  6532. amount += step;
  6533. }
  6534. }
  6535. i--;
  6536. catmullRom.push(Vector3.CatmullRom(totalPoints[i], totalPoints[i + 1], totalPoints[i + 2], totalPoints[i + 3], amount));
  6537. return new Curve3(catmullRom);
  6538. };
  6539. /**
  6540. * Returns the Curve3 stored array of successive Vector3
  6541. */
  6542. Curve3.prototype.getPoints = function () {
  6543. return this._points;
  6544. };
  6545. /**
  6546. * Returns the computed length (float) of the curve.
  6547. */
  6548. Curve3.prototype.length = function () {
  6549. return this._length;
  6550. };
  6551. /**
  6552. * Returns a new instance of Curve3 object : var curve = curveA.continue(curveB);
  6553. * This new Curve3 is built by translating and sticking the curveB at the end of the curveA.
  6554. * curveA and curveB keep unchanged.
  6555. */
  6556. Curve3.prototype.continue = function (curve) {
  6557. var lastPoint = this._points[this._points.length - 1];
  6558. var continuedPoints = this._points.slice();
  6559. var curvePoints = curve.getPoints();
  6560. for (var i = 1; i < curvePoints.length; i++) {
  6561. continuedPoints.push(curvePoints[i].subtract(curvePoints[0]).add(lastPoint));
  6562. }
  6563. var continuedCurve = new Curve3(continuedPoints);
  6564. return continuedCurve;
  6565. };
  6566. Curve3.prototype._computeLength = function (path) {
  6567. var l = 0;
  6568. for (var i = 1; i < path.length; i++) {
  6569. l += (path[i].subtract(path[i - 1])).length();
  6570. }
  6571. return l;
  6572. };
  6573. return Curve3;
  6574. }());
  6575. BABYLON.Curve3 = Curve3;
  6576. // Vertex formats
  6577. var PositionNormalVertex = /** @class */ (function () {
  6578. function PositionNormalVertex(position, normal) {
  6579. if (position === void 0) { position = Vector3.Zero(); }
  6580. if (normal === void 0) { normal = Vector3.Up(); }
  6581. this.position = position;
  6582. this.normal = normal;
  6583. }
  6584. PositionNormalVertex.prototype.clone = function () {
  6585. return new PositionNormalVertex(this.position.clone(), this.normal.clone());
  6586. };
  6587. return PositionNormalVertex;
  6588. }());
  6589. BABYLON.PositionNormalVertex = PositionNormalVertex;
  6590. var PositionNormalTextureVertex = /** @class */ (function () {
  6591. function PositionNormalTextureVertex(position, normal, uv) {
  6592. if (position === void 0) { position = Vector3.Zero(); }
  6593. if (normal === void 0) { normal = Vector3.Up(); }
  6594. if (uv === void 0) { uv = Vector2.Zero(); }
  6595. this.position = position;
  6596. this.normal = normal;
  6597. this.uv = uv;
  6598. }
  6599. PositionNormalTextureVertex.prototype.clone = function () {
  6600. return new PositionNormalTextureVertex(this.position.clone(), this.normal.clone(), this.uv.clone());
  6601. };
  6602. return PositionNormalTextureVertex;
  6603. }());
  6604. BABYLON.PositionNormalTextureVertex = PositionNormalTextureVertex;
  6605. // Temporary pre-allocated objects for engine internal use
  6606. // usage in any internal function :
  6607. // var tmp = Tmp.Vector3[0]; <= gets access to the first pre-created Vector3
  6608. // There's a Tmp array per object type : int, float, Vector2, Vector3, Vector4, Quaternion, Matrix
  6609. var Tmp = /** @class */ (function () {
  6610. function Tmp() {
  6611. }
  6612. Tmp.Color3 = [Color3.Black(), Color3.Black(), Color3.Black()];
  6613. Tmp.Vector2 = [Vector2.Zero(), Vector2.Zero(), Vector2.Zero()]; // 3 temp Vector2 at once should be enough
  6614. Tmp.Vector3 = [Vector3.Zero(), Vector3.Zero(), Vector3.Zero(),
  6615. Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero()]; // 9 temp Vector3 at once should be enough
  6616. Tmp.Vector4 = [Vector4.Zero(), Vector4.Zero(), Vector4.Zero()]; // 3 temp Vector4 at once should be enough
  6617. Tmp.Quaternion = [Quaternion.Zero(), Quaternion.Zero()]; // 2 temp Quaternion at once should be enough
  6618. Tmp.Matrix = [Matrix.Zero(), Matrix.Zero(),
  6619. Matrix.Zero(), Matrix.Zero(),
  6620. Matrix.Zero(), Matrix.Zero(),
  6621. Matrix.Zero(), Matrix.Zero()]; // 6 temp Matrices at once should be enough
  6622. return Tmp;
  6623. }());
  6624. BABYLON.Tmp = Tmp;
  6625. // Same as Tmp but not exported to keep it onyl for math functions to avoid conflicts
  6626. var MathTmp = /** @class */ (function () {
  6627. function MathTmp() {
  6628. }
  6629. MathTmp.Vector3 = [Vector3.Zero()];
  6630. MathTmp.Matrix = [Matrix.Zero(), Matrix.Zero()];
  6631. MathTmp.Quaternion = [Quaternion.Zero()];
  6632. return MathTmp;
  6633. }());
  6634. })(BABYLON || (BABYLON = {}));
  6635. //# sourceMappingURL=babylon.math.js.map
  6636. var BABYLON;
  6637. (function (BABYLON) {
  6638. var Scalar = /** @class */ (function () {
  6639. function Scalar() {
  6640. }
  6641. /**
  6642. * Boolean : true if the absolute difference between a and b is lower than epsilon (default = 1.401298E-45)
  6643. */
  6644. Scalar.WithinEpsilon = function (a, b, epsilon) {
  6645. if (epsilon === void 0) { epsilon = 1.401298E-45; }
  6646. var num = a - b;
  6647. return -epsilon <= num && num <= epsilon;
  6648. };
  6649. /**
  6650. * Returns a string : the upper case translation of the number i to hexadecimal.
  6651. */
  6652. Scalar.ToHex = function (i) {
  6653. var str = i.toString(16);
  6654. if (i <= 15) {
  6655. return ("0" + str).toUpperCase();
  6656. }
  6657. return str.toUpperCase();
  6658. };
  6659. /**
  6660. * Returns -1 if value is negative and +1 is value is positive.
  6661. * Returns the value itself if it's equal to zero.
  6662. */
  6663. Scalar.Sign = function (value) {
  6664. value = +value; // convert to a number
  6665. if (value === 0 || isNaN(value))
  6666. return value;
  6667. return value > 0 ? 1 : -1;
  6668. };
  6669. /**
  6670. * Returns the value itself if it's between min and max.
  6671. * Returns min if the value is lower than min.
  6672. * Returns max if the value is greater than max.
  6673. */
  6674. Scalar.Clamp = function (value, min, max) {
  6675. if (min === void 0) { min = 0; }
  6676. if (max === void 0) { max = 1; }
  6677. return Math.min(max, Math.max(min, value));
  6678. };
  6679. /**
  6680. * Returns the log2 of value.
  6681. */
  6682. Scalar.Log2 = function (value) {
  6683. return Math.log(value) * Math.LOG2E;
  6684. };
  6685. /**
  6686. * Loops the value, so that it is never larger than length and never smaller than 0.
  6687. *
  6688. * This is similar to the modulo operator but it works with floating point numbers.
  6689. * For example, using 3.0 for t and 2.5 for length, the result would be 0.5.
  6690. * With t = 5 and length = 2.5, the result would be 0.0.
  6691. * Note, however, that the behaviour is not defined for negative numbers as it is for the modulo operator
  6692. */
  6693. Scalar.Repeat = function (value, length) {
  6694. return value - Math.floor(value / length) * length;
  6695. };
  6696. /**
  6697. * Normalize the value between 0.0 and 1.0 using min and max values
  6698. */
  6699. Scalar.Normalize = function (value, min, max) {
  6700. return (value - min) / (max - min);
  6701. };
  6702. /**
  6703. * Denormalize the value from 0.0 and 1.0 using min and max values
  6704. */
  6705. Scalar.Denormalize = function (normalized, min, max) {
  6706. return (normalized * (max - min) + min);
  6707. };
  6708. /**
  6709. * Calculates the shortest difference between two given angles given in degrees.
  6710. */
  6711. Scalar.DeltaAngle = function (current, target) {
  6712. var num = Scalar.Repeat(target - current, 360.0);
  6713. if (num > 180.0) {
  6714. num -= 360.0;
  6715. }
  6716. return num;
  6717. };
  6718. /**
  6719. * PingPongs the value t, so that it is never larger than length and never smaller than 0.
  6720. *
  6721. * The returned value will move back and forth between 0 and length
  6722. */
  6723. Scalar.PingPong = function (tx, length) {
  6724. var t = Scalar.Repeat(tx, length * 2.0);
  6725. return length - Math.abs(t - length);
  6726. };
  6727. /**
  6728. * Interpolates between min and max with smoothing at the limits.
  6729. *
  6730. * This function interpolates between min and max in a similar way to Lerp. However, the interpolation will gradually speed up
  6731. * from the start and slow down toward the end. This is useful for creating natural-looking animation, fading and other transitions.
  6732. */
  6733. Scalar.SmoothStep = function (from, to, tx) {
  6734. var t = Scalar.Clamp(tx);
  6735. t = -2.0 * t * t * t + 3.0 * t * t;
  6736. return to * t + from * (1.0 - t);
  6737. };
  6738. /**
  6739. * Moves a value current towards target.
  6740. *
  6741. * This is essentially the same as Mathf.Lerp but instead the function will ensure that the speed never exceeds maxDelta.
  6742. * Negative values of maxDelta pushes the value away from target.
  6743. */
  6744. Scalar.MoveTowards = function (current, target, maxDelta) {
  6745. var result = 0;
  6746. if (Math.abs(target - current) <= maxDelta) {
  6747. result = target;
  6748. }
  6749. else {
  6750. result = current + Scalar.Sign(target - current) * maxDelta;
  6751. }
  6752. return result;
  6753. };
  6754. /**
  6755. * Same as MoveTowards but makes sure the values interpolate correctly when they wrap around 360 degrees.
  6756. *
  6757. * Variables current and target are assumed to be in degrees. For optimization reasons, negative values of maxDelta
  6758. * are not supported and may cause oscillation. To push current away from a target angle, add 180 to that angle instead.
  6759. */
  6760. Scalar.MoveTowardsAngle = function (current, target, maxDelta) {
  6761. var num = Scalar.DeltaAngle(current, target);
  6762. var result = 0;
  6763. if (-maxDelta < num && num < maxDelta) {
  6764. result = target;
  6765. }
  6766. else {
  6767. target = current + num;
  6768. result = Scalar.MoveTowards(current, target, maxDelta);
  6769. }
  6770. return result;
  6771. };
  6772. /**
  6773. * Creates a new scalar with values linearly interpolated of "amount" between the start scalar and the end scalar.
  6774. */
  6775. Scalar.Lerp = function (start, end, amount) {
  6776. return start + ((end - start) * amount);
  6777. };
  6778. /**
  6779. * Same as Lerp but makes sure the values interpolate correctly when they wrap around 360 degrees.
  6780. * The parameter t is clamped to the range [0, 1]. Variables a and b are assumed to be in degrees.
  6781. */
  6782. Scalar.LerpAngle = function (start, end, amount) {
  6783. var num = Scalar.Repeat(end - start, 360.0);
  6784. if (num > 180.0) {
  6785. num -= 360.0;
  6786. }
  6787. return start + num * Scalar.Clamp(amount);
  6788. };
  6789. /**
  6790. * Calculates the linear parameter t that produces the interpolant value within the range [a, b].
  6791. */
  6792. Scalar.InverseLerp = function (a, b, value) {
  6793. var result = 0;
  6794. if (a != b) {
  6795. result = Scalar.Clamp((value - a) / (b - a));
  6796. }
  6797. else {
  6798. result = 0.0;
  6799. }
  6800. return result;
  6801. };
  6802. /**
  6803. * Returns a new scalar located for "amount" (float) on the Hermite spline defined by the scalars "value1", "value3", "tangent1", "tangent2".
  6804. */
  6805. Scalar.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  6806. var squared = amount * amount;
  6807. var cubed = amount * squared;
  6808. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  6809. var part2 = (-2.0 * cubed) + (3.0 * squared);
  6810. var part3 = (cubed - (2.0 * squared)) + amount;
  6811. var part4 = cubed - squared;
  6812. return (((value1 * part1) + (value2 * part2)) + (tangent1 * part3)) + (tangent2 * part4);
  6813. };
  6814. /**
  6815. * Returns a random float number between and min and max values
  6816. */
  6817. Scalar.RandomRange = function (min, max) {
  6818. if (min === max)
  6819. return min;
  6820. return ((Math.random() * (max - min)) + min);
  6821. };
  6822. /**
  6823. * This function returns percentage of a number in a given range.
  6824. *
  6825. * RangeToPercent(40,20,60) will return 0.5 (50%)
  6826. * RangeToPercent(34,0,100) will return 0.34 (34%)
  6827. */
  6828. Scalar.RangeToPercent = function (number, min, max) {
  6829. return ((number - min) / (max - min));
  6830. };
  6831. /**
  6832. * This function returns number that corresponds to the percentage in a given range.
  6833. *
  6834. * PercentToRange(0.34,0,100) will return 34.
  6835. */
  6836. Scalar.PercentToRange = function (percent, min, max) {
  6837. return ((max - min) * percent + min);
  6838. };
  6839. /**
  6840. * Returns the angle converted to equivalent value between -Math.PI and Math.PI radians.
  6841. * @param angle The angle to normalize in radian.
  6842. * @return The converted angle.
  6843. */
  6844. Scalar.NormalizeRadians = function (angle) {
  6845. // More precise but slower version kept for reference.
  6846. // angle = angle % Tools.TwoPi;
  6847. // angle = (angle + Tools.TwoPi) % Tools.TwoPi;
  6848. //if (angle > Math.PI) {
  6849. // angle -= Tools.TwoPi;
  6850. //}
  6851. angle -= (Scalar.TwoPi * Math.floor((angle + Math.PI) / Scalar.TwoPi));
  6852. return angle;
  6853. };
  6854. /**
  6855. * Two pi constants convenient for computation.
  6856. */
  6857. Scalar.TwoPi = Math.PI * 2;
  6858. return Scalar;
  6859. }());
  6860. BABYLON.Scalar = Scalar;
  6861. })(BABYLON || (BABYLON = {}));
  6862. //# sourceMappingURL=babylon.math.scalar.js.map
  6863. //# sourceMappingURL=babylon.mixins.js.map
  6864. // Type definitions for WebGL 2, Editor's Draft Fri Feb 24 16:10:18 2017 -0800
  6865. // Project: https://www.khronos.org/registry/webgl/specs/latest/2.0/
  6866. // Definitions by: Nico Kemnitz <https://github.com/nkemnitz/>
  6867. // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
  6868. //# sourceMappingURL=babylon.webgl2.js.map
  6869. var BABYLON;
  6870. (function (BABYLON) {
  6871. var __decoratorInitialStore = {};
  6872. var __mergedStore = {};
  6873. var _copySource = function (creationFunction, source, instanciate) {
  6874. var destination = creationFunction();
  6875. // Tags
  6876. if (BABYLON.Tags) {
  6877. BABYLON.Tags.AddTagsTo(destination, source.tags);
  6878. }
  6879. var classStore = getMergedStore(destination);
  6880. // Properties
  6881. for (var property in classStore) {
  6882. var propertyDescriptor = classStore[property];
  6883. var sourceProperty = source[property];
  6884. var propertyType = propertyDescriptor.type;
  6885. if (sourceProperty !== undefined && sourceProperty !== null) {
  6886. switch (propertyType) {
  6887. case 0: // Value
  6888. case 6:// Mesh reference
  6889. destination[property] = sourceProperty;
  6890. break;
  6891. case 1:// Texture
  6892. destination[property] = (instanciate || sourceProperty.isRenderTarget) ? sourceProperty : sourceProperty.clone();
  6893. break;
  6894. case 2: // Color3
  6895. case 3: // FresnelParameters
  6896. case 4: // Vector2
  6897. case 5: // Vector3
  6898. case 7: // Color Curves
  6899. case 10:// Quaternion
  6900. destination[property] = instanciate ? sourceProperty : sourceProperty.clone();
  6901. break;
  6902. }
  6903. }
  6904. }
  6905. return destination;
  6906. };
  6907. function getDirectStore(target) {
  6908. var classKey = target.getClassName();
  6909. if (!__decoratorInitialStore[classKey]) {
  6910. __decoratorInitialStore[classKey] = {};
  6911. }
  6912. return __decoratorInitialStore[classKey];
  6913. }
  6914. /**
  6915. * Return the list of properties flagged as serializable
  6916. * @param target: host object
  6917. */
  6918. function getMergedStore(target) {
  6919. var classKey = target.getClassName();
  6920. if (__mergedStore[classKey]) {
  6921. return __mergedStore[classKey];
  6922. }
  6923. __mergedStore[classKey] = {};
  6924. var store = __mergedStore[classKey];
  6925. var currentTarget = target;
  6926. var currentKey = classKey;
  6927. while (currentKey) {
  6928. var initialStore = __decoratorInitialStore[currentKey];
  6929. for (var property in initialStore) {
  6930. store[property] = initialStore[property];
  6931. }
  6932. var parent_1 = void 0;
  6933. var done = false;
  6934. do {
  6935. parent_1 = Object.getPrototypeOf(currentTarget);
  6936. if (!parent_1.getClassName) {
  6937. done = true;
  6938. break;
  6939. }
  6940. if (parent_1.getClassName() !== currentKey) {
  6941. break;
  6942. }
  6943. currentTarget = parent_1;
  6944. } while (parent_1);
  6945. if (done) {
  6946. break;
  6947. }
  6948. currentKey = parent_1.getClassName();
  6949. currentTarget = parent_1;
  6950. }
  6951. return store;
  6952. }
  6953. function generateSerializableMember(type, sourceName) {
  6954. return function (target, propertyKey) {
  6955. var classStore = getDirectStore(target);
  6956. if (!classStore[propertyKey]) {
  6957. classStore[propertyKey] = { type: type, sourceName: sourceName };
  6958. }
  6959. };
  6960. }
  6961. function generateExpandMember(setCallback, targetKey) {
  6962. if (targetKey === void 0) { targetKey = null; }
  6963. return function (target, propertyKey) {
  6964. var key = targetKey || ("_" + propertyKey);
  6965. Object.defineProperty(target, propertyKey, {
  6966. get: function () {
  6967. return this[key];
  6968. },
  6969. set: function (value) {
  6970. if (this[key] === value) {
  6971. return;
  6972. }
  6973. this[key] = value;
  6974. target[setCallback].apply(this);
  6975. },
  6976. enumerable: true,
  6977. configurable: true
  6978. });
  6979. };
  6980. }
  6981. function expandToProperty(callback, targetKey) {
  6982. if (targetKey === void 0) { targetKey = null; }
  6983. return generateExpandMember(callback, targetKey);
  6984. }
  6985. BABYLON.expandToProperty = expandToProperty;
  6986. function serialize(sourceName) {
  6987. return generateSerializableMember(0, sourceName); // value member
  6988. }
  6989. BABYLON.serialize = serialize;
  6990. function serializeAsTexture(sourceName) {
  6991. return generateSerializableMember(1, sourceName); // texture member
  6992. }
  6993. BABYLON.serializeAsTexture = serializeAsTexture;
  6994. function serializeAsColor3(sourceName) {
  6995. return generateSerializableMember(2, sourceName); // color3 member
  6996. }
  6997. BABYLON.serializeAsColor3 = serializeAsColor3;
  6998. function serializeAsFresnelParameters(sourceName) {
  6999. return generateSerializableMember(3, sourceName); // fresnel parameters member
  7000. }
  7001. BABYLON.serializeAsFresnelParameters = serializeAsFresnelParameters;
  7002. function serializeAsVector2(sourceName) {
  7003. return generateSerializableMember(4, sourceName); // vector2 member
  7004. }
  7005. BABYLON.serializeAsVector2 = serializeAsVector2;
  7006. function serializeAsVector3(sourceName) {
  7007. return generateSerializableMember(5, sourceName); // vector3 member
  7008. }
  7009. BABYLON.serializeAsVector3 = serializeAsVector3;
  7010. function serializeAsMeshReference(sourceName) {
  7011. return generateSerializableMember(6, sourceName); // mesh reference member
  7012. }
  7013. BABYLON.serializeAsMeshReference = serializeAsMeshReference;
  7014. function serializeAsColorCurves(sourceName) {
  7015. return generateSerializableMember(7, sourceName); // color curves
  7016. }
  7017. BABYLON.serializeAsColorCurves = serializeAsColorCurves;
  7018. function serializeAsColor4(sourceName) {
  7019. return generateSerializableMember(8, sourceName); // color 4
  7020. }
  7021. BABYLON.serializeAsColor4 = serializeAsColor4;
  7022. function serializeAsImageProcessingConfiguration(sourceName) {
  7023. return generateSerializableMember(9, sourceName); // image processing
  7024. }
  7025. BABYLON.serializeAsImageProcessingConfiguration = serializeAsImageProcessingConfiguration;
  7026. function serializeAsQuaternion(sourceName) {
  7027. return generateSerializableMember(10, sourceName); // quaternion member
  7028. }
  7029. BABYLON.serializeAsQuaternion = serializeAsQuaternion;
  7030. var SerializationHelper = /** @class */ (function () {
  7031. function SerializationHelper() {
  7032. }
  7033. SerializationHelper.Serialize = function (entity, serializationObject) {
  7034. if (!serializationObject) {
  7035. serializationObject = {};
  7036. }
  7037. // Tags
  7038. if (BABYLON.Tags) {
  7039. serializationObject.tags = BABYLON.Tags.GetTags(entity);
  7040. }
  7041. var serializedProperties = getMergedStore(entity);
  7042. // Properties
  7043. for (var property in serializedProperties) {
  7044. var propertyDescriptor = serializedProperties[property];
  7045. var targetPropertyName = propertyDescriptor.sourceName || property;
  7046. var propertyType = propertyDescriptor.type;
  7047. var sourceProperty = entity[property];
  7048. if (sourceProperty !== undefined && sourceProperty !== null) {
  7049. switch (propertyType) {
  7050. case 0:// Value
  7051. serializationObject[targetPropertyName] = sourceProperty;
  7052. break;
  7053. case 1:// Texture
  7054. serializationObject[targetPropertyName] = sourceProperty.serialize();
  7055. break;
  7056. case 2:// Color3
  7057. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7058. break;
  7059. case 3:// FresnelParameters
  7060. serializationObject[targetPropertyName] = sourceProperty.serialize();
  7061. break;
  7062. case 4:// Vector2
  7063. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7064. break;
  7065. case 5:// Vector3
  7066. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7067. break;
  7068. case 6:// Mesh reference
  7069. serializationObject[targetPropertyName] = sourceProperty.id;
  7070. break;
  7071. case 7:// Color Curves
  7072. serializationObject[targetPropertyName] = sourceProperty.serialize();
  7073. break;
  7074. case 8:// Color 4
  7075. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7076. break;
  7077. case 9:// Image Processing
  7078. serializationObject[targetPropertyName] = sourceProperty.serialize();
  7079. break;
  7080. }
  7081. }
  7082. }
  7083. return serializationObject;
  7084. };
  7085. SerializationHelper.Parse = function (creationFunction, source, scene, rootUrl) {
  7086. if (rootUrl === void 0) { rootUrl = null; }
  7087. var destination = creationFunction();
  7088. if (!rootUrl) {
  7089. rootUrl = "";
  7090. }
  7091. // Tags
  7092. if (BABYLON.Tags) {
  7093. BABYLON.Tags.AddTagsTo(destination, source.tags);
  7094. }
  7095. var classStore = getMergedStore(destination);
  7096. // Properties
  7097. for (var property in classStore) {
  7098. var propertyDescriptor = classStore[property];
  7099. var sourceProperty = source[propertyDescriptor.sourceName || property];
  7100. var propertyType = propertyDescriptor.type;
  7101. if (sourceProperty !== undefined && sourceProperty !== null) {
  7102. var dest = destination;
  7103. switch (propertyType) {
  7104. case 0:// Value
  7105. dest[property] = sourceProperty;
  7106. break;
  7107. case 1:// Texture
  7108. if (scene) {
  7109. dest[property] = BABYLON.Texture.Parse(sourceProperty, scene, rootUrl);
  7110. }
  7111. break;
  7112. case 2:// Color3
  7113. dest[property] = BABYLON.Color3.FromArray(sourceProperty);
  7114. break;
  7115. case 3:// FresnelParameters
  7116. dest[property] = BABYLON.FresnelParameters.Parse(sourceProperty);
  7117. break;
  7118. case 4:// Vector2
  7119. dest[property] = BABYLON.Vector2.FromArray(sourceProperty);
  7120. break;
  7121. case 5:// Vector3
  7122. dest[property] = BABYLON.Vector3.FromArray(sourceProperty);
  7123. break;
  7124. case 6:// Mesh reference
  7125. if (scene) {
  7126. dest[property] = scene.getLastMeshByID(sourceProperty);
  7127. }
  7128. break;
  7129. case 7:// Color Curves
  7130. dest[property] = BABYLON.ColorCurves.Parse(sourceProperty);
  7131. break;
  7132. case 8:// Color 4
  7133. dest[property] = BABYLON.Color4.FromArray(sourceProperty);
  7134. break;
  7135. case 9:// Image Processing
  7136. dest[property] = BABYLON.ImageProcessingConfiguration.Parse(sourceProperty);
  7137. break;
  7138. }
  7139. }
  7140. }
  7141. return destination;
  7142. };
  7143. SerializationHelper.Clone = function (creationFunction, source) {
  7144. return _copySource(creationFunction, source, false);
  7145. };
  7146. SerializationHelper.Instanciate = function (creationFunction, source) {
  7147. return _copySource(creationFunction, source, true);
  7148. };
  7149. return SerializationHelper;
  7150. }());
  7151. BABYLON.SerializationHelper = SerializationHelper;
  7152. })(BABYLON || (BABYLON = {}));
  7153. //# sourceMappingURL=babylon.decorators.js.map
  7154. var BABYLON;
  7155. (function (BABYLON) {
  7156. /**
  7157. * Wrapper class for promise with external resolve and reject.
  7158. */
  7159. var Deferred = /** @class */ (function () {
  7160. /**
  7161. * Constructor for this deferred object.
  7162. */
  7163. function Deferred() {
  7164. var _this = this;
  7165. this.promise = new Promise(function (resolve, reject) {
  7166. _this._resolve = resolve;
  7167. _this._reject = reject;
  7168. });
  7169. }
  7170. Object.defineProperty(Deferred.prototype, "resolve", {
  7171. /**
  7172. * The resolve method of the promise associated with this deferred object.
  7173. */
  7174. get: function () {
  7175. return this._resolve;
  7176. },
  7177. enumerable: true,
  7178. configurable: true
  7179. });
  7180. Object.defineProperty(Deferred.prototype, "reject", {
  7181. /**
  7182. * The reject method of the promise associated with this deferred object.
  7183. */
  7184. get: function () {
  7185. return this._reject;
  7186. },
  7187. enumerable: true,
  7188. configurable: true
  7189. });
  7190. return Deferred;
  7191. }());
  7192. BABYLON.Deferred = Deferred;
  7193. })(BABYLON || (BABYLON = {}));
  7194. //# sourceMappingURL=babylon.deferred.js.map
  7195. var BABYLON;
  7196. (function (BABYLON) {
  7197. /**
  7198. * A class serves as a medium between the observable and its observers
  7199. */
  7200. var EventState = /** @class */ (function () {
  7201. /**
  7202. * Create a new EventState
  7203. * @param mask defines the mask associated with this state
  7204. * @param skipNextObservers defines a flag which will instruct the observable to skip following observers when set to true
  7205. * @param target defines the original target of the state
  7206. * @param currentTarget defines the current target of the state
  7207. */
  7208. function EventState(mask, skipNextObservers, target, currentTarget) {
  7209. if (skipNextObservers === void 0) { skipNextObservers = false; }
  7210. this.initalize(mask, skipNextObservers, target, currentTarget);
  7211. }
  7212. /**
  7213. * Initialize the current event state
  7214. * @param mask defines the mask associated with this state
  7215. * @param skipNextObservers defines a flag which will instruct the observable to skip following observers when set to true
  7216. * @param target defines the original target of the state
  7217. * @param currentTarget defines the current target of the state
  7218. * @returns the current event state
  7219. */
  7220. EventState.prototype.initalize = function (mask, skipNextObservers, target, currentTarget) {
  7221. if (skipNextObservers === void 0) { skipNextObservers = false; }
  7222. this.mask = mask;
  7223. this.skipNextObservers = skipNextObservers;
  7224. this.target = target;
  7225. this.currentTarget = currentTarget;
  7226. return this;
  7227. };
  7228. return EventState;
  7229. }());
  7230. BABYLON.EventState = EventState;
  7231. /**
  7232. * Represent an Observer registered to a given Observable object.
  7233. */
  7234. var Observer = /** @class */ (function () {
  7235. /**
  7236. * Creates a new observer
  7237. * @param callback defines the callback to call when the observer is notified
  7238. * @param mask defines the mask of the observer (used to filter notifications)
  7239. * @param scope defines the current scope used to restore the JS context
  7240. */
  7241. function Observer(
  7242. /**
  7243. * Defines the callback to call when the observer is notified
  7244. */
  7245. callback,
  7246. /**
  7247. * Defines the mask of the observer (used to filter notifications)
  7248. */
  7249. mask,
  7250. /**
  7251. * Defines the current scope used to restore the JS context
  7252. */
  7253. scope) {
  7254. if (scope === void 0) { scope = null; }
  7255. this.callback = callback;
  7256. this.mask = mask;
  7257. this.scope = scope;
  7258. /** @ignore */
  7259. this._willBeUnregistered = false;
  7260. /**
  7261. * Gets or sets a property defining that the observer as to be unregistered after the next notification
  7262. */
  7263. this.unregisterOnNextCall = false;
  7264. }
  7265. return Observer;
  7266. }());
  7267. BABYLON.Observer = Observer;
  7268. /**
  7269. * Represent a list of observers registered to multiple Observables object.
  7270. */
  7271. var MultiObserver = /** @class */ (function () {
  7272. function MultiObserver() {
  7273. }
  7274. /**
  7275. * Release associated resources
  7276. */
  7277. MultiObserver.prototype.dispose = function () {
  7278. if (this._observers && this._observables) {
  7279. for (var index = 0; index < this._observers.length; index++) {
  7280. this._observables[index].remove(this._observers[index]);
  7281. }
  7282. }
  7283. this._observers = null;
  7284. this._observables = null;
  7285. };
  7286. /**
  7287. * Raise a callback when one of the observable will notify
  7288. * @param observables defines a list of observables to watch
  7289. * @param callback defines the callback to call on notification
  7290. * @param mask defines the mask used to filter notifications
  7291. * @param scope defines the current scope used to restore the JS context
  7292. * @returns the new MultiObserver
  7293. */
  7294. MultiObserver.Watch = function (observables, callback, mask, scope) {
  7295. if (mask === void 0) { mask = -1; }
  7296. if (scope === void 0) { scope = null; }
  7297. var result = new MultiObserver();
  7298. result._observers = new Array();
  7299. result._observables = observables;
  7300. for (var _i = 0, observables_1 = observables; _i < observables_1.length; _i++) {
  7301. var observable = observables_1[_i];
  7302. var observer = observable.add(callback, mask, false, scope);
  7303. if (observer) {
  7304. result._observers.push(observer);
  7305. }
  7306. }
  7307. return result;
  7308. };
  7309. return MultiObserver;
  7310. }());
  7311. BABYLON.MultiObserver = MultiObserver;
  7312. /**
  7313. * The Observable class is a simple implementation of the Observable pattern.
  7314. * There's one slight particularity though: a given Observable can notify its observer using a particular mask value, only the Observers registered with this mask value will be notified.
  7315. * This enable a more fine grained execution without having to rely on multiple different Observable objects.
  7316. * For instance you may have a given Observable that have four different types of notifications: Move (mask = 0x01), Stop (mask = 0x02), Turn Right (mask = 0X04), Turn Left (mask = 0X08).
  7317. * A given observer can register itself with only Move and Stop (mask = 0x03), then it will only be notified when one of these two occurs and will never be for Turn Left/Right.
  7318. */
  7319. var Observable = /** @class */ (function () {
  7320. /**
  7321. * Creates a new observable
  7322. * @param onObserverAdded defines a callback to call when a new observer is added
  7323. */
  7324. function Observable(onObserverAdded) {
  7325. this._observers = new Array();
  7326. this._eventState = new EventState(0);
  7327. if (onObserverAdded) {
  7328. this._onObserverAdded = onObserverAdded;
  7329. }
  7330. }
  7331. /**
  7332. * Create a new Observer with the specified callback
  7333. * @param callback the callback that will be executed for that Observer
  7334. * @param mask the mask used to filter observers
  7335. * @param insertFirst if true the callback will be inserted at the first position, hence executed before the others ones. If false (default behavior) the callback will be inserted at the last position, executed after all the others already present.
  7336. * @param scope optional scope for the callback to be called from
  7337. * @param unregisterOnFirstCall defines if the observer as to be unregistered after the next notification
  7338. * @returns the new observer created for the callback
  7339. */
  7340. Observable.prototype.add = function (callback, mask, insertFirst, scope, unregisterOnFirstCall) {
  7341. if (mask === void 0) { mask = -1; }
  7342. if (insertFirst === void 0) { insertFirst = false; }
  7343. if (scope === void 0) { scope = null; }
  7344. if (unregisterOnFirstCall === void 0) { unregisterOnFirstCall = false; }
  7345. if (!callback) {
  7346. return null;
  7347. }
  7348. var observer = new Observer(callback, mask, scope);
  7349. observer.unregisterOnNextCall = unregisterOnFirstCall;
  7350. if (insertFirst) {
  7351. this._observers.unshift(observer);
  7352. }
  7353. else {
  7354. this._observers.push(observer);
  7355. }
  7356. if (this._onObserverAdded) {
  7357. this._onObserverAdded(observer);
  7358. }
  7359. return observer;
  7360. };
  7361. /**
  7362. * Remove an Observer from the Observable object
  7363. * @param observer the instance of the Observer to remove
  7364. * @returns false if it doesn't belong to this Observable
  7365. */
  7366. Observable.prototype.remove = function (observer) {
  7367. if (!observer) {
  7368. return false;
  7369. }
  7370. var index = this._observers.indexOf(observer);
  7371. if (index !== -1) {
  7372. this._observers.splice(index, 1);
  7373. return true;
  7374. }
  7375. return false;
  7376. };
  7377. /**
  7378. * Remove a callback from the Observable object
  7379. * @param callback the callback to remove
  7380. * @param scope optional scope. If used only the callbacks with this scope will be removed
  7381. * @returns false if it doesn't belong to this Observable
  7382. */
  7383. Observable.prototype.removeCallback = function (callback, scope) {
  7384. for (var index = 0; index < this._observers.length; index++) {
  7385. if (this._observers[index].callback === callback && (!scope || scope === this._observers[index].scope)) {
  7386. this._observers.splice(index, 1);
  7387. return true;
  7388. }
  7389. }
  7390. return false;
  7391. };
  7392. Observable.prototype._deferUnregister = function (observer) {
  7393. var _this = this;
  7394. observer.unregisterOnNextCall = false;
  7395. observer._willBeUnregistered = true;
  7396. BABYLON.Tools.SetImmediate(function () {
  7397. _this.remove(observer);
  7398. });
  7399. };
  7400. /**
  7401. * Notify all Observers by calling their respective callback with the given data
  7402. * Will return true if all observers were executed, false if an observer set skipNextObservers to true, then prevent the subsequent ones to execute
  7403. * @param eventData defines the data to send to all observers
  7404. * @param mask defines the mask of the current notification (observers with incompatible mask (ie mask & observer.mask === 0) will not be notified)
  7405. * @param target defines the original target of the state
  7406. * @param currentTarget defines the current target of the state
  7407. * @returns false if the complete observer chain was not processed (because one observer set the skipNextObservers to true)
  7408. */
  7409. Observable.prototype.notifyObservers = function (eventData, mask, target, currentTarget) {
  7410. if (mask === void 0) { mask = -1; }
  7411. if (!this._observers.length) {
  7412. return true;
  7413. }
  7414. var state = this._eventState;
  7415. state.mask = mask;
  7416. state.target = target;
  7417. state.currentTarget = currentTarget;
  7418. state.skipNextObservers = false;
  7419. state.lastReturnValue = eventData;
  7420. for (var _i = 0, _a = this._observers; _i < _a.length; _i++) {
  7421. var obs = _a[_i];
  7422. if (obs._willBeUnregistered) {
  7423. continue;
  7424. }
  7425. if (obs.mask & mask) {
  7426. if (obs.scope) {
  7427. state.lastReturnValue = obs.callback.apply(obs.scope, [eventData, state]);
  7428. }
  7429. else {
  7430. state.lastReturnValue = obs.callback(eventData, state);
  7431. }
  7432. if (obs.unregisterOnNextCall) {
  7433. this._deferUnregister(obs);
  7434. }
  7435. }
  7436. if (state.skipNextObservers) {
  7437. return false;
  7438. }
  7439. }
  7440. return true;
  7441. };
  7442. /**
  7443. * Calling this will execute each callback, expecting it to be a promise or return a value.
  7444. * If at any point in the chain one function fails, the promise will fail and the execution will not continue.
  7445. * This is useful when a chain of events (sometimes async events) is needed to initialize a certain object
  7446. * and it is crucial that all callbacks will be executed.
  7447. * The order of the callbacks is kept, callbacks are not executed parallel.
  7448. *
  7449. * @param eventData The data to be sent to each callback
  7450. * @param mask is used to filter observers defaults to -1
  7451. * @param target defines the callback target (see EventState)
  7452. * @param currentTarget defines he current object in the bubbling phase
  7453. * @returns {Promise<T>} will return a Promise than resolves when all callbacks executed successfully.
  7454. */
  7455. Observable.prototype.notifyObserversWithPromise = function (eventData, mask, target, currentTarget) {
  7456. var _this = this;
  7457. if (mask === void 0) { mask = -1; }
  7458. // create an empty promise
  7459. var p = Promise.resolve(eventData);
  7460. // no observers? return this promise.
  7461. if (!this._observers.length) {
  7462. return p;
  7463. }
  7464. var state = this._eventState;
  7465. state.mask = mask;
  7466. state.target = target;
  7467. state.currentTarget = currentTarget;
  7468. state.skipNextObservers = false;
  7469. // execute one callback after another (not using Promise.all, the order is important)
  7470. this._observers.forEach(function (obs) {
  7471. if (state.skipNextObservers) {
  7472. return;
  7473. }
  7474. if (obs._willBeUnregistered) {
  7475. return;
  7476. }
  7477. if (obs.mask & mask) {
  7478. if (obs.scope) {
  7479. p = p.then(function (lastReturnedValue) {
  7480. state.lastReturnValue = lastReturnedValue;
  7481. return obs.callback.apply(obs.scope, [eventData, state]);
  7482. });
  7483. }
  7484. else {
  7485. p = p.then(function (lastReturnedValue) {
  7486. state.lastReturnValue = lastReturnedValue;
  7487. return obs.callback(eventData, state);
  7488. });
  7489. }
  7490. if (obs.unregisterOnNextCall) {
  7491. _this._deferUnregister(obs);
  7492. }
  7493. }
  7494. });
  7495. // return the eventData
  7496. return p.then(function () { return eventData; });
  7497. };
  7498. /**
  7499. * Notify a specific observer
  7500. * @param observer defines the observer to notify
  7501. * @param eventData defines the data to be sent to each callback
  7502. * @param mask is used to filter observers defaults to -1
  7503. */
  7504. Observable.prototype.notifyObserver = function (observer, eventData, mask) {
  7505. if (mask === void 0) { mask = -1; }
  7506. var state = this._eventState;
  7507. state.mask = mask;
  7508. state.skipNextObservers = false;
  7509. observer.callback(eventData, state);
  7510. };
  7511. /**
  7512. * Gets a boolean indicating if the observable has at least one observer
  7513. * @returns true is the Observable has at least one Observer registered
  7514. */
  7515. Observable.prototype.hasObservers = function () {
  7516. return this._observers.length > 0;
  7517. };
  7518. /**
  7519. * Clear the list of observers
  7520. */
  7521. Observable.prototype.clear = function () {
  7522. this._observers = new Array();
  7523. this._onObserverAdded = null;
  7524. };
  7525. /**
  7526. * Clone the current observable
  7527. * @returns a new observable
  7528. */
  7529. Observable.prototype.clone = function () {
  7530. var result = new Observable();
  7531. result._observers = this._observers.slice(0);
  7532. return result;
  7533. };
  7534. /**
  7535. * Does this observable handles observer registered with a given mask
  7536. * @param mask defines the mask to be tested
  7537. * @return whether or not one observer registered with the given mask is handeled
  7538. **/
  7539. Observable.prototype.hasSpecificMask = function (mask) {
  7540. if (mask === void 0) { mask = -1; }
  7541. for (var _i = 0, _a = this._observers; _i < _a.length; _i++) {
  7542. var obs = _a[_i];
  7543. if (obs.mask & mask || obs.mask === mask) {
  7544. return true;
  7545. }
  7546. }
  7547. return false;
  7548. };
  7549. return Observable;
  7550. }());
  7551. BABYLON.Observable = Observable;
  7552. })(BABYLON || (BABYLON = {}));
  7553. //# sourceMappingURL=babylon.observable.js.map
  7554. var BABYLON;
  7555. (function (BABYLON) {
  7556. var SmartArray = /** @class */ (function () {
  7557. function SmartArray(capacity) {
  7558. this.length = 0;
  7559. this.data = new Array(capacity);
  7560. this._id = SmartArray._GlobalId++;
  7561. }
  7562. SmartArray.prototype.push = function (value) {
  7563. this.data[this.length++] = value;
  7564. if (this.length > this.data.length) {
  7565. this.data.length *= 2;
  7566. }
  7567. };
  7568. SmartArray.prototype.forEach = function (func) {
  7569. for (var index = 0; index < this.length; index++) {
  7570. func(this.data[index]);
  7571. }
  7572. };
  7573. SmartArray.prototype.sort = function (compareFn) {
  7574. this.data.sort(compareFn);
  7575. };
  7576. SmartArray.prototype.reset = function () {
  7577. this.length = 0;
  7578. };
  7579. SmartArray.prototype.dispose = function () {
  7580. this.reset();
  7581. if (this.data) {
  7582. this.data.length = 0;
  7583. this.data = [];
  7584. }
  7585. };
  7586. SmartArray.prototype.concat = function (array) {
  7587. if (array.length === 0) {
  7588. return;
  7589. }
  7590. if (this.length + array.length > this.data.length) {
  7591. this.data.length = (this.length + array.length) * 2;
  7592. }
  7593. for (var index = 0; index < array.length; index++) {
  7594. this.data[this.length++] = (array.data || array)[index];
  7595. }
  7596. };
  7597. SmartArray.prototype.indexOf = function (value) {
  7598. var position = this.data.indexOf(value);
  7599. if (position >= this.length) {
  7600. return -1;
  7601. }
  7602. return position;
  7603. };
  7604. SmartArray.prototype.contains = function (value) {
  7605. return this.data.indexOf(value) !== -1;
  7606. };
  7607. // Statics
  7608. SmartArray._GlobalId = 0;
  7609. return SmartArray;
  7610. }());
  7611. BABYLON.SmartArray = SmartArray;
  7612. var SmartArrayNoDuplicate = /** @class */ (function (_super) {
  7613. __extends(SmartArrayNoDuplicate, _super);
  7614. function SmartArrayNoDuplicate() {
  7615. var _this = _super !== null && _super.apply(this, arguments) || this;
  7616. _this._duplicateId = 0;
  7617. return _this;
  7618. }
  7619. SmartArrayNoDuplicate.prototype.push = function (value) {
  7620. _super.prototype.push.call(this, value);
  7621. if (!value.__smartArrayFlags) {
  7622. value.__smartArrayFlags = {};
  7623. }
  7624. value.__smartArrayFlags[this._id] = this._duplicateId;
  7625. };
  7626. SmartArrayNoDuplicate.prototype.pushNoDuplicate = function (value) {
  7627. if (value.__smartArrayFlags && value.__smartArrayFlags[this._id] === this._duplicateId) {
  7628. return false;
  7629. }
  7630. this.push(value);
  7631. return true;
  7632. };
  7633. SmartArrayNoDuplicate.prototype.reset = function () {
  7634. _super.prototype.reset.call(this);
  7635. this._duplicateId++;
  7636. };
  7637. SmartArrayNoDuplicate.prototype.concatWithNoDuplicate = function (array) {
  7638. if (array.length === 0) {
  7639. return;
  7640. }
  7641. if (this.length + array.length > this.data.length) {
  7642. this.data.length = (this.length + array.length) * 2;
  7643. }
  7644. for (var index = 0; index < array.length; index++) {
  7645. var item = (array.data || array)[index];
  7646. this.pushNoDuplicate(item);
  7647. }
  7648. };
  7649. return SmartArrayNoDuplicate;
  7650. }(SmartArray));
  7651. BABYLON.SmartArrayNoDuplicate = SmartArrayNoDuplicate;
  7652. })(BABYLON || (BABYLON = {}));
  7653. //# sourceMappingURL=babylon.smartArray.js.map
  7654. var BABYLON;
  7655. (function (BABYLON) {
  7656. // See https://stackoverflow.com/questions/12915412/how-do-i-extend-a-host-object-e-g-error-in-typescript
  7657. // and https://github.com/Microsoft/TypeScript/wiki/Breaking-Changes#extending-built-ins-like-error-array-and-map-may-no-longer-work
  7658. var LoadFileError = /** @class */ (function (_super) {
  7659. __extends(LoadFileError, _super);
  7660. function LoadFileError(message, request) {
  7661. var _this = _super.call(this, message) || this;
  7662. _this.request = request;
  7663. _this.name = "LoadFileError";
  7664. LoadFileError._setPrototypeOf(_this, LoadFileError.prototype);
  7665. return _this;
  7666. }
  7667. // Polyfill for Object.setPrototypeOf if necessary.
  7668. LoadFileError._setPrototypeOf = Object.setPrototypeOf || (function (o, proto) { o.__proto__ = proto; return o; });
  7669. return LoadFileError;
  7670. }(Error));
  7671. BABYLON.LoadFileError = LoadFileError;
  7672. var RetryStrategy = /** @class */ (function () {
  7673. function RetryStrategy() {
  7674. }
  7675. RetryStrategy.ExponentialBackoff = function (maxRetries, baseInterval) {
  7676. if (maxRetries === void 0) { maxRetries = 3; }
  7677. if (baseInterval === void 0) { baseInterval = 500; }
  7678. return function (url, request, retryIndex) {
  7679. if (request.status !== 0 || retryIndex >= maxRetries || url.indexOf("file:") !== -1) {
  7680. return -1;
  7681. }
  7682. return Math.pow(2, retryIndex) * baseInterval;
  7683. };
  7684. };
  7685. return RetryStrategy;
  7686. }());
  7687. BABYLON.RetryStrategy = RetryStrategy;
  7688. // Screenshots
  7689. var screenshotCanvas;
  7690. var cloneValue = function (source, destinationObject) {
  7691. if (!source)
  7692. return null;
  7693. if (source instanceof BABYLON.Mesh) {
  7694. return null;
  7695. }
  7696. if (source instanceof BABYLON.SubMesh) {
  7697. return source.clone(destinationObject);
  7698. }
  7699. else if (source.clone) {
  7700. return source.clone();
  7701. }
  7702. return null;
  7703. };
  7704. var Tools = /** @class */ (function () {
  7705. function Tools() {
  7706. }
  7707. /**
  7708. * Interpolates between a and b via alpha
  7709. * @param a The lower value (returned when alpha = 0)
  7710. * @param b The upper value (returned when alpha = 1)
  7711. * @param alpha The interpolation-factor
  7712. * @return The mixed value
  7713. */
  7714. Tools.Mix = function (a, b, alpha) {
  7715. return a * (1 - alpha) + b * alpha;
  7716. };
  7717. Tools.Instantiate = function (className) {
  7718. if (Tools.RegisteredExternalClasses && Tools.RegisteredExternalClasses[className]) {
  7719. return Tools.RegisteredExternalClasses[className];
  7720. }
  7721. var arr = className.split(".");
  7722. var fn = (window || this);
  7723. for (var i = 0, len = arr.length; i < len; i++) {
  7724. fn = fn[arr[i]];
  7725. }
  7726. if (typeof fn !== "function") {
  7727. return null;
  7728. }
  7729. return fn;
  7730. };
  7731. /**
  7732. * Provides a slice function that will work even on IE
  7733. * @param data defines the array to slice
  7734. * @returns the new sliced array
  7735. */
  7736. Tools.Slice = function (data) {
  7737. if (data.slice) {
  7738. return data.slice();
  7739. }
  7740. return Array.prototype.slice.call(data);
  7741. };
  7742. Tools.SetImmediate = function (action) {
  7743. if (window.setImmediate) {
  7744. window.setImmediate(action);
  7745. }
  7746. else {
  7747. setTimeout(action, 1);
  7748. }
  7749. };
  7750. Tools.IsExponentOfTwo = function (value) {
  7751. var count = 1;
  7752. do {
  7753. count *= 2;
  7754. } while (count < value);
  7755. return count === value;
  7756. };
  7757. /**
  7758. * Find the next highest power of two.
  7759. * @param x Number to start search from.
  7760. * @return Next highest power of two.
  7761. */
  7762. Tools.CeilingPOT = function (x) {
  7763. x--;
  7764. x |= x >> 1;
  7765. x |= x >> 2;
  7766. x |= x >> 4;
  7767. x |= x >> 8;
  7768. x |= x >> 16;
  7769. x++;
  7770. return x;
  7771. };
  7772. /**
  7773. * Find the next lowest power of two.
  7774. * @param x Number to start search from.
  7775. * @return Next lowest power of two.
  7776. */
  7777. Tools.FloorPOT = function (x) {
  7778. x = x | (x >> 1);
  7779. x = x | (x >> 2);
  7780. x = x | (x >> 4);
  7781. x = x | (x >> 8);
  7782. x = x | (x >> 16);
  7783. return x - (x >> 1);
  7784. };
  7785. /**
  7786. * Find the nearest power of two.
  7787. * @param x Number to start search from.
  7788. * @return Next nearest power of two.
  7789. */
  7790. Tools.NearestPOT = function (x) {
  7791. var c = Tools.CeilingPOT(x);
  7792. var f = Tools.FloorPOT(x);
  7793. return (c - x) > (x - f) ? f : c;
  7794. };
  7795. Tools.GetExponentOfTwo = function (value, max, mode) {
  7796. if (mode === void 0) { mode = BABYLON.Engine.SCALEMODE_NEAREST; }
  7797. var pot;
  7798. switch (mode) {
  7799. case BABYLON.Engine.SCALEMODE_FLOOR:
  7800. pot = Tools.FloorPOT(value);
  7801. break;
  7802. case BABYLON.Engine.SCALEMODE_NEAREST:
  7803. pot = Tools.NearestPOT(value);
  7804. break;
  7805. case BABYLON.Engine.SCALEMODE_CEILING:
  7806. default:
  7807. pot = Tools.CeilingPOT(value);
  7808. break;
  7809. }
  7810. return Math.min(pot, max);
  7811. };
  7812. Tools.GetFilename = function (path) {
  7813. var index = path.lastIndexOf("/");
  7814. if (index < 0)
  7815. return path;
  7816. return path.substring(index + 1);
  7817. };
  7818. /**
  7819. * Extracts the "folder" part of a path (everything before the filename).
  7820. * @param uri The URI to extract the info from
  7821. * @param returnUnchangedIfNoSlash Do not touch the URI if no slashes are present
  7822. * @returns The "folder" part of the path
  7823. */
  7824. Tools.GetFolderPath = function (uri, returnUnchangedIfNoSlash) {
  7825. if (returnUnchangedIfNoSlash === void 0) { returnUnchangedIfNoSlash = false; }
  7826. var index = uri.lastIndexOf("/");
  7827. if (index < 0) {
  7828. if (returnUnchangedIfNoSlash) {
  7829. return uri;
  7830. }
  7831. return "";
  7832. }
  7833. return uri.substring(0, index + 1);
  7834. };
  7835. Tools.GetDOMTextContent = function (element) {
  7836. var result = "";
  7837. var child = element.firstChild;
  7838. while (child) {
  7839. if (child.nodeType === 3) {
  7840. result += child.textContent;
  7841. }
  7842. child = child.nextSibling;
  7843. }
  7844. return result;
  7845. };
  7846. Tools.ToDegrees = function (angle) {
  7847. return angle * 180 / Math.PI;
  7848. };
  7849. Tools.ToRadians = function (angle) {
  7850. return angle * Math.PI / 180;
  7851. };
  7852. Tools.EncodeArrayBufferTobase64 = function (buffer) {
  7853. var keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
  7854. var output = "";
  7855. var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
  7856. var i = 0;
  7857. var bytes = new Uint8Array(buffer);
  7858. while (i < bytes.length) {
  7859. chr1 = bytes[i++];
  7860. chr2 = i < bytes.length ? bytes[i++] : Number.NaN; // Not sure if the index
  7861. chr3 = i < bytes.length ? bytes[i++] : Number.NaN; // checks are needed here
  7862. enc1 = chr1 >> 2;
  7863. enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
  7864. enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
  7865. enc4 = chr3 & 63;
  7866. if (isNaN(chr2)) {
  7867. enc3 = enc4 = 64;
  7868. }
  7869. else if (isNaN(chr3)) {
  7870. enc4 = 64;
  7871. }
  7872. output += keyStr.charAt(enc1) + keyStr.charAt(enc2) +
  7873. keyStr.charAt(enc3) + keyStr.charAt(enc4);
  7874. }
  7875. return "data:image/png;base64," + output;
  7876. };
  7877. Tools.ExtractMinAndMaxIndexed = function (positions, indices, indexStart, indexCount, bias) {
  7878. if (bias === void 0) { bias = null; }
  7879. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  7880. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  7881. for (var index = indexStart; index < indexStart + indexCount; index++) {
  7882. var current = new BABYLON.Vector3(positions[indices[index] * 3], positions[indices[index] * 3 + 1], positions[indices[index] * 3 + 2]);
  7883. minimum = BABYLON.Vector3.Minimize(current, minimum);
  7884. maximum = BABYLON.Vector3.Maximize(current, maximum);
  7885. }
  7886. if (bias) {
  7887. minimum.x -= minimum.x * bias.x + bias.y;
  7888. minimum.y -= minimum.y * bias.x + bias.y;
  7889. minimum.z -= minimum.z * bias.x + bias.y;
  7890. maximum.x += maximum.x * bias.x + bias.y;
  7891. maximum.y += maximum.y * bias.x + bias.y;
  7892. maximum.z += maximum.z * bias.x + bias.y;
  7893. }
  7894. return {
  7895. minimum: minimum,
  7896. maximum: maximum
  7897. };
  7898. };
  7899. Tools.ExtractMinAndMax = function (positions, start, count, bias, stride) {
  7900. if (bias === void 0) { bias = null; }
  7901. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  7902. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  7903. if (!stride) {
  7904. stride = 3;
  7905. }
  7906. for (var index = start; index < start + count; index++) {
  7907. var current = new BABYLON.Vector3(positions[index * stride], positions[index * stride + 1], positions[index * stride + 2]);
  7908. minimum = BABYLON.Vector3.Minimize(current, minimum);
  7909. maximum = BABYLON.Vector3.Maximize(current, maximum);
  7910. }
  7911. if (bias) {
  7912. minimum.x -= minimum.x * bias.x + bias.y;
  7913. minimum.y -= minimum.y * bias.x + bias.y;
  7914. minimum.z -= minimum.z * bias.x + bias.y;
  7915. maximum.x += maximum.x * bias.x + bias.y;
  7916. maximum.y += maximum.y * bias.x + bias.y;
  7917. maximum.z += maximum.z * bias.x + bias.y;
  7918. }
  7919. return {
  7920. minimum: minimum,
  7921. maximum: maximum
  7922. };
  7923. };
  7924. Tools.Vector2ArrayFeeder = function (array) {
  7925. return function (index) {
  7926. var isFloatArray = (array.BYTES_PER_ELEMENT !== undefined);
  7927. var length = isFloatArray ? array.length / 2 : array.length;
  7928. if (index >= length) {
  7929. return null;
  7930. }
  7931. if (isFloatArray) {
  7932. var fa = array;
  7933. return new BABYLON.Vector2(fa[index * 2 + 0], fa[index * 2 + 1]);
  7934. }
  7935. var a = array;
  7936. return a[index];
  7937. };
  7938. };
  7939. Tools.ExtractMinAndMaxVector2 = function (feeder, bias) {
  7940. if (bias === void 0) { bias = null; }
  7941. var minimum = new BABYLON.Vector2(Number.MAX_VALUE, Number.MAX_VALUE);
  7942. var maximum = new BABYLON.Vector2(-Number.MAX_VALUE, -Number.MAX_VALUE);
  7943. var i = 0;
  7944. var cur = feeder(i++);
  7945. while (cur) {
  7946. minimum = BABYLON.Vector2.Minimize(cur, minimum);
  7947. maximum = BABYLON.Vector2.Maximize(cur, maximum);
  7948. cur = feeder(i++);
  7949. }
  7950. if (bias) {
  7951. minimum.x -= minimum.x * bias.x + bias.y;
  7952. minimum.y -= minimum.y * bias.x + bias.y;
  7953. maximum.x += maximum.x * bias.x + bias.y;
  7954. maximum.y += maximum.y * bias.x + bias.y;
  7955. }
  7956. return {
  7957. minimum: minimum,
  7958. maximum: maximum
  7959. };
  7960. };
  7961. Tools.MakeArray = function (obj, allowsNullUndefined) {
  7962. if (allowsNullUndefined !== true && (obj === undefined || obj == null))
  7963. return null;
  7964. return Array.isArray(obj) ? obj : [obj];
  7965. };
  7966. // Misc.
  7967. Tools.GetPointerPrefix = function () {
  7968. var eventPrefix = "pointer";
  7969. // Check if pointer events are supported
  7970. if (Tools.IsWindowObjectExist() && !window.PointerEvent && !navigator.pointerEnabled) {
  7971. eventPrefix = "mouse";
  7972. }
  7973. return eventPrefix;
  7974. };
  7975. /**
  7976. * @param func - the function to be called
  7977. * @param requester - the object that will request the next frame. Falls back to window.
  7978. */
  7979. Tools.QueueNewFrame = function (func, requester) {
  7980. if (!Tools.IsWindowObjectExist()) {
  7981. return setTimeout(func, 16);
  7982. }
  7983. if (!requester) {
  7984. requester = window;
  7985. }
  7986. if (requester.requestAnimationFrame) {
  7987. return requester.requestAnimationFrame(func);
  7988. }
  7989. else if (requester.msRequestAnimationFrame) {
  7990. return requester.msRequestAnimationFrame(func);
  7991. }
  7992. else if (requester.webkitRequestAnimationFrame) {
  7993. return requester.webkitRequestAnimationFrame(func);
  7994. }
  7995. else if (requester.mozRequestAnimationFrame) {
  7996. return requester.mozRequestAnimationFrame(func);
  7997. }
  7998. else if (requester.oRequestAnimationFrame) {
  7999. return requester.oRequestAnimationFrame(func);
  8000. }
  8001. else {
  8002. return window.setTimeout(func, 16);
  8003. }
  8004. };
  8005. Tools.RequestFullscreen = function (element) {
  8006. var requestFunction = element.requestFullscreen || element.msRequestFullscreen || element.webkitRequestFullscreen || element.mozRequestFullScreen;
  8007. if (!requestFunction)
  8008. return;
  8009. requestFunction.call(element);
  8010. };
  8011. Tools.ExitFullscreen = function () {
  8012. if (document.exitFullscreen) {
  8013. document.exitFullscreen();
  8014. }
  8015. else if (document.mozCancelFullScreen) {
  8016. document.mozCancelFullScreen();
  8017. }
  8018. else if (document.webkitCancelFullScreen) {
  8019. document.webkitCancelFullScreen();
  8020. }
  8021. else if (document.msCancelFullScreen) {
  8022. document.msCancelFullScreen();
  8023. }
  8024. };
  8025. Tools.SetCorsBehavior = function (url, element) {
  8026. if (url && url.indexOf("data:") === 0) {
  8027. return;
  8028. }
  8029. if (Tools.CorsBehavior) {
  8030. if (typeof (Tools.CorsBehavior) === 'string' || Tools.CorsBehavior instanceof String) {
  8031. element.crossOrigin = Tools.CorsBehavior;
  8032. }
  8033. else {
  8034. var result = Tools.CorsBehavior(url);
  8035. if (result) {
  8036. element.crossOrigin = result;
  8037. }
  8038. }
  8039. }
  8040. };
  8041. // External files
  8042. Tools.CleanUrl = function (url) {
  8043. url = url.replace(/#/mg, "%23");
  8044. return url;
  8045. };
  8046. Tools.LoadImage = function (url, onLoad, onError, database) {
  8047. if (url instanceof ArrayBuffer) {
  8048. url = Tools.EncodeArrayBufferTobase64(url);
  8049. }
  8050. url = Tools.CleanUrl(url);
  8051. url = Tools.PreprocessUrl(url);
  8052. var img = new Image();
  8053. Tools.SetCorsBehavior(url, img);
  8054. var loadHandler = function () {
  8055. img.removeEventListener("load", loadHandler);
  8056. img.removeEventListener("error", errorHandler);
  8057. onLoad(img);
  8058. };
  8059. var errorHandler = function (err) {
  8060. img.removeEventListener("load", loadHandler);
  8061. img.removeEventListener("error", errorHandler);
  8062. Tools.Error("Error while trying to load image: " + url);
  8063. if (onError) {
  8064. onError("Error while trying to load image: " + url, err);
  8065. }
  8066. };
  8067. img.addEventListener("load", loadHandler);
  8068. img.addEventListener("error", errorHandler);
  8069. var noIndexedDB = function () {
  8070. img.src = url;
  8071. };
  8072. var loadFromIndexedDB = function () {
  8073. if (database) {
  8074. database.loadImageFromDB(url, img);
  8075. }
  8076. };
  8077. //ANY database to do!
  8078. if (url.substr(0, 5) !== "data:" && database && database.enableTexturesOffline && BABYLON.Database.IsUASupportingBlobStorage) {
  8079. database.openAsync(loadFromIndexedDB, noIndexedDB);
  8080. }
  8081. else {
  8082. if (url.indexOf("file:") !== -1) {
  8083. var textureName = decodeURIComponent(url.substring(5).toLowerCase());
  8084. if (BABYLON.FilesInput.FilesToLoad[textureName]) {
  8085. try {
  8086. var blobURL;
  8087. try {
  8088. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesToLoad[textureName], { oneTimeOnly: true });
  8089. }
  8090. catch (ex) {
  8091. // Chrome doesn't support oneTimeOnly parameter
  8092. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesToLoad[textureName]);
  8093. }
  8094. img.src = blobURL;
  8095. }
  8096. catch (e) {
  8097. img.src = "";
  8098. }
  8099. return img;
  8100. }
  8101. }
  8102. noIndexedDB();
  8103. }
  8104. return img;
  8105. };
  8106. Tools.LoadFile = function (url, onSuccess, onProgress, database, useArrayBuffer, onError) {
  8107. url = Tools.CleanUrl(url);
  8108. url = Tools.PreprocessUrl(url);
  8109. // If file and file input are set
  8110. if (url.indexOf("file:") !== -1) {
  8111. var fileName = decodeURIComponent(url.substring(5).toLowerCase());
  8112. if (BABYLON.FilesInput.FilesToLoad[fileName]) {
  8113. return Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[fileName], onSuccess, onProgress, useArrayBuffer);
  8114. }
  8115. }
  8116. var loadUrl = Tools.BaseUrl + url;
  8117. var aborted = false;
  8118. var fileRequest = {
  8119. onCompleteObservable: new BABYLON.Observable(),
  8120. abort: function () { return aborted = true; },
  8121. };
  8122. var requestFile = function () {
  8123. var request = new XMLHttpRequest();
  8124. var retryHandle = null;
  8125. fileRequest.abort = function () {
  8126. aborted = true;
  8127. if (request.readyState !== (XMLHttpRequest.DONE || 4)) {
  8128. request.abort();
  8129. }
  8130. if (retryHandle !== null) {
  8131. clearTimeout(retryHandle);
  8132. retryHandle = null;
  8133. }
  8134. };
  8135. var retryLoop = function (retryIndex) {
  8136. request.open('GET', loadUrl, true);
  8137. if (useArrayBuffer) {
  8138. request.responseType = "arraybuffer";
  8139. }
  8140. if (onProgress) {
  8141. request.addEventListener("progress", onProgress);
  8142. }
  8143. var onLoadEnd = function () {
  8144. request.removeEventListener("loadend", onLoadEnd);
  8145. fileRequest.onCompleteObservable.notifyObservers(fileRequest);
  8146. fileRequest.onCompleteObservable.clear();
  8147. };
  8148. request.addEventListener("loadend", onLoadEnd);
  8149. var onReadyStateChange = function () {
  8150. if (aborted) {
  8151. return;
  8152. }
  8153. // In case of undefined state in some browsers.
  8154. if (request.readyState === (XMLHttpRequest.DONE || 4)) {
  8155. // Some browsers have issues where onreadystatechange can be called multiple times with the same value.
  8156. request.removeEventListener("readystatechange", onReadyStateChange);
  8157. if (request.status >= 200 && request.status < 300 || (!Tools.IsWindowObjectExist() && (request.status === 0))) {
  8158. onSuccess(!useArrayBuffer ? request.responseText : request.response, request.responseURL);
  8159. return;
  8160. }
  8161. var retryStrategy = Tools.DefaultRetryStrategy;
  8162. if (retryStrategy) {
  8163. var waitTime = retryStrategy(loadUrl, request, retryIndex);
  8164. if (waitTime !== -1) {
  8165. // Prevent the request from completing for retry.
  8166. request.removeEventListener("loadend", onLoadEnd);
  8167. request = new XMLHttpRequest();
  8168. retryHandle = setTimeout(function () { return retryLoop(retryIndex + 1); }, waitTime);
  8169. return;
  8170. }
  8171. }
  8172. var e = new LoadFileError("Error status: " + request.status + " " + request.statusText + " - Unable to load " + loadUrl, request);
  8173. if (onError) {
  8174. onError(request, e);
  8175. }
  8176. else {
  8177. throw e;
  8178. }
  8179. }
  8180. };
  8181. request.addEventListener("readystatechange", onReadyStateChange);
  8182. request.send();
  8183. };
  8184. retryLoop(0);
  8185. };
  8186. // Caching all files
  8187. if (database && database.enableSceneOffline) {
  8188. var noIndexedDB_1 = function () {
  8189. if (!aborted) {
  8190. requestFile();
  8191. }
  8192. };
  8193. var loadFromIndexedDB = function () {
  8194. // TODO: database needs to support aborting and should return a IFileRequest
  8195. if (aborted) {
  8196. return;
  8197. }
  8198. if (database) {
  8199. database.loadFileFromDB(url, function (data) {
  8200. if (!aborted) {
  8201. onSuccess(data);
  8202. }
  8203. fileRequest.onCompleteObservable.notifyObservers(fileRequest);
  8204. }, onProgress ? function (event) {
  8205. if (!aborted) {
  8206. onProgress(event);
  8207. }
  8208. } : undefined, noIndexedDB_1, useArrayBuffer);
  8209. }
  8210. };
  8211. database.openAsync(loadFromIndexedDB, noIndexedDB_1);
  8212. }
  8213. else {
  8214. requestFile();
  8215. }
  8216. return fileRequest;
  8217. };
  8218. /**
  8219. * Load a script (identified by an url). When the url returns, the
  8220. * content of this file is added into a new script element, attached to the DOM (body element)
  8221. */
  8222. Tools.LoadScript = function (scriptUrl, onSuccess, onError) {
  8223. var head = document.getElementsByTagName('head')[0];
  8224. var script = document.createElement('script');
  8225. script.type = 'text/javascript';
  8226. script.src = scriptUrl;
  8227. script.onload = function () {
  8228. if (onSuccess) {
  8229. onSuccess();
  8230. }
  8231. };
  8232. script.onerror = function (e) {
  8233. if (onError) {
  8234. onError("Unable to load script", e);
  8235. }
  8236. };
  8237. head.appendChild(script);
  8238. };
  8239. Tools.ReadFileAsDataURL = function (fileToLoad, callback, progressCallback) {
  8240. var reader = new FileReader();
  8241. var request = {
  8242. onCompleteObservable: new BABYLON.Observable(),
  8243. abort: function () { return reader.abort(); },
  8244. };
  8245. reader.onloadend = function (e) {
  8246. request.onCompleteObservable.notifyObservers(request);
  8247. };
  8248. reader.onload = function (e) {
  8249. //target doesn't have result from ts 1.3
  8250. callback(e.target['result']);
  8251. };
  8252. reader.onprogress = progressCallback;
  8253. reader.readAsDataURL(fileToLoad);
  8254. return request;
  8255. };
  8256. Tools.ReadFile = function (fileToLoad, callback, progressCallBack, useArrayBuffer) {
  8257. var reader = new FileReader();
  8258. var request = {
  8259. onCompleteObservable: new BABYLON.Observable(),
  8260. abort: function () { return reader.abort(); },
  8261. };
  8262. reader.onloadend = function (e) { return request.onCompleteObservable.notifyObservers(request); };
  8263. reader.onerror = function (e) {
  8264. Tools.Log("Error while reading file: " + fileToLoad.name);
  8265. callback(JSON.stringify({ autoClear: true, clearColor: [1, 0, 0], ambientColor: [0, 0, 0], gravity: [0, -9.807, 0], meshes: [], cameras: [], lights: [] }));
  8266. };
  8267. reader.onload = function (e) {
  8268. //target doesn't have result from ts 1.3
  8269. callback(e.target['result']);
  8270. };
  8271. if (progressCallBack) {
  8272. reader.onprogress = progressCallBack;
  8273. }
  8274. if (!useArrayBuffer) {
  8275. // Asynchronous read
  8276. reader.readAsText(fileToLoad);
  8277. }
  8278. else {
  8279. reader.readAsArrayBuffer(fileToLoad);
  8280. }
  8281. return request;
  8282. };
  8283. //returns a downloadable url to a file content.
  8284. Tools.FileAsURL = function (content) {
  8285. var fileBlob = new Blob([content]);
  8286. var url = window.URL || window.webkitURL;
  8287. var link = url.createObjectURL(fileBlob);
  8288. return link;
  8289. };
  8290. // Misc.
  8291. Tools.Format = function (value, decimals) {
  8292. if (decimals === void 0) { decimals = 2; }
  8293. return value.toFixed(decimals);
  8294. };
  8295. Tools.CheckExtends = function (v, min, max) {
  8296. if (v.x < min.x)
  8297. min.x = v.x;
  8298. if (v.y < min.y)
  8299. min.y = v.y;
  8300. if (v.z < min.z)
  8301. min.z = v.z;
  8302. if (v.x > max.x)
  8303. max.x = v.x;
  8304. if (v.y > max.y)
  8305. max.y = v.y;
  8306. if (v.z > max.z)
  8307. max.z = v.z;
  8308. };
  8309. Tools.DeepCopy = function (source, destination, doNotCopyList, mustCopyList) {
  8310. for (var prop in source) {
  8311. if (prop[0] === "_" && (!mustCopyList || mustCopyList.indexOf(prop) === -1)) {
  8312. continue;
  8313. }
  8314. if (doNotCopyList && doNotCopyList.indexOf(prop) !== -1) {
  8315. continue;
  8316. }
  8317. var sourceValue = source[prop];
  8318. var typeOfSourceValue = typeof sourceValue;
  8319. if (typeOfSourceValue === "function") {
  8320. continue;
  8321. }
  8322. if (typeOfSourceValue === "object") {
  8323. if (sourceValue instanceof Array) {
  8324. destination[prop] = [];
  8325. if (sourceValue.length > 0) {
  8326. if (typeof sourceValue[0] == "object") {
  8327. for (var index = 0; index < sourceValue.length; index++) {
  8328. var clonedValue = cloneValue(sourceValue[index], destination);
  8329. if (destination[prop].indexOf(clonedValue) === -1) {
  8330. destination[prop].push(clonedValue);
  8331. }
  8332. }
  8333. }
  8334. else {
  8335. destination[prop] = sourceValue.slice(0);
  8336. }
  8337. }
  8338. }
  8339. else {
  8340. destination[prop] = cloneValue(sourceValue, destination);
  8341. }
  8342. }
  8343. else {
  8344. destination[prop] = sourceValue;
  8345. }
  8346. }
  8347. };
  8348. Tools.IsEmpty = function (obj) {
  8349. for (var i in obj) {
  8350. if (obj.hasOwnProperty(i)) {
  8351. return false;
  8352. }
  8353. }
  8354. return true;
  8355. };
  8356. Tools.RegisterTopRootEvents = function (events) {
  8357. for (var index = 0; index < events.length; index++) {
  8358. var event = events[index];
  8359. window.addEventListener(event.name, event.handler, false);
  8360. try {
  8361. if (window.parent) {
  8362. window.parent.addEventListener(event.name, event.handler, false);
  8363. }
  8364. }
  8365. catch (e) {
  8366. // Silently fails...
  8367. }
  8368. }
  8369. };
  8370. Tools.UnregisterTopRootEvents = function (events) {
  8371. for (var index = 0; index < events.length; index++) {
  8372. var event = events[index];
  8373. window.removeEventListener(event.name, event.handler);
  8374. try {
  8375. if (window.parent) {
  8376. window.parent.removeEventListener(event.name, event.handler);
  8377. }
  8378. }
  8379. catch (e) {
  8380. // Silently fails...
  8381. }
  8382. }
  8383. };
  8384. Tools.DumpFramebuffer = function (width, height, engine, successCallback, mimeType, fileName) {
  8385. if (mimeType === void 0) { mimeType = "image/png"; }
  8386. // Read the contents of the framebuffer
  8387. var numberOfChannelsByLine = width * 4;
  8388. var halfHeight = height / 2;
  8389. //Reading datas from WebGL
  8390. var data = engine.readPixels(0, 0, width, height);
  8391. //To flip image on Y axis.
  8392. for (var i = 0; i < halfHeight; i++) {
  8393. for (var j = 0; j < numberOfChannelsByLine; j++) {
  8394. var currentCell = j + i * numberOfChannelsByLine;
  8395. var targetLine = height - i - 1;
  8396. var targetCell = j + targetLine * numberOfChannelsByLine;
  8397. var temp = data[currentCell];
  8398. data[currentCell] = data[targetCell];
  8399. data[targetCell] = temp;
  8400. }
  8401. }
  8402. // Create a 2D canvas to store the result
  8403. if (!screenshotCanvas) {
  8404. screenshotCanvas = document.createElement('canvas');
  8405. }
  8406. screenshotCanvas.width = width;
  8407. screenshotCanvas.height = height;
  8408. var context = screenshotCanvas.getContext('2d');
  8409. if (context) {
  8410. // Copy the pixels to a 2D canvas
  8411. var imageData = context.createImageData(width, height);
  8412. var castData = (imageData.data);
  8413. castData.set(data);
  8414. context.putImageData(imageData, 0, 0);
  8415. Tools.EncodeScreenshotCanvasData(successCallback, mimeType, fileName);
  8416. }
  8417. };
  8418. Tools.EncodeScreenshotCanvasData = function (successCallback, mimeType, fileName) {
  8419. if (mimeType === void 0) { mimeType = "image/png"; }
  8420. var base64Image = screenshotCanvas.toDataURL(mimeType);
  8421. if (successCallback) {
  8422. successCallback(base64Image);
  8423. }
  8424. else {
  8425. // We need HTMLCanvasElement.toBlob for HD screenshots
  8426. if (!screenshotCanvas.toBlob) {
  8427. // low performance polyfill based on toDataURL (https://developer.mozilla.org/en-US/docs/Web/API/HTMLCanvasElement/toBlob)
  8428. screenshotCanvas.toBlob = function (callback, type, quality) {
  8429. var _this = this;
  8430. setTimeout(function () {
  8431. var binStr = atob(_this.toDataURL(type, quality).split(',')[1]), len = binStr.length, arr = new Uint8Array(len);
  8432. for (var i = 0; i < len; i++) {
  8433. arr[i] = binStr.charCodeAt(i);
  8434. }
  8435. callback(new Blob([arr], { type: type || 'image/png' }));
  8436. });
  8437. };
  8438. }
  8439. screenshotCanvas.toBlob(function (blob) {
  8440. var url = URL.createObjectURL(blob);
  8441. //Creating a link if the browser have the download attribute on the a tag, to automatically start download generated image.
  8442. if (("download" in document.createElement("a"))) {
  8443. var a = window.document.createElement("a");
  8444. a.href = url;
  8445. if (fileName) {
  8446. a.setAttribute("download", fileName);
  8447. }
  8448. else {
  8449. var date = new Date();
  8450. var stringDate = (date.getFullYear() + "-" + (date.getMonth() + 1)).slice(-2) + "-" + date.getDate() + "_" + date.getHours() + "-" + ('0' + date.getMinutes()).slice(-2);
  8451. a.setAttribute("download", "screenshot_" + stringDate + ".png");
  8452. }
  8453. window.document.body.appendChild(a);
  8454. a.addEventListener("click", function () {
  8455. if (a.parentElement) {
  8456. a.parentElement.removeChild(a);
  8457. }
  8458. });
  8459. a.click();
  8460. }
  8461. else {
  8462. var newWindow = window.open("");
  8463. if (!newWindow)
  8464. return;
  8465. var img = newWindow.document.createElement("img");
  8466. img.onload = function () {
  8467. // no longer need to read the blob so it's revoked
  8468. URL.revokeObjectURL(url);
  8469. };
  8470. img.src = url;
  8471. newWindow.document.body.appendChild(img);
  8472. }
  8473. });
  8474. }
  8475. };
  8476. Tools.CreateScreenshot = function (engine, camera, size, successCallback, mimeType) {
  8477. if (mimeType === void 0) { mimeType = "image/png"; }
  8478. var width;
  8479. var height;
  8480. // If a precision value is specified
  8481. if (size.precision) {
  8482. width = Math.round(engine.getRenderWidth() * size.precision);
  8483. height = Math.round(width / engine.getAspectRatio(camera));
  8484. }
  8485. else if (size.width && size.height) {
  8486. width = size.width;
  8487. height = size.height;
  8488. }
  8489. else if (size.width && !size.height) {
  8490. width = size.width;
  8491. height = Math.round(width / engine.getAspectRatio(camera));
  8492. }
  8493. else if (size.height && !size.width) {
  8494. height = size.height;
  8495. width = Math.round(height * engine.getAspectRatio(camera));
  8496. }
  8497. else if (!isNaN(size)) {
  8498. height = size;
  8499. width = size;
  8500. }
  8501. else {
  8502. Tools.Error("Invalid 'size' parameter !");
  8503. return;
  8504. }
  8505. if (!screenshotCanvas) {
  8506. screenshotCanvas = document.createElement('canvas');
  8507. }
  8508. screenshotCanvas.width = width;
  8509. screenshotCanvas.height = height;
  8510. var renderContext = screenshotCanvas.getContext("2d");
  8511. var ratio = engine.getRenderWidth() / engine.getRenderHeight();
  8512. var newWidth = width;
  8513. var newHeight = newWidth / ratio;
  8514. if (newHeight > height) {
  8515. newHeight = height;
  8516. newWidth = newHeight * ratio;
  8517. }
  8518. var offsetX = Math.max(0, width - newWidth) / 2;
  8519. var offsetY = Math.max(0, height - newHeight) / 2;
  8520. var renderingCanvas = engine.getRenderingCanvas();
  8521. if (renderContext && renderingCanvas) {
  8522. renderContext.drawImage(renderingCanvas, offsetX, offsetY, newWidth, newHeight);
  8523. }
  8524. Tools.EncodeScreenshotCanvasData(successCallback, mimeType);
  8525. };
  8526. /**
  8527. * Generates an image screenshot from the specified camera.
  8528. *
  8529. * @param engine The engine to use for rendering
  8530. * @param camera The camera to use for rendering
  8531. * @param size This parameter can be set to a single number or to an object with the
  8532. * following (optional) properties: precision, width, height. If a single number is passed,
  8533. * it will be used for both width and height. If an object is passed, the screenshot size
  8534. * will be derived from the parameters. The precision property is a multiplier allowing
  8535. * rendering at a higher or lower resolution.
  8536. * @param successCallback The callback receives a single parameter which contains the
  8537. * screenshot as a string of base64-encoded characters. This string can be assigned to the
  8538. * src parameter of an <img> to display it.
  8539. * @param mimeType The MIME type of the screenshot image (default: image/png).
  8540. * Check your browser for supported MIME types.
  8541. * @param samples Texture samples (default: 1)
  8542. * @param antialiasing Whether antialiasing should be turned on or not (default: false)
  8543. * @param fileName A name for for the downloaded file.
  8544. * @constructor
  8545. */
  8546. Tools.CreateScreenshotUsingRenderTarget = function (engine, camera, size, successCallback, mimeType, samples, antialiasing, fileName) {
  8547. if (mimeType === void 0) { mimeType = "image/png"; }
  8548. if (samples === void 0) { samples = 1; }
  8549. if (antialiasing === void 0) { antialiasing = false; }
  8550. var width;
  8551. var height;
  8552. //If a precision value is specified
  8553. if (size.precision) {
  8554. width = Math.round(engine.getRenderWidth() * size.precision);
  8555. height = Math.round(width / engine.getAspectRatio(camera));
  8556. size = { width: width, height: height };
  8557. }
  8558. else if (size.width && size.height) {
  8559. width = size.width;
  8560. height = size.height;
  8561. }
  8562. else if (size.width && !size.height) {
  8563. width = size.width;
  8564. height = Math.round(width / engine.getAspectRatio(camera));
  8565. size = { width: width, height: height };
  8566. }
  8567. else if (size.height && !size.width) {
  8568. height = size.height;
  8569. width = Math.round(height * engine.getAspectRatio(camera));
  8570. size = { width: width, height: height };
  8571. }
  8572. else if (!isNaN(size)) {
  8573. height = size;
  8574. width = size;
  8575. }
  8576. else {
  8577. Tools.Error("Invalid 'size' parameter !");
  8578. return;
  8579. }
  8580. var scene = camera.getScene();
  8581. var previousCamera = null;
  8582. if (scene.activeCamera !== camera) {
  8583. previousCamera = scene.activeCamera;
  8584. scene.activeCamera = camera;
  8585. }
  8586. //At this point size can be a number, or an object (according to engine.prototype.createRenderTargetTexture method)
  8587. var texture = new BABYLON.RenderTargetTexture("screenShot", size, scene, false, false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  8588. texture.renderList = null;
  8589. texture.samples = samples;
  8590. if (antialiasing) {
  8591. texture.addPostProcess(new BABYLON.FxaaPostProcess('antialiasing', 1.0, scene.activeCamera));
  8592. }
  8593. texture.onAfterRenderObservable.add(function () {
  8594. Tools.DumpFramebuffer(width, height, engine, successCallback, mimeType, fileName);
  8595. });
  8596. scene.incrementRenderId();
  8597. scene.resetCachedMaterial();
  8598. texture.render(true);
  8599. texture.dispose();
  8600. if (previousCamera) {
  8601. scene.activeCamera = previousCamera;
  8602. }
  8603. camera.getProjectionMatrix(true); // Force cache refresh;
  8604. };
  8605. // XHR response validator for local file scenario
  8606. Tools.ValidateXHRData = function (xhr, dataType) {
  8607. // 1 for text (.babylon, manifest and shaders), 2 for TGA, 4 for DDS, 7 for all
  8608. if (dataType === void 0) { dataType = 7; }
  8609. try {
  8610. if (dataType & 1) {
  8611. if (xhr.responseText && xhr.responseText.length > 0) {
  8612. return true;
  8613. }
  8614. else if (dataType === 1) {
  8615. return false;
  8616. }
  8617. }
  8618. if (dataType & 2) {
  8619. // Check header width and height since there is no "TGA" magic number
  8620. var tgaHeader = BABYLON.TGATools.GetTGAHeader(xhr.response);
  8621. if (tgaHeader.width && tgaHeader.height && tgaHeader.width > 0 && tgaHeader.height > 0) {
  8622. return true;
  8623. }
  8624. else if (dataType === 2) {
  8625. return false;
  8626. }
  8627. }
  8628. if (dataType & 4) {
  8629. // Check for the "DDS" magic number
  8630. var ddsHeader = new Uint8Array(xhr.response, 0, 3);
  8631. if (ddsHeader[0] === 68 && ddsHeader[1] === 68 && ddsHeader[2] === 83) {
  8632. return true;
  8633. }
  8634. else {
  8635. return false;
  8636. }
  8637. }
  8638. }
  8639. catch (e) {
  8640. // Global protection
  8641. }
  8642. return false;
  8643. };
  8644. /**
  8645. * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  8646. * Be aware Math.random() could cause collisions, but:
  8647. * "All but 6 of the 128 bits of the ID are randomly generated, which means that for any two ids, there's a 1 in 2^^122 (or 5.3x10^^36) chance they'll collide"
  8648. */
  8649. Tools.RandomId = function () {
  8650. return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
  8651. var r = Math.random() * 16 | 0, v = c === 'x' ? r : (r & 0x3 | 0x8);
  8652. return v.toString(16);
  8653. });
  8654. };
  8655. /**
  8656. * Test if the given uri is a base64 string.
  8657. * @param uri The uri to test
  8658. * @return True if the uri is a base64 string or false otherwise.
  8659. */
  8660. Tools.IsBase64 = function (uri) {
  8661. return uri.length < 5 ? false : uri.substr(0, 5) === "data:";
  8662. };
  8663. /**
  8664. * Decode the given base64 uri.
  8665. * @param uri The uri to decode
  8666. * @return The decoded base64 data.
  8667. */
  8668. Tools.DecodeBase64 = function (uri) {
  8669. var decodedString = atob(uri.split(",")[1]);
  8670. var bufferLength = decodedString.length;
  8671. var bufferView = new Uint8Array(new ArrayBuffer(bufferLength));
  8672. for (var i = 0; i < bufferLength; i++) {
  8673. bufferView[i] = decodedString.charCodeAt(i);
  8674. }
  8675. return bufferView.buffer;
  8676. };
  8677. Object.defineProperty(Tools, "NoneLogLevel", {
  8678. get: function () {
  8679. return Tools._NoneLogLevel;
  8680. },
  8681. enumerable: true,
  8682. configurable: true
  8683. });
  8684. Object.defineProperty(Tools, "MessageLogLevel", {
  8685. get: function () {
  8686. return Tools._MessageLogLevel;
  8687. },
  8688. enumerable: true,
  8689. configurable: true
  8690. });
  8691. Object.defineProperty(Tools, "WarningLogLevel", {
  8692. get: function () {
  8693. return Tools._WarningLogLevel;
  8694. },
  8695. enumerable: true,
  8696. configurable: true
  8697. });
  8698. Object.defineProperty(Tools, "ErrorLogLevel", {
  8699. get: function () {
  8700. return Tools._ErrorLogLevel;
  8701. },
  8702. enumerable: true,
  8703. configurable: true
  8704. });
  8705. Object.defineProperty(Tools, "AllLogLevel", {
  8706. get: function () {
  8707. return Tools._MessageLogLevel | Tools._WarningLogLevel | Tools._ErrorLogLevel;
  8708. },
  8709. enumerable: true,
  8710. configurable: true
  8711. });
  8712. Tools._AddLogEntry = function (entry) {
  8713. Tools._LogCache = entry + Tools._LogCache;
  8714. if (Tools.OnNewCacheEntry) {
  8715. Tools.OnNewCacheEntry(entry);
  8716. }
  8717. };
  8718. Tools._FormatMessage = function (message) {
  8719. var padStr = function (i) { return (i < 10) ? "0" + i : "" + i; };
  8720. var date = new Date();
  8721. return "[" + padStr(date.getHours()) + ":" + padStr(date.getMinutes()) + ":" + padStr(date.getSeconds()) + "]: " + message;
  8722. };
  8723. Tools._LogDisabled = function (message) {
  8724. // nothing to do
  8725. };
  8726. Tools._LogEnabled = function (message) {
  8727. var formattedMessage = Tools._FormatMessage(message);
  8728. console.log("BJS - " + formattedMessage);
  8729. var entry = "<div style='color:white'>" + formattedMessage + "</div><br>";
  8730. Tools._AddLogEntry(entry);
  8731. };
  8732. Tools._WarnDisabled = function (message) {
  8733. // nothing to do
  8734. };
  8735. Tools._WarnEnabled = function (message) {
  8736. var formattedMessage = Tools._FormatMessage(message);
  8737. console.warn("BJS - " + formattedMessage);
  8738. var entry = "<div style='color:orange'>" + formattedMessage + "</div><br>";
  8739. Tools._AddLogEntry(entry);
  8740. };
  8741. Tools._ErrorDisabled = function (message) {
  8742. // nothing to do
  8743. };
  8744. Tools._ErrorEnabled = function (message) {
  8745. Tools.errorsCount++;
  8746. var formattedMessage = Tools._FormatMessage(message);
  8747. console.error("BJS - " + formattedMessage);
  8748. var entry = "<div style='color:red'>" + formattedMessage + "</div><br>";
  8749. Tools._AddLogEntry(entry);
  8750. };
  8751. Object.defineProperty(Tools, "LogCache", {
  8752. get: function () {
  8753. return Tools._LogCache;
  8754. },
  8755. enumerable: true,
  8756. configurable: true
  8757. });
  8758. Tools.ClearLogCache = function () {
  8759. Tools._LogCache = "";
  8760. Tools.errorsCount = 0;
  8761. };
  8762. Object.defineProperty(Tools, "LogLevels", {
  8763. set: function (level) {
  8764. if ((level & Tools.MessageLogLevel) === Tools.MessageLogLevel) {
  8765. Tools.Log = Tools._LogEnabled;
  8766. }
  8767. else {
  8768. Tools.Log = Tools._LogDisabled;
  8769. }
  8770. if ((level & Tools.WarningLogLevel) === Tools.WarningLogLevel) {
  8771. Tools.Warn = Tools._WarnEnabled;
  8772. }
  8773. else {
  8774. Tools.Warn = Tools._WarnDisabled;
  8775. }
  8776. if ((level & Tools.ErrorLogLevel) === Tools.ErrorLogLevel) {
  8777. Tools.Error = Tools._ErrorEnabled;
  8778. }
  8779. else {
  8780. Tools.Error = Tools._ErrorDisabled;
  8781. }
  8782. },
  8783. enumerable: true,
  8784. configurable: true
  8785. });
  8786. Tools.IsWindowObjectExist = function () {
  8787. return (typeof window) !== "undefined";
  8788. };
  8789. Object.defineProperty(Tools, "PerformanceNoneLogLevel", {
  8790. get: function () {
  8791. return Tools._PerformanceNoneLogLevel;
  8792. },
  8793. enumerable: true,
  8794. configurable: true
  8795. });
  8796. Object.defineProperty(Tools, "PerformanceUserMarkLogLevel", {
  8797. get: function () {
  8798. return Tools._PerformanceUserMarkLogLevel;
  8799. },
  8800. enumerable: true,
  8801. configurable: true
  8802. });
  8803. Object.defineProperty(Tools, "PerformanceConsoleLogLevel", {
  8804. get: function () {
  8805. return Tools._PerformanceConsoleLogLevel;
  8806. },
  8807. enumerable: true,
  8808. configurable: true
  8809. });
  8810. Object.defineProperty(Tools, "PerformanceLogLevel", {
  8811. set: function (level) {
  8812. if ((level & Tools.PerformanceUserMarkLogLevel) === Tools.PerformanceUserMarkLogLevel) {
  8813. Tools.StartPerformanceCounter = Tools._StartUserMark;
  8814. Tools.EndPerformanceCounter = Tools._EndUserMark;
  8815. return;
  8816. }
  8817. if ((level & Tools.PerformanceConsoleLogLevel) === Tools.PerformanceConsoleLogLevel) {
  8818. Tools.StartPerformanceCounter = Tools._StartPerformanceConsole;
  8819. Tools.EndPerformanceCounter = Tools._EndPerformanceConsole;
  8820. return;
  8821. }
  8822. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  8823. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  8824. },
  8825. enumerable: true,
  8826. configurable: true
  8827. });
  8828. Tools._StartPerformanceCounterDisabled = function (counterName, condition) {
  8829. };
  8830. Tools._EndPerformanceCounterDisabled = function (counterName, condition) {
  8831. };
  8832. Tools._StartUserMark = function (counterName, condition) {
  8833. if (condition === void 0) { condition = true; }
  8834. if (!Tools._performance) {
  8835. if (!Tools.IsWindowObjectExist()) {
  8836. return;
  8837. }
  8838. Tools._performance = window.performance;
  8839. }
  8840. if (!condition || !Tools._performance.mark) {
  8841. return;
  8842. }
  8843. Tools._performance.mark(counterName + "-Begin");
  8844. };
  8845. Tools._EndUserMark = function (counterName, condition) {
  8846. if (condition === void 0) { condition = true; }
  8847. if (!condition || !Tools._performance.mark) {
  8848. return;
  8849. }
  8850. Tools._performance.mark(counterName + "-End");
  8851. Tools._performance.measure(counterName, counterName + "-Begin", counterName + "-End");
  8852. };
  8853. Tools._StartPerformanceConsole = function (counterName, condition) {
  8854. if (condition === void 0) { condition = true; }
  8855. if (!condition) {
  8856. return;
  8857. }
  8858. Tools._StartUserMark(counterName, condition);
  8859. if (console.time) {
  8860. console.time(counterName);
  8861. }
  8862. };
  8863. Tools._EndPerformanceConsole = function (counterName, condition) {
  8864. if (condition === void 0) { condition = true; }
  8865. if (!condition) {
  8866. return;
  8867. }
  8868. Tools._EndUserMark(counterName, condition);
  8869. if (console.time) {
  8870. console.timeEnd(counterName);
  8871. }
  8872. };
  8873. Object.defineProperty(Tools, "Now", {
  8874. get: function () {
  8875. if (Tools.IsWindowObjectExist() && window.performance && window.performance.now) {
  8876. return window.performance.now();
  8877. }
  8878. return new Date().getTime();
  8879. },
  8880. enumerable: true,
  8881. configurable: true
  8882. });
  8883. /**
  8884. * This method will return the name of the class used to create the instance of the given object.
  8885. * It will works only on Javascript basic data types (number, string, ...) and instance of class declared with the @className decorator.
  8886. * @param object the object to get the class name from
  8887. * @return the name of the class, will be "object" for a custom data type not using the @className decorator
  8888. */
  8889. Tools.GetClassName = function (object, isType) {
  8890. if (isType === void 0) { isType = false; }
  8891. var name = null;
  8892. if (!isType && object.getClassName) {
  8893. name = object.getClassName();
  8894. }
  8895. else {
  8896. if (object instanceof Object) {
  8897. var classObj = isType ? object : Object.getPrototypeOf(object);
  8898. name = classObj.constructor["__bjsclassName__"];
  8899. }
  8900. if (!name) {
  8901. name = typeof object;
  8902. }
  8903. }
  8904. return name;
  8905. };
  8906. Tools.First = function (array, predicate) {
  8907. for (var _i = 0, array_1 = array; _i < array_1.length; _i++) {
  8908. var el = array_1[_i];
  8909. if (predicate(el)) {
  8910. return el;
  8911. }
  8912. }
  8913. return null;
  8914. };
  8915. /**
  8916. * This method will return the name of the full name of the class, including its owning module (if any).
  8917. * It will works only on Javascript basic data types (number, string, ...) and instance of class declared with the @className decorator or implementing a method getClassName():string (in which case the module won't be specified).
  8918. * @param object the object to get the class name from
  8919. * @return a string that can have two forms: "moduleName.className" if module was specified when the class' Name was registered or "className" if there was not module specified.
  8920. */
  8921. Tools.getFullClassName = function (object, isType) {
  8922. if (isType === void 0) { isType = false; }
  8923. var className = null;
  8924. var moduleName = null;
  8925. if (!isType && object.getClassName) {
  8926. className = object.getClassName();
  8927. }
  8928. else {
  8929. if (object instanceof Object) {
  8930. var classObj = isType ? object : Object.getPrototypeOf(object);
  8931. className = classObj.constructor["__bjsclassName__"];
  8932. moduleName = classObj.constructor["__bjsmoduleName__"];
  8933. }
  8934. if (!className) {
  8935. className = typeof object;
  8936. }
  8937. }
  8938. if (!className) {
  8939. return null;
  8940. }
  8941. return ((moduleName != null) ? (moduleName + ".") : "") + className;
  8942. };
  8943. /**
  8944. * This method can be used with hashCodeFromStream when your input is an array of values that are either: number, string, boolean or custom type implementing the getHashCode():number method.
  8945. * @param array
  8946. */
  8947. Tools.arrayOrStringFeeder = function (array) {
  8948. return function (index) {
  8949. if (index >= array.length) {
  8950. return null;
  8951. }
  8952. var val = array.charCodeAt ? array.charCodeAt(index) : array[index];
  8953. if (val && val.getHashCode) {
  8954. val = val.getHashCode();
  8955. }
  8956. if (typeof val === "string") {
  8957. return Tools.hashCodeFromStream(Tools.arrayOrStringFeeder(val));
  8958. }
  8959. return val;
  8960. };
  8961. };
  8962. /**
  8963. * Compute the hashCode of a stream of number
  8964. * To compute the HashCode on a string or an Array of data types implementing the getHashCode() method, use the arrayOrStringFeeder method.
  8965. * @param feeder a callback that will be called until it returns null, each valid returned values will be used to compute the hash code.
  8966. * @return the hash code computed
  8967. */
  8968. Tools.hashCodeFromStream = function (feeder) {
  8969. // Based from here: http://stackoverflow.com/a/7616484/802124
  8970. var hash = 0;
  8971. var index = 0;
  8972. var chr = feeder(index++);
  8973. while (chr != null) {
  8974. hash = ((hash << 5) - hash) + chr;
  8975. hash |= 0; // Convert to 32bit integer
  8976. chr = feeder(index++);
  8977. }
  8978. return hash;
  8979. };
  8980. /**
  8981. * Returns a promise that resolves after the given amount of time.
  8982. * @param delay Number of milliseconds to delay
  8983. * @returns Promise that resolves after the given amount of time
  8984. */
  8985. Tools.DelayAsync = function (delay) {
  8986. return new Promise(function (resolve) {
  8987. setTimeout(function () {
  8988. resolve();
  8989. }, delay);
  8990. });
  8991. };
  8992. Tools.BaseUrl = "";
  8993. Tools.DefaultRetryStrategy = RetryStrategy.ExponentialBackoff();
  8994. /**
  8995. * Default behaviour for cors in the application.
  8996. * It can be a string if the expected behavior is identical in the entire app.
  8997. * Or a callback to be able to set it per url or on a group of them (in case of Video source for instance)
  8998. */
  8999. Tools.CorsBehavior = "anonymous";
  9000. Tools.UseFallbackTexture = true;
  9001. /**
  9002. * Use this object to register external classes like custom textures or material
  9003. * to allow the laoders to instantiate them
  9004. */
  9005. Tools.RegisteredExternalClasses = {};
  9006. // Used in case of a texture loading problem
  9007. Tools.fallbackTexture = "data:image/jpg;base64,/9j/4AAQSkZJRgABAQEAYABgAAD/4QBmRXhpZgAATU0AKgAAAAgABAEaAAUAAAABAAAAPgEbAAUAAAABAAAARgEoAAMAAAABAAIAAAExAAIAAAAQAAAATgAAAAAAAABgAAAAAQAAAGAAAAABcGFpbnQubmV0IDQuMC41AP/bAEMABAIDAwMCBAMDAwQEBAQFCQYFBQUFCwgIBgkNCw0NDQsMDA4QFBEODxMPDAwSGBITFRYXFxcOERkbGRYaFBYXFv/bAEMBBAQEBQUFCgYGChYPDA8WFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFv/AABEIAQABAAMBIgACEQEDEQH/xAAfAAABBQEBAQEBAQAAAAAAAAAAAQIDBAUGBwgJCgv/xAC1EAACAQMDAgQDBQUEBAAAAX0BAgMABBEFEiExQQYTUWEHInEUMoGRoQgjQrHBFVLR8CQzYnKCCQoWFxgZGiUmJygpKjQ1Njc4OTpDREVGR0hJSlNUVVZXWFlaY2RlZmdoaWpzdHV2d3h5eoOEhYaHiImKkpOUlZaXmJmaoqOkpaanqKmqsrO0tba3uLm6wsPExcbHyMnK0tPU1dbX2Nna4eLj5OXm5+jp6vHy8/T19vf4+fr/xAAfAQADAQEBAQEBAQEBAAAAAAAAAQIDBAUGBwgJCgv/xAC1EQACAQIEBAMEBwUEBAABAncAAQIDEQQFITEGEkFRB2FxEyIygQgUQpGhscEJIzNS8BVictEKFiQ04SXxFxgZGiYnKCkqNTY3ODk6Q0RFRkdISUpTVFVWV1hZWmNkZWZnaGlqc3R1dnd4eXqCg4SFhoeIiYqSk5SVlpeYmZqio6Slpqeoqaqys7S1tre4ubrCw8TFxsfIycrS09TV1tfY2dri4+Tl5ufo6ery8/T19vf4+fr/2gAMAwEAAhEDEQA/APH6KKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FCiiigD6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++gooooA+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gUKKKKAPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76CiiigD5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BQooooA+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/voKKKKAPl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FCiiigD6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++gooooA+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gUKKKKAPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76CiiigD5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BQooooA+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/voKKKKAPl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FCiiigD6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++gooooA+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gUKKKKAPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76P//Z";
  9008. Tools.PreprocessUrl = function (url) {
  9009. return url;
  9010. };
  9011. // Logs
  9012. Tools._NoneLogLevel = 0;
  9013. Tools._MessageLogLevel = 1;
  9014. Tools._WarningLogLevel = 2;
  9015. Tools._ErrorLogLevel = 4;
  9016. Tools._LogCache = "";
  9017. Tools.errorsCount = 0;
  9018. Tools.Log = Tools._LogEnabled;
  9019. Tools.Warn = Tools._WarnEnabled;
  9020. Tools.Error = Tools._ErrorEnabled;
  9021. // Performances
  9022. Tools._PerformanceNoneLogLevel = 0;
  9023. Tools._PerformanceUserMarkLogLevel = 1;
  9024. Tools._PerformanceConsoleLogLevel = 2;
  9025. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  9026. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  9027. return Tools;
  9028. }());
  9029. BABYLON.Tools = Tools;
  9030. /**
  9031. * This class is used to track a performance counter which is number based.
  9032. * The user has access to many properties which give statistics of different nature
  9033. *
  9034. * The implementer can track two kinds of Performance Counter: time and count
  9035. * For time you can optionally call fetchNewFrame() to notify the start of a new frame to monitor, then call beginMonitoring() to start and endMonitoring() to record the lapsed time. endMonitoring takes a newFrame parameter for you to specify if the monitored time should be set for a new frame or accumulated to the current frame being monitored.
  9036. * For count you first have to call fetchNewFrame() to notify the start of a new frame to monitor, then call addCount() how many time required to increment the count value you monitor.
  9037. */
  9038. var PerfCounter = /** @class */ (function () {
  9039. function PerfCounter() {
  9040. this._startMonitoringTime = 0;
  9041. this._min = 0;
  9042. this._max = 0;
  9043. this._average = 0;
  9044. this._lastSecAverage = 0;
  9045. this._current = 0;
  9046. this._totalValueCount = 0;
  9047. this._totalAccumulated = 0;
  9048. this._lastSecAccumulated = 0;
  9049. this._lastSecTime = 0;
  9050. this._lastSecValueCount = 0;
  9051. }
  9052. Object.defineProperty(PerfCounter.prototype, "min", {
  9053. /**
  9054. * Returns the smallest value ever
  9055. */
  9056. get: function () {
  9057. return this._min;
  9058. },
  9059. enumerable: true,
  9060. configurable: true
  9061. });
  9062. Object.defineProperty(PerfCounter.prototype, "max", {
  9063. /**
  9064. * Returns the biggest value ever
  9065. */
  9066. get: function () {
  9067. return this._max;
  9068. },
  9069. enumerable: true,
  9070. configurable: true
  9071. });
  9072. Object.defineProperty(PerfCounter.prototype, "average", {
  9073. /**
  9074. * Returns the average value since the performance counter is running
  9075. */
  9076. get: function () {
  9077. return this._average;
  9078. },
  9079. enumerable: true,
  9080. configurable: true
  9081. });
  9082. Object.defineProperty(PerfCounter.prototype, "lastSecAverage", {
  9083. /**
  9084. * Returns the average value of the last second the counter was monitored
  9085. */
  9086. get: function () {
  9087. return this._lastSecAverage;
  9088. },
  9089. enumerable: true,
  9090. configurable: true
  9091. });
  9092. Object.defineProperty(PerfCounter.prototype, "current", {
  9093. /**
  9094. * Returns the current value
  9095. */
  9096. get: function () {
  9097. return this._current;
  9098. },
  9099. enumerable: true,
  9100. configurable: true
  9101. });
  9102. Object.defineProperty(PerfCounter.prototype, "total", {
  9103. get: function () {
  9104. return this._totalAccumulated;
  9105. },
  9106. enumerable: true,
  9107. configurable: true
  9108. });
  9109. Object.defineProperty(PerfCounter.prototype, "count", {
  9110. get: function () {
  9111. return this._totalValueCount;
  9112. },
  9113. enumerable: true,
  9114. configurable: true
  9115. });
  9116. /**
  9117. * Call this method to start monitoring a new frame.
  9118. * This scenario is typically used when you accumulate monitoring time many times for a single frame, you call this method at the start of the frame, then beginMonitoring to start recording and endMonitoring(false) to accumulated the recorded time to the PerfCounter or addCount() to accumulate a monitored count.
  9119. */
  9120. PerfCounter.prototype.fetchNewFrame = function () {
  9121. this._totalValueCount++;
  9122. this._current = 0;
  9123. this._lastSecValueCount++;
  9124. };
  9125. /**
  9126. * Call this method to monitor a count of something (e.g. mesh drawn in viewport count)
  9127. * @param newCount the count value to add to the monitored count
  9128. * @param fetchResult true when it's the last time in the frame you add to the counter and you wish to update the statistics properties (min/max/average), false if you only want to update statistics.
  9129. */
  9130. PerfCounter.prototype.addCount = function (newCount, fetchResult) {
  9131. if (!PerfCounter.Enabled) {
  9132. return;
  9133. }
  9134. this._current += newCount;
  9135. if (fetchResult) {
  9136. this._fetchResult();
  9137. }
  9138. };
  9139. /**
  9140. * Start monitoring this performance counter
  9141. */
  9142. PerfCounter.prototype.beginMonitoring = function () {
  9143. if (!PerfCounter.Enabled) {
  9144. return;
  9145. }
  9146. this._startMonitoringTime = Tools.Now;
  9147. };
  9148. /**
  9149. * Compute the time lapsed since the previous beginMonitoring() call.
  9150. * @param newFrame true by default to fetch the result and monitor a new frame, if false the time monitored will be added to the current frame counter
  9151. */
  9152. PerfCounter.prototype.endMonitoring = function (newFrame) {
  9153. if (newFrame === void 0) { newFrame = true; }
  9154. if (!PerfCounter.Enabled) {
  9155. return;
  9156. }
  9157. if (newFrame) {
  9158. this.fetchNewFrame();
  9159. }
  9160. var currentTime = Tools.Now;
  9161. this._current = currentTime - this._startMonitoringTime;
  9162. if (newFrame) {
  9163. this._fetchResult();
  9164. }
  9165. };
  9166. PerfCounter.prototype._fetchResult = function () {
  9167. this._totalAccumulated += this._current;
  9168. this._lastSecAccumulated += this._current;
  9169. // Min/Max update
  9170. this._min = Math.min(this._min, this._current);
  9171. this._max = Math.max(this._max, this._current);
  9172. this._average = this._totalAccumulated / this._totalValueCount;
  9173. // Reset last sec?
  9174. var now = Tools.Now;
  9175. if ((now - this._lastSecTime) > 1000) {
  9176. this._lastSecAverage = this._lastSecAccumulated / this._lastSecValueCount;
  9177. this._lastSecTime = now;
  9178. this._lastSecAccumulated = 0;
  9179. this._lastSecValueCount = 0;
  9180. }
  9181. };
  9182. PerfCounter.Enabled = true;
  9183. return PerfCounter;
  9184. }());
  9185. BABYLON.PerfCounter = PerfCounter;
  9186. /**
  9187. * Use this className as a decorator on a given class definition to add it a name and optionally its module.
  9188. * You can then use the Tools.getClassName(obj) on an instance to retrieve its class name.
  9189. * This method is the only way to get it done in all cases, even if the .js file declaring the class is minified
  9190. * @param name The name of the class, case should be preserved
  9191. * @param module The name of the Module hosting the class, optional, but strongly recommended to specify if possible. Case should be preserved.
  9192. */
  9193. function className(name, module) {
  9194. return function (target) {
  9195. target["__bjsclassName__"] = name;
  9196. target["__bjsmoduleName__"] = (module != null) ? module : null;
  9197. };
  9198. }
  9199. BABYLON.className = className;
  9200. /**
  9201. * An implementation of a loop for asynchronous functions.
  9202. */
  9203. var AsyncLoop = /** @class */ (function () {
  9204. /**
  9205. * Constroctor.
  9206. * @param iterations the number of iterations.
  9207. * @param _fn the function to run each iteration
  9208. * @param _successCallback the callback that will be called upon succesful execution
  9209. * @param offset starting offset.
  9210. */
  9211. function AsyncLoop(iterations, _fn, _successCallback, offset) {
  9212. if (offset === void 0) { offset = 0; }
  9213. this.iterations = iterations;
  9214. this._fn = _fn;
  9215. this._successCallback = _successCallback;
  9216. this.index = offset - 1;
  9217. this._done = false;
  9218. }
  9219. /**
  9220. * Execute the next iteration. Must be called after the last iteration was finished.
  9221. */
  9222. AsyncLoop.prototype.executeNext = function () {
  9223. if (!this._done) {
  9224. if (this.index + 1 < this.iterations) {
  9225. ++this.index;
  9226. this._fn(this);
  9227. }
  9228. else {
  9229. this.breakLoop();
  9230. }
  9231. }
  9232. };
  9233. /**
  9234. * Break the loop and run the success callback.
  9235. */
  9236. AsyncLoop.prototype.breakLoop = function () {
  9237. this._done = true;
  9238. this._successCallback();
  9239. };
  9240. /**
  9241. * Helper function
  9242. */
  9243. AsyncLoop.Run = function (iterations, _fn, _successCallback, offset) {
  9244. if (offset === void 0) { offset = 0; }
  9245. var loop = new AsyncLoop(iterations, _fn, _successCallback, offset);
  9246. loop.executeNext();
  9247. return loop;
  9248. };
  9249. /**
  9250. * A for-loop that will run a given number of iterations synchronous and the rest async.
  9251. * @param iterations total number of iterations
  9252. * @param syncedIterations number of synchronous iterations in each async iteration.
  9253. * @param fn the function to call each iteration.
  9254. * @param callback a success call back that will be called when iterating stops.
  9255. * @param breakFunction a break condition (optional)
  9256. * @param timeout timeout settings for the setTimeout function. default - 0.
  9257. * @constructor
  9258. */
  9259. AsyncLoop.SyncAsyncForLoop = function (iterations, syncedIterations, fn, callback, breakFunction, timeout) {
  9260. if (timeout === void 0) { timeout = 0; }
  9261. AsyncLoop.Run(Math.ceil(iterations / syncedIterations), function (loop) {
  9262. if (breakFunction && breakFunction())
  9263. loop.breakLoop();
  9264. else {
  9265. setTimeout(function () {
  9266. for (var i = 0; i < syncedIterations; ++i) {
  9267. var iteration = (loop.index * syncedIterations) + i;
  9268. if (iteration >= iterations)
  9269. break;
  9270. fn(iteration);
  9271. if (breakFunction && breakFunction()) {
  9272. loop.breakLoop();
  9273. break;
  9274. }
  9275. }
  9276. loop.executeNext();
  9277. }, timeout);
  9278. }
  9279. }, callback);
  9280. };
  9281. return AsyncLoop;
  9282. }());
  9283. BABYLON.AsyncLoop = AsyncLoop;
  9284. })(BABYLON || (BABYLON = {}));
  9285. //# sourceMappingURL=babylon.tools.js.map
  9286. var BABYLON;
  9287. (function (BABYLON) {
  9288. var PromiseStates;
  9289. (function (PromiseStates) {
  9290. PromiseStates[PromiseStates["Pending"] = 0] = "Pending";
  9291. PromiseStates[PromiseStates["Fulfilled"] = 1] = "Fulfilled";
  9292. PromiseStates[PromiseStates["Rejected"] = 2] = "Rejected";
  9293. })(PromiseStates || (PromiseStates = {}));
  9294. var FulFillmentAgregator = /** @class */ (function () {
  9295. function FulFillmentAgregator() {
  9296. this.count = 0;
  9297. this.target = 0;
  9298. this.results = [];
  9299. }
  9300. return FulFillmentAgregator;
  9301. }());
  9302. var InternalPromise = /** @class */ (function () {
  9303. function InternalPromise(resolver) {
  9304. var _this = this;
  9305. this._state = PromiseStates.Pending;
  9306. this._children = new Array();
  9307. this._rejectWasConsumed = false;
  9308. if (!resolver) {
  9309. return;
  9310. }
  9311. try {
  9312. resolver(function (value) {
  9313. _this._resolve(value);
  9314. }, function (reason) {
  9315. _this._reject(reason);
  9316. });
  9317. }
  9318. catch (e) {
  9319. this._reject(e);
  9320. }
  9321. }
  9322. InternalPromise.prototype.catch = function (onRejected) {
  9323. return this.then(undefined, onRejected);
  9324. };
  9325. InternalPromise.prototype.then = function (onFulfilled, onRejected) {
  9326. var _this = this;
  9327. var newPromise = new InternalPromise();
  9328. newPromise._onFulfilled = onFulfilled;
  9329. newPromise._onRejected = onRejected;
  9330. // Composition
  9331. this._children.push(newPromise);
  9332. if (this._state !== PromiseStates.Pending) {
  9333. BABYLON.Tools.SetImmediate(function () {
  9334. if (_this._state === PromiseStates.Fulfilled || _this._rejectWasConsumed) {
  9335. var returnedValue = newPromise._resolve(_this._result);
  9336. if (returnedValue !== undefined && returnedValue !== null) {
  9337. if (returnedValue._state !== undefined) {
  9338. var returnedPromise = returnedValue;
  9339. newPromise._children.push(returnedPromise);
  9340. newPromise = returnedPromise;
  9341. }
  9342. else {
  9343. newPromise._result = returnedValue;
  9344. }
  9345. }
  9346. }
  9347. else {
  9348. newPromise._reject(_this._reason);
  9349. }
  9350. });
  9351. }
  9352. return newPromise;
  9353. };
  9354. InternalPromise.prototype._moveChildren = function (children) {
  9355. (_a = this._children).push.apply(_a, children.splice(0, children.length));
  9356. if (this._state === PromiseStates.Fulfilled) {
  9357. for (var _i = 0, _b = this._children; _i < _b.length; _i++) {
  9358. var child = _b[_i];
  9359. child._resolve(this._result);
  9360. }
  9361. }
  9362. else if (this._state === PromiseStates.Rejected) {
  9363. for (var _c = 0, _d = this._children; _c < _d.length; _c++) {
  9364. var child = _d[_c];
  9365. child._reject(this._reason);
  9366. }
  9367. }
  9368. var _a;
  9369. };
  9370. InternalPromise.prototype._resolve = function (value) {
  9371. try {
  9372. this._state = PromiseStates.Fulfilled;
  9373. this._result = value;
  9374. var returnedValue = null;
  9375. if (this._onFulfilled) {
  9376. returnedValue = this._onFulfilled(value);
  9377. }
  9378. if (returnedValue !== undefined && returnedValue !== null) {
  9379. if (returnedValue._state !== undefined) {
  9380. // Transmit children
  9381. var returnedPromise = returnedValue;
  9382. returnedPromise._moveChildren(this._children);
  9383. }
  9384. else {
  9385. value = returnedValue;
  9386. }
  9387. }
  9388. for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
  9389. var child = _a[_i];
  9390. child._resolve(value);
  9391. }
  9392. this._children.length = 0;
  9393. delete this._onFulfilled;
  9394. delete this._onRejected;
  9395. return returnedValue;
  9396. }
  9397. catch (e) {
  9398. this._reject(e, true);
  9399. }
  9400. return null;
  9401. };
  9402. InternalPromise.prototype._reject = function (reason, onLocalThrow) {
  9403. if (onLocalThrow === void 0) { onLocalThrow = false; }
  9404. this._state = PromiseStates.Rejected;
  9405. this._reason = reason;
  9406. if (this._onRejected && !onLocalThrow) {
  9407. try {
  9408. this._onRejected(reason);
  9409. this._rejectWasConsumed = true;
  9410. }
  9411. catch (e) {
  9412. reason = e;
  9413. }
  9414. }
  9415. for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
  9416. var child = _a[_i];
  9417. if (this._rejectWasConsumed) {
  9418. child._resolve(null);
  9419. }
  9420. else {
  9421. child._reject(reason);
  9422. }
  9423. }
  9424. this._children.length = 0;
  9425. delete this._onFulfilled;
  9426. delete this._onRejected;
  9427. };
  9428. InternalPromise.resolve = function (value) {
  9429. var newPromise = new InternalPromise();
  9430. newPromise._resolve(value);
  9431. return newPromise;
  9432. };
  9433. InternalPromise._RegisterForFulfillment = function (promise, agregator, index) {
  9434. promise.then(function (value) {
  9435. agregator.results[index] = value;
  9436. agregator.count++;
  9437. if (agregator.count === agregator.target) {
  9438. agregator.rootPromise._resolve(agregator.results);
  9439. }
  9440. return null;
  9441. }, function (reason) {
  9442. if (agregator.rootPromise._state !== PromiseStates.Rejected) {
  9443. agregator.rootPromise._reject(reason);
  9444. }
  9445. });
  9446. };
  9447. InternalPromise.all = function (promises) {
  9448. var newPromise = new InternalPromise();
  9449. var agregator = new FulFillmentAgregator();
  9450. agregator.target = promises.length;
  9451. agregator.rootPromise = newPromise;
  9452. if (promises.length) {
  9453. for (var index = 0; index < promises.length; index++) {
  9454. InternalPromise._RegisterForFulfillment(promises[index], agregator, index);
  9455. }
  9456. }
  9457. else {
  9458. newPromise._resolve([]);
  9459. }
  9460. return newPromise;
  9461. };
  9462. return InternalPromise;
  9463. }());
  9464. /**
  9465. * Helper class that provides a small promise polyfill
  9466. */
  9467. var PromisePolyfill = /** @class */ (function () {
  9468. function PromisePolyfill() {
  9469. }
  9470. /**
  9471. * Static function used to check if the polyfill is required
  9472. * If this is the case then the function will inject the polyfill to window.Promise
  9473. * @param force defines a boolean used to force the injection (mostly for testing purposes)
  9474. */
  9475. PromisePolyfill.Apply = function (force) {
  9476. if (force === void 0) { force = false; }
  9477. if (force || typeof Promise === 'undefined') {
  9478. var root = window;
  9479. root.Promise = InternalPromise;
  9480. }
  9481. };
  9482. return PromisePolyfill;
  9483. }());
  9484. BABYLON.PromisePolyfill = PromisePolyfill;
  9485. })(BABYLON || (BABYLON = {}));
  9486. //# sourceMappingURL=babylon.promise.js.map
  9487. var BABYLON;
  9488. (function (BABYLON) {
  9489. var _AlphaState = /** @class */ (function () {
  9490. /**
  9491. * Initializes the state.
  9492. */
  9493. function _AlphaState() {
  9494. this._isAlphaBlendDirty = false;
  9495. this._isBlendFunctionParametersDirty = false;
  9496. this._isBlendEquationParametersDirty = false;
  9497. this._isBlendConstantsDirty = false;
  9498. this._alphaBlend = false;
  9499. this._blendFunctionParameters = new Array(4);
  9500. this._blendEquationParameters = new Array(2);
  9501. this._blendConstants = new Array(4);
  9502. this.reset();
  9503. }
  9504. Object.defineProperty(_AlphaState.prototype, "isDirty", {
  9505. get: function () {
  9506. return this._isAlphaBlendDirty || this._isBlendFunctionParametersDirty;
  9507. },
  9508. enumerable: true,
  9509. configurable: true
  9510. });
  9511. Object.defineProperty(_AlphaState.prototype, "alphaBlend", {
  9512. get: function () {
  9513. return this._alphaBlend;
  9514. },
  9515. set: function (value) {
  9516. if (this._alphaBlend === value) {
  9517. return;
  9518. }
  9519. this._alphaBlend = value;
  9520. this._isAlphaBlendDirty = true;
  9521. },
  9522. enumerable: true,
  9523. configurable: true
  9524. });
  9525. _AlphaState.prototype.setAlphaBlendConstants = function (r, g, b, a) {
  9526. if (this._blendConstants[0] === r &&
  9527. this._blendConstants[1] === g &&
  9528. this._blendConstants[2] === b &&
  9529. this._blendConstants[3] === a) {
  9530. return;
  9531. }
  9532. this._blendConstants[0] = r;
  9533. this._blendConstants[1] = g;
  9534. this._blendConstants[2] = b;
  9535. this._blendConstants[3] = a;
  9536. this._isBlendConstantsDirty = true;
  9537. };
  9538. _AlphaState.prototype.setAlphaBlendFunctionParameters = function (value0, value1, value2, value3) {
  9539. if (this._blendFunctionParameters[0] === value0 &&
  9540. this._blendFunctionParameters[1] === value1 &&
  9541. this._blendFunctionParameters[2] === value2 &&
  9542. this._blendFunctionParameters[3] === value3) {
  9543. return;
  9544. }
  9545. this._blendFunctionParameters[0] = value0;
  9546. this._blendFunctionParameters[1] = value1;
  9547. this._blendFunctionParameters[2] = value2;
  9548. this._blendFunctionParameters[3] = value3;
  9549. this._isBlendFunctionParametersDirty = true;
  9550. };
  9551. _AlphaState.prototype.setAlphaEquationParameters = function (rgb, alpha) {
  9552. if (this._blendEquationParameters[0] === rgb &&
  9553. this._blendEquationParameters[1] === alpha) {
  9554. return;
  9555. }
  9556. this._blendEquationParameters[0] = rgb;
  9557. this._blendEquationParameters[1] = alpha;
  9558. this._isBlendEquationParametersDirty = true;
  9559. };
  9560. _AlphaState.prototype.reset = function () {
  9561. this._alphaBlend = false;
  9562. this._blendFunctionParameters[0] = null;
  9563. this._blendFunctionParameters[1] = null;
  9564. this._blendFunctionParameters[2] = null;
  9565. this._blendFunctionParameters[3] = null;
  9566. this._blendEquationParameters[0] = null;
  9567. this._blendEquationParameters[1] = null;
  9568. this._blendConstants[0] = null;
  9569. this._blendConstants[1] = null;
  9570. this._blendConstants[2] = null;
  9571. this._blendConstants[3] = null;
  9572. this._isAlphaBlendDirty = true;
  9573. this._isBlendFunctionParametersDirty = false;
  9574. this._isBlendEquationParametersDirty = false;
  9575. this._isBlendConstantsDirty = false;
  9576. };
  9577. _AlphaState.prototype.apply = function (gl) {
  9578. if (!this.isDirty) {
  9579. return;
  9580. }
  9581. // Alpha blend
  9582. if (this._isAlphaBlendDirty) {
  9583. if (this._alphaBlend) {
  9584. gl.enable(gl.BLEND);
  9585. }
  9586. else {
  9587. gl.disable(gl.BLEND);
  9588. }
  9589. this._isAlphaBlendDirty = false;
  9590. }
  9591. // Alpha function
  9592. if (this._isBlendFunctionParametersDirty) {
  9593. gl.blendFuncSeparate(this._blendFunctionParameters[0], this._blendFunctionParameters[1], this._blendFunctionParameters[2], this._blendFunctionParameters[3]);
  9594. this._isBlendFunctionParametersDirty = false;
  9595. }
  9596. // Alpha equation
  9597. if (this._isBlendEquationParametersDirty) {
  9598. gl.blendEquationSeparate(this._isBlendEquationParametersDirty[0], this._isBlendEquationParametersDirty[1]);
  9599. this._isBlendEquationParametersDirty = false;
  9600. }
  9601. // Constants
  9602. if (this._isBlendConstantsDirty) {
  9603. gl.blendColor(this._blendConstants[0], this._blendConstants[1], this._blendConstants[2], this._blendConstants[3]);
  9604. this._isBlendConstantsDirty = false;
  9605. }
  9606. };
  9607. return _AlphaState;
  9608. }());
  9609. BABYLON._AlphaState = _AlphaState;
  9610. })(BABYLON || (BABYLON = {}));
  9611. //# sourceMappingURL=babylon.alphaCullingState.js.map
  9612. var BABYLON;
  9613. (function (BABYLON) {
  9614. var _DepthCullingState = /** @class */ (function () {
  9615. /**
  9616. * Initializes the state.
  9617. */
  9618. function _DepthCullingState() {
  9619. this._isDepthTestDirty = false;
  9620. this._isDepthMaskDirty = false;
  9621. this._isDepthFuncDirty = false;
  9622. this._isCullFaceDirty = false;
  9623. this._isCullDirty = false;
  9624. this._isZOffsetDirty = false;
  9625. this._isFrontFaceDirty = false;
  9626. this.reset();
  9627. }
  9628. Object.defineProperty(_DepthCullingState.prototype, "isDirty", {
  9629. get: function () {
  9630. return this._isDepthFuncDirty || this._isDepthTestDirty || this._isDepthMaskDirty || this._isCullFaceDirty || this._isCullDirty || this._isZOffsetDirty || this._isFrontFaceDirty;
  9631. },
  9632. enumerable: true,
  9633. configurable: true
  9634. });
  9635. Object.defineProperty(_DepthCullingState.prototype, "zOffset", {
  9636. get: function () {
  9637. return this._zOffset;
  9638. },
  9639. set: function (value) {
  9640. if (this._zOffset === value) {
  9641. return;
  9642. }
  9643. this._zOffset = value;
  9644. this._isZOffsetDirty = true;
  9645. },
  9646. enumerable: true,
  9647. configurable: true
  9648. });
  9649. Object.defineProperty(_DepthCullingState.prototype, "cullFace", {
  9650. get: function () {
  9651. return this._cullFace;
  9652. },
  9653. set: function (value) {
  9654. if (this._cullFace === value) {
  9655. return;
  9656. }
  9657. this._cullFace = value;
  9658. this._isCullFaceDirty = true;
  9659. },
  9660. enumerable: true,
  9661. configurable: true
  9662. });
  9663. Object.defineProperty(_DepthCullingState.prototype, "cull", {
  9664. get: function () {
  9665. return this._cull;
  9666. },
  9667. set: function (value) {
  9668. if (this._cull === value) {
  9669. return;
  9670. }
  9671. this._cull = value;
  9672. this._isCullDirty = true;
  9673. },
  9674. enumerable: true,
  9675. configurable: true
  9676. });
  9677. Object.defineProperty(_DepthCullingState.prototype, "depthFunc", {
  9678. get: function () {
  9679. return this._depthFunc;
  9680. },
  9681. set: function (value) {
  9682. if (this._depthFunc === value) {
  9683. return;
  9684. }
  9685. this._depthFunc = value;
  9686. this._isDepthFuncDirty = true;
  9687. },
  9688. enumerable: true,
  9689. configurable: true
  9690. });
  9691. Object.defineProperty(_DepthCullingState.prototype, "depthMask", {
  9692. get: function () {
  9693. return this._depthMask;
  9694. },
  9695. set: function (value) {
  9696. if (this._depthMask === value) {
  9697. return;
  9698. }
  9699. this._depthMask = value;
  9700. this._isDepthMaskDirty = true;
  9701. },
  9702. enumerable: true,
  9703. configurable: true
  9704. });
  9705. Object.defineProperty(_DepthCullingState.prototype, "depthTest", {
  9706. get: function () {
  9707. return this._depthTest;
  9708. },
  9709. set: function (value) {
  9710. if (this._depthTest === value) {
  9711. return;
  9712. }
  9713. this._depthTest = value;
  9714. this._isDepthTestDirty = true;
  9715. },
  9716. enumerable: true,
  9717. configurable: true
  9718. });
  9719. Object.defineProperty(_DepthCullingState.prototype, "frontFace", {
  9720. get: function () {
  9721. return this._frontFace;
  9722. },
  9723. set: function (value) {
  9724. if (this._frontFace === value) {
  9725. return;
  9726. }
  9727. this._frontFace = value;
  9728. this._isFrontFaceDirty = true;
  9729. },
  9730. enumerable: true,
  9731. configurable: true
  9732. });
  9733. _DepthCullingState.prototype.reset = function () {
  9734. this._depthMask = true;
  9735. this._depthTest = true;
  9736. this._depthFunc = null;
  9737. this._cullFace = null;
  9738. this._cull = null;
  9739. this._zOffset = 0;
  9740. this._frontFace = null;
  9741. this._isDepthTestDirty = true;
  9742. this._isDepthMaskDirty = true;
  9743. this._isDepthFuncDirty = false;
  9744. this._isCullFaceDirty = false;
  9745. this._isCullDirty = false;
  9746. this._isZOffsetDirty = false;
  9747. this._isFrontFaceDirty = false;
  9748. };
  9749. _DepthCullingState.prototype.apply = function (gl) {
  9750. if (!this.isDirty) {
  9751. return;
  9752. }
  9753. // Cull
  9754. if (this._isCullDirty) {
  9755. if (this.cull) {
  9756. gl.enable(gl.CULL_FACE);
  9757. }
  9758. else {
  9759. gl.disable(gl.CULL_FACE);
  9760. }
  9761. this._isCullDirty = false;
  9762. }
  9763. // Cull face
  9764. if (this._isCullFaceDirty) {
  9765. gl.cullFace(this.cullFace);
  9766. this._isCullFaceDirty = false;
  9767. }
  9768. // Depth mask
  9769. if (this._isDepthMaskDirty) {
  9770. gl.depthMask(this.depthMask);
  9771. this._isDepthMaskDirty = false;
  9772. }
  9773. // Depth test
  9774. if (this._isDepthTestDirty) {
  9775. if (this.depthTest) {
  9776. gl.enable(gl.DEPTH_TEST);
  9777. }
  9778. else {
  9779. gl.disable(gl.DEPTH_TEST);
  9780. }
  9781. this._isDepthTestDirty = false;
  9782. }
  9783. // Depth func
  9784. if (this._isDepthFuncDirty) {
  9785. gl.depthFunc(this.depthFunc);
  9786. this._isDepthFuncDirty = false;
  9787. }
  9788. // zOffset
  9789. if (this._isZOffsetDirty) {
  9790. if (this.zOffset) {
  9791. gl.enable(gl.POLYGON_OFFSET_FILL);
  9792. gl.polygonOffset(this.zOffset, 0);
  9793. }
  9794. else {
  9795. gl.disable(gl.POLYGON_OFFSET_FILL);
  9796. }
  9797. this._isZOffsetDirty = false;
  9798. }
  9799. // Front face
  9800. if (this._isFrontFaceDirty) {
  9801. gl.frontFace(this.frontFace);
  9802. this._isFrontFaceDirty = false;
  9803. }
  9804. };
  9805. return _DepthCullingState;
  9806. }());
  9807. BABYLON._DepthCullingState = _DepthCullingState;
  9808. })(BABYLON || (BABYLON = {}));
  9809. //# sourceMappingURL=babylon.depthCullingState.js.map
  9810. var BABYLON;
  9811. (function (BABYLON) {
  9812. var _StencilState = /** @class */ (function () {
  9813. function _StencilState() {
  9814. this._isStencilTestDirty = false;
  9815. this._isStencilMaskDirty = false;
  9816. this._isStencilFuncDirty = false;
  9817. this._isStencilOpDirty = false;
  9818. this.reset();
  9819. }
  9820. Object.defineProperty(_StencilState.prototype, "isDirty", {
  9821. get: function () {
  9822. return this._isStencilTestDirty || this._isStencilMaskDirty || this._isStencilFuncDirty || this._isStencilOpDirty;
  9823. },
  9824. enumerable: true,
  9825. configurable: true
  9826. });
  9827. Object.defineProperty(_StencilState.prototype, "stencilFunc", {
  9828. get: function () {
  9829. return this._stencilFunc;
  9830. },
  9831. set: function (value) {
  9832. if (this._stencilFunc === value) {
  9833. return;
  9834. }
  9835. this._stencilFunc = value;
  9836. this._isStencilFuncDirty = true;
  9837. },
  9838. enumerable: true,
  9839. configurable: true
  9840. });
  9841. Object.defineProperty(_StencilState.prototype, "stencilFuncRef", {
  9842. get: function () {
  9843. return this._stencilFuncRef;
  9844. },
  9845. set: function (value) {
  9846. if (this._stencilFuncRef === value) {
  9847. return;
  9848. }
  9849. this._stencilFuncRef = value;
  9850. this._isStencilFuncDirty = true;
  9851. },
  9852. enumerable: true,
  9853. configurable: true
  9854. });
  9855. Object.defineProperty(_StencilState.prototype, "stencilFuncMask", {
  9856. get: function () {
  9857. return this._stencilFuncMask;
  9858. },
  9859. set: function (value) {
  9860. if (this._stencilFuncMask === value) {
  9861. return;
  9862. }
  9863. this._stencilFuncMask = value;
  9864. this._isStencilFuncDirty = true;
  9865. },
  9866. enumerable: true,
  9867. configurable: true
  9868. });
  9869. Object.defineProperty(_StencilState.prototype, "stencilOpStencilFail", {
  9870. get: function () {
  9871. return this._stencilOpStencilFail;
  9872. },
  9873. set: function (value) {
  9874. if (this._stencilOpStencilFail === value) {
  9875. return;
  9876. }
  9877. this._stencilOpStencilFail = value;
  9878. this._isStencilOpDirty = true;
  9879. },
  9880. enumerable: true,
  9881. configurable: true
  9882. });
  9883. Object.defineProperty(_StencilState.prototype, "stencilOpDepthFail", {
  9884. get: function () {
  9885. return this._stencilOpDepthFail;
  9886. },
  9887. set: function (value) {
  9888. if (this._stencilOpDepthFail === value) {
  9889. return;
  9890. }
  9891. this._stencilOpDepthFail = value;
  9892. this._isStencilOpDirty = true;
  9893. },
  9894. enumerable: true,
  9895. configurable: true
  9896. });
  9897. Object.defineProperty(_StencilState.prototype, "stencilOpStencilDepthPass", {
  9898. get: function () {
  9899. return this._stencilOpStencilDepthPass;
  9900. },
  9901. set: function (value) {
  9902. if (this._stencilOpStencilDepthPass === value) {
  9903. return;
  9904. }
  9905. this._stencilOpStencilDepthPass = value;
  9906. this._isStencilOpDirty = true;
  9907. },
  9908. enumerable: true,
  9909. configurable: true
  9910. });
  9911. Object.defineProperty(_StencilState.prototype, "stencilMask", {
  9912. get: function () {
  9913. return this._stencilMask;
  9914. },
  9915. set: function (value) {
  9916. if (this._stencilMask === value) {
  9917. return;
  9918. }
  9919. this._stencilMask = value;
  9920. this._isStencilMaskDirty = true;
  9921. },
  9922. enumerable: true,
  9923. configurable: true
  9924. });
  9925. Object.defineProperty(_StencilState.prototype, "stencilTest", {
  9926. get: function () {
  9927. return this._stencilTest;
  9928. },
  9929. set: function (value) {
  9930. if (this._stencilTest === value) {
  9931. return;
  9932. }
  9933. this._stencilTest = value;
  9934. this._isStencilTestDirty = true;
  9935. },
  9936. enumerable: true,
  9937. configurable: true
  9938. });
  9939. _StencilState.prototype.reset = function () {
  9940. this._stencilTest = false;
  9941. this._stencilMask = 0xFF;
  9942. this._stencilFunc = BABYLON.Engine.ALWAYS;
  9943. this._stencilFuncRef = 1;
  9944. this._stencilFuncMask = 0xFF;
  9945. this._stencilOpStencilFail = BABYLON.Engine.KEEP;
  9946. this._stencilOpDepthFail = BABYLON.Engine.KEEP;
  9947. this._stencilOpStencilDepthPass = BABYLON.Engine.REPLACE;
  9948. this._isStencilTestDirty = true;
  9949. this._isStencilMaskDirty = true;
  9950. this._isStencilFuncDirty = true;
  9951. this._isStencilOpDirty = true;
  9952. };
  9953. _StencilState.prototype.apply = function (gl) {
  9954. if (!this.isDirty) {
  9955. return;
  9956. }
  9957. // Stencil test
  9958. if (this._isStencilTestDirty) {
  9959. if (this.stencilTest) {
  9960. gl.enable(gl.STENCIL_TEST);
  9961. }
  9962. else {
  9963. gl.disable(gl.STENCIL_TEST);
  9964. }
  9965. this._isStencilTestDirty = false;
  9966. }
  9967. // Stencil mask
  9968. if (this._isStencilMaskDirty) {
  9969. gl.stencilMask(this.stencilMask);
  9970. this._isStencilMaskDirty = false;
  9971. }
  9972. // Stencil func
  9973. if (this._isStencilFuncDirty) {
  9974. gl.stencilFunc(this.stencilFunc, this.stencilFuncRef, this.stencilFuncMask);
  9975. this._isStencilFuncDirty = false;
  9976. }
  9977. // Stencil op
  9978. if (this._isStencilOpDirty) {
  9979. gl.stencilOp(this.stencilOpStencilFail, this.stencilOpDepthFail, this.stencilOpStencilDepthPass);
  9980. this._isStencilOpDirty = false;
  9981. }
  9982. };
  9983. return _StencilState;
  9984. }());
  9985. BABYLON._StencilState = _StencilState;
  9986. })(BABYLON || (BABYLON = {}));
  9987. //# sourceMappingURL=babylon.stencilState.js.map
  9988. var __assign = (this && this.__assign) || Object.assign || function(t) {
  9989. for (var s, i = 1, n = arguments.length; i < n; i++) {
  9990. s = arguments[i];
  9991. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  9992. t[p] = s[p];
  9993. }
  9994. return t;
  9995. };
  9996. var BABYLON;
  9997. (function (BABYLON) {
  9998. var compileShader = function (gl, source, type, defines, shaderVersion) {
  9999. return compileRawShader(gl, shaderVersion + (defines ? defines + "\n" : "") + source, type);
  10000. };
  10001. var compileRawShader = function (gl, source, type) {
  10002. var shader = gl.createShader(type === "vertex" ? gl.VERTEX_SHADER : gl.FRAGMENT_SHADER);
  10003. gl.shaderSource(shader, source);
  10004. gl.compileShader(shader);
  10005. if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
  10006. var log = gl.getShaderInfoLog(shader);
  10007. if (log) {
  10008. throw new Error(log);
  10009. }
  10010. }
  10011. if (!shader) {
  10012. throw new Error("Something went wrong while compile the shader.");
  10013. }
  10014. return shader;
  10015. };
  10016. var getSamplingParameters = function (samplingMode, generateMipMaps, gl) {
  10017. var magFilter = gl.NEAREST;
  10018. var minFilter = gl.NEAREST;
  10019. switch (samplingMode) {
  10020. case BABYLON.Texture.BILINEAR_SAMPLINGMODE:
  10021. magFilter = gl.LINEAR;
  10022. if (generateMipMaps) {
  10023. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  10024. }
  10025. else {
  10026. minFilter = gl.LINEAR;
  10027. }
  10028. break;
  10029. case BABYLON.Texture.TRILINEAR_SAMPLINGMODE:
  10030. magFilter = gl.LINEAR;
  10031. if (generateMipMaps) {
  10032. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  10033. }
  10034. else {
  10035. minFilter = gl.LINEAR;
  10036. }
  10037. break;
  10038. case BABYLON.Texture.NEAREST_SAMPLINGMODE:
  10039. magFilter = gl.NEAREST;
  10040. if (generateMipMaps) {
  10041. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  10042. }
  10043. else {
  10044. minFilter = gl.NEAREST;
  10045. }
  10046. break;
  10047. case BABYLON.Texture.NEAREST_NEAREST_MIPNEAREST:
  10048. magFilter = gl.NEAREST;
  10049. if (generateMipMaps) {
  10050. minFilter = gl.NEAREST_MIPMAP_NEAREST;
  10051. }
  10052. else {
  10053. minFilter = gl.NEAREST;
  10054. }
  10055. break;
  10056. case BABYLON.Texture.NEAREST_LINEAR_MIPNEAREST:
  10057. magFilter = gl.NEAREST;
  10058. if (generateMipMaps) {
  10059. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  10060. }
  10061. else {
  10062. minFilter = gl.LINEAR;
  10063. }
  10064. break;
  10065. case BABYLON.Texture.NEAREST_LINEAR_MIPLINEAR:
  10066. magFilter = gl.NEAREST;
  10067. if (generateMipMaps) {
  10068. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  10069. }
  10070. else {
  10071. minFilter = gl.LINEAR;
  10072. }
  10073. break;
  10074. case BABYLON.Texture.NEAREST_LINEAR:
  10075. magFilter = gl.NEAREST;
  10076. minFilter = gl.LINEAR;
  10077. break;
  10078. case BABYLON.Texture.NEAREST_NEAREST:
  10079. magFilter = gl.NEAREST;
  10080. minFilter = gl.NEAREST;
  10081. break;
  10082. case BABYLON.Texture.LINEAR_NEAREST_MIPNEAREST:
  10083. magFilter = gl.LINEAR;
  10084. if (generateMipMaps) {
  10085. minFilter = gl.NEAREST_MIPMAP_NEAREST;
  10086. }
  10087. else {
  10088. minFilter = gl.NEAREST;
  10089. }
  10090. break;
  10091. case BABYLON.Texture.LINEAR_NEAREST_MIPLINEAR:
  10092. magFilter = gl.LINEAR;
  10093. if (generateMipMaps) {
  10094. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  10095. }
  10096. else {
  10097. minFilter = gl.NEAREST;
  10098. }
  10099. break;
  10100. case BABYLON.Texture.LINEAR_LINEAR:
  10101. magFilter = gl.LINEAR;
  10102. minFilter = gl.LINEAR;
  10103. break;
  10104. case BABYLON.Texture.LINEAR_NEAREST:
  10105. magFilter = gl.LINEAR;
  10106. minFilter = gl.NEAREST;
  10107. break;
  10108. }
  10109. return {
  10110. min: minFilter,
  10111. mag: magFilter
  10112. };
  10113. };
  10114. var partialLoadImg = function (url, index, loadedImages, scene, onfinish, onErrorCallBack) {
  10115. if (onErrorCallBack === void 0) { onErrorCallBack = null; }
  10116. var img;
  10117. var onload = function () {
  10118. loadedImages[index] = img;
  10119. loadedImages._internalCount++;
  10120. if (scene) {
  10121. scene._removePendingData(img);
  10122. }
  10123. if (loadedImages._internalCount === 6) {
  10124. onfinish(loadedImages);
  10125. }
  10126. };
  10127. var onerror = function (message, exception) {
  10128. if (scene) {
  10129. scene._removePendingData(img);
  10130. }
  10131. if (onErrorCallBack) {
  10132. onErrorCallBack(message, exception);
  10133. }
  10134. };
  10135. img = BABYLON.Tools.LoadImage(url, onload, onerror, scene ? scene.database : null);
  10136. if (scene) {
  10137. scene._addPendingData(img);
  10138. }
  10139. };
  10140. var cascadeLoadImgs = function (rootUrl, scene, onfinish, files, onError) {
  10141. if (onError === void 0) { onError = null; }
  10142. var loadedImages = [];
  10143. loadedImages._internalCount = 0;
  10144. for (var index = 0; index < 6; index++) {
  10145. partialLoadImg(files[index], index, loadedImages, scene, onfinish, onError);
  10146. }
  10147. };
  10148. var BufferPointer = /** @class */ (function () {
  10149. function BufferPointer() {
  10150. }
  10151. return BufferPointer;
  10152. }());
  10153. var InstancingAttributeInfo = /** @class */ (function () {
  10154. function InstancingAttributeInfo() {
  10155. }
  10156. return InstancingAttributeInfo;
  10157. }());
  10158. BABYLON.InstancingAttributeInfo = InstancingAttributeInfo;
  10159. /**
  10160. * Define options used to create a render target texture
  10161. */
  10162. var RenderTargetCreationOptions = /** @class */ (function () {
  10163. function RenderTargetCreationOptions() {
  10164. }
  10165. return RenderTargetCreationOptions;
  10166. }());
  10167. BABYLON.RenderTargetCreationOptions = RenderTargetCreationOptions;
  10168. /**
  10169. * Regroup several parameters relative to the browser in use
  10170. */
  10171. var EngineCapabilities = /** @class */ (function () {
  10172. function EngineCapabilities() {
  10173. }
  10174. return EngineCapabilities;
  10175. }());
  10176. BABYLON.EngineCapabilities = EngineCapabilities;
  10177. /**
  10178. * The engine class is responsible for interfacing with all lower-level APIs such as WebGL and Audio.
  10179. */
  10180. var Engine = /** @class */ (function () {
  10181. /**
  10182. * @constructor
  10183. * @param canvasOrContext defines the canvas or WebGL context to use for rendering
  10184. * @param antialias defines enable antialiasing (default: false)
  10185. * @param options defines further options to be sent to the getContext() function
  10186. * @param adaptToDeviceRatio defines whether to adapt to the device's viewport characteristics (default: false)
  10187. */
  10188. function Engine(canvasOrContext, antialias, options, adaptToDeviceRatio) {
  10189. if (adaptToDeviceRatio === void 0) { adaptToDeviceRatio = false; }
  10190. var _this = this;
  10191. // Public members
  10192. this.forcePOTTextures = false;
  10193. this.isFullscreen = false;
  10194. this.isPointerLock = false;
  10195. this.cullBackFaces = true;
  10196. this.renderEvenInBackground = true;
  10197. this.preventCacheWipeBetweenFrames = false;
  10198. // To enable/disable IDB support and avoid XHR on .manifest
  10199. this.enableOfflineSupport = false;
  10200. this.scenes = new Array();
  10201. this.postProcesses = new Array();
  10202. // Observables
  10203. /**
  10204. * Observable event triggered each time the rendering canvas is resized
  10205. */
  10206. this.onResizeObservable = new BABYLON.Observable();
  10207. /**
  10208. * Observable event triggered each time the canvas loses focus
  10209. */
  10210. this.onCanvasBlurObservable = new BABYLON.Observable();
  10211. /**
  10212. * Observable event triggered each time the canvas gains focus
  10213. */
  10214. this.onCanvasFocusObservable = new BABYLON.Observable();
  10215. /**
  10216. * Observable event triggered each time the canvas receives pointerout event
  10217. */
  10218. this.onCanvasPointerOutObservable = new BABYLON.Observable();
  10219. /**
  10220. * Observable event triggered before each texture is initialized
  10221. */
  10222. this.onBeforeTextureInitObservable = new BABYLON.Observable();
  10223. //WebVR
  10224. this._vrDisplay = undefined;
  10225. this._vrSupported = false;
  10226. this._vrExclusivePointerMode = false;
  10227. // Uniform buffers list
  10228. this.disableUniformBuffers = false;
  10229. this._uniformBuffers = new Array();
  10230. // Observables
  10231. /**
  10232. * Observable raised when the engine begins a new frame
  10233. */
  10234. this.onBeginFrameObservable = new BABYLON.Observable();
  10235. /**
  10236. * Observable raised when the engine ends the current frame
  10237. */
  10238. this.onEndFrameObservable = new BABYLON.Observable();
  10239. /**
  10240. * Observable raised when the engine is about to compile a shader
  10241. */
  10242. this.onBeforeShaderCompilationObservable = new BABYLON.Observable();
  10243. /**
  10244. * Observable raised when the engine has jsut compiled a shader
  10245. */
  10246. this.onAfterShaderCompilationObservable = new BABYLON.Observable();
  10247. this._windowIsBackground = false;
  10248. this._webGLVersion = 1.0;
  10249. this._badOS = false;
  10250. this._badDesktopOS = false;
  10251. /**
  10252. * Gets or sets a value indicating if we want to disable texture binding optmization.
  10253. * This could be required on some buggy drivers which wants to have textures bound in a progressive order
  10254. * By default Babylon.js will try to let textures bound where they are and only update the samplers to point where the texture is.
  10255. */
  10256. this.disableTextureBindingOptimization = false;
  10257. this.onVRDisplayChangedObservable = new BABYLON.Observable();
  10258. this.onVRRequestPresentComplete = new BABYLON.Observable();
  10259. this.onVRRequestPresentStart = new BABYLON.Observable();
  10260. this._colorWrite = true;
  10261. this._drawCalls = new BABYLON.PerfCounter();
  10262. this._textureCollisions = new BABYLON.PerfCounter();
  10263. this._renderingQueueLaunched = false;
  10264. this._activeRenderLoops = new Array();
  10265. // Deterministic lockstepMaxSteps
  10266. this._deterministicLockstep = false;
  10267. this._lockstepMaxSteps = 4;
  10268. // Lost context
  10269. this.onContextLostObservable = new BABYLON.Observable();
  10270. this.onContextRestoredObservable = new BABYLON.Observable();
  10271. this._contextWasLost = false;
  10272. this._doNotHandleContextLost = false;
  10273. // FPS
  10274. this._performanceMonitor = new BABYLON.PerformanceMonitor();
  10275. this._fps = 60;
  10276. this._deltaTime = 0;
  10277. /**
  10278. * Turn this value on if you want to pause FPS computation when in background
  10279. */
  10280. this.disablePerformanceMonitorInBackground = false;
  10281. // States
  10282. this._depthCullingState = new BABYLON._DepthCullingState();
  10283. this._stencilState = new BABYLON._StencilState();
  10284. this._alphaState = new BABYLON._AlphaState();
  10285. this._alphaMode = Engine.ALPHA_DISABLE;
  10286. // Cache
  10287. this._internalTexturesCache = new Array();
  10288. this._activeChannel = 0;
  10289. this._currentTextureChannel = -1;
  10290. this._boundTexturesCache = {};
  10291. this._compiledEffects = {};
  10292. this._vertexAttribArraysEnabled = [];
  10293. this._uintIndicesCurrentlySet = false;
  10294. this._currentBoundBuffer = new Array();
  10295. this._currentBufferPointers = new Array();
  10296. this._currentInstanceLocations = new Array();
  10297. this._currentInstanceBuffers = new Array();
  10298. this._firstBoundInternalTextureTracker = new BABYLON.DummyInternalTextureTracker();
  10299. this._lastBoundInternalTextureTracker = new BABYLON.DummyInternalTextureTracker();
  10300. this._vaoRecordInProgress = false;
  10301. this._mustWipeVertexAttributes = false;
  10302. this._nextFreeTextureSlots = new Array();
  10303. this._maxSimultaneousTextures = 0;
  10304. this._activeRequests = new Array();
  10305. // Hardware supported Compressed Textures
  10306. this._texturesSupported = new Array();
  10307. this._onVRFullScreenTriggered = function () {
  10308. if (_this._vrDisplay && _this._vrDisplay.isPresenting) {
  10309. //get the old size before we change
  10310. _this._oldSize = new BABYLON.Size(_this.getRenderWidth(), _this.getRenderHeight());
  10311. _this._oldHardwareScaleFactor = _this.getHardwareScalingLevel();
  10312. //get the width and height, change the render size
  10313. var leftEye = _this._vrDisplay.getEyeParameters('left');
  10314. _this.setHardwareScalingLevel(1);
  10315. _this.setSize(leftEye.renderWidth * 2, leftEye.renderHeight);
  10316. }
  10317. else {
  10318. _this.setHardwareScalingLevel(_this._oldHardwareScaleFactor);
  10319. _this.setSize(_this._oldSize.width, _this._oldSize.height);
  10320. }
  10321. };
  10322. this._boundUniforms = {};
  10323. // Register promises
  10324. BABYLON.PromisePolyfill.Apply();
  10325. var canvas = null;
  10326. Engine.Instances.push(this);
  10327. if (!canvasOrContext) {
  10328. return;
  10329. }
  10330. options = options || {};
  10331. if (canvasOrContext.getContext) {
  10332. canvas = canvasOrContext;
  10333. this._renderingCanvas = canvas;
  10334. if (antialias != null) {
  10335. options.antialias = antialias;
  10336. }
  10337. if (options.deterministicLockstep === undefined) {
  10338. options.deterministicLockstep = false;
  10339. }
  10340. if (options.lockstepMaxSteps === undefined) {
  10341. options.lockstepMaxSteps = 4;
  10342. }
  10343. if (options.preserveDrawingBuffer === undefined) {
  10344. options.preserveDrawingBuffer = false;
  10345. }
  10346. if (options.audioEngine === undefined) {
  10347. options.audioEngine = true;
  10348. }
  10349. if (options.stencil === undefined) {
  10350. options.stencil = true;
  10351. }
  10352. this._deterministicLockstep = options.deterministicLockstep;
  10353. this._lockstepMaxSteps = options.lockstepMaxSteps;
  10354. this._doNotHandleContextLost = options.doNotHandleContextLost ? true : false;
  10355. // Exceptions
  10356. if (navigator && navigator.userAgent) {
  10357. var ua = navigator.userAgent;
  10358. for (var _i = 0, _a = Engine.ExceptionList; _i < _a.length; _i++) {
  10359. var exception = _a[_i];
  10360. var key = exception.key;
  10361. var targets = exception.targets;
  10362. if (ua.indexOf(key) > -1) {
  10363. if (exception.capture && exception.captureConstraint) {
  10364. var capture = exception.capture;
  10365. var constraint = exception.captureConstraint;
  10366. var regex = new RegExp(capture);
  10367. var matches = regex.exec(ua);
  10368. if (matches && matches.length > 0) {
  10369. var capturedValue = parseInt(matches[matches.length - 1]);
  10370. if (capturedValue >= constraint) {
  10371. continue;
  10372. }
  10373. }
  10374. }
  10375. for (var _b = 0, targets_1 = targets; _b < targets_1.length; _b++) {
  10376. var target = targets_1[_b];
  10377. switch (target) {
  10378. case "uniformBuffer":
  10379. this.disableUniformBuffers = true;
  10380. break;
  10381. case "textureBindingOptimization":
  10382. this.disableTextureBindingOptimization = true;
  10383. break;
  10384. }
  10385. }
  10386. break;
  10387. }
  10388. }
  10389. }
  10390. // GL
  10391. if (!options.disableWebGL2Support) {
  10392. try {
  10393. this._gl = (canvas.getContext("webgl2", options) || canvas.getContext("experimental-webgl2", options));
  10394. if (this._gl) {
  10395. this._webGLVersion = 2.0;
  10396. }
  10397. }
  10398. catch (e) {
  10399. // Do nothing
  10400. }
  10401. }
  10402. if (!this._gl) {
  10403. if (!canvas) {
  10404. throw new Error("The provided canvas is null or undefined.");
  10405. }
  10406. try {
  10407. this._gl = (canvas.getContext("webgl", options) || canvas.getContext("experimental-webgl", options));
  10408. }
  10409. catch (e) {
  10410. throw new Error("WebGL not supported");
  10411. }
  10412. }
  10413. if (!this._gl) {
  10414. throw new Error("WebGL not supported");
  10415. }
  10416. this._onCanvasFocus = function () {
  10417. _this.onCanvasFocusObservable.notifyObservers(_this);
  10418. };
  10419. this._onCanvasBlur = function () {
  10420. _this.onCanvasBlurObservable.notifyObservers(_this);
  10421. };
  10422. canvas.addEventListener("focus", this._onCanvasFocus);
  10423. canvas.addEventListener("blur", this._onCanvasBlur);
  10424. this._onBlur = function () {
  10425. if (_this.disablePerformanceMonitorInBackground) {
  10426. _this._performanceMonitor.disable();
  10427. }
  10428. _this._windowIsBackground = true;
  10429. };
  10430. this._onFocus = function () {
  10431. if (_this.disablePerformanceMonitorInBackground) {
  10432. _this._performanceMonitor.enable();
  10433. }
  10434. _this._windowIsBackground = false;
  10435. };
  10436. this._onCanvasPointerOut = function () {
  10437. _this.onCanvasPointerOutObservable.notifyObservers(_this);
  10438. };
  10439. window.addEventListener("blur", this._onBlur);
  10440. window.addEventListener("focus", this._onFocus);
  10441. canvas.addEventListener("pointerout", this._onCanvasPointerOut);
  10442. // Context lost
  10443. if (!this._doNotHandleContextLost) {
  10444. this._onContextLost = function (evt) {
  10445. evt.preventDefault();
  10446. _this._contextWasLost = true;
  10447. BABYLON.Tools.Warn("WebGL context lost.");
  10448. _this.onContextLostObservable.notifyObservers(_this);
  10449. };
  10450. this._onContextRestored = function (evt) {
  10451. // Adding a timeout to avoid race condition at browser level
  10452. setTimeout(function () {
  10453. // Rebuild gl context
  10454. _this._initGLContext();
  10455. // Rebuild effects
  10456. _this._rebuildEffects();
  10457. // Rebuild textures
  10458. _this._rebuildInternalTextures();
  10459. // Rebuild buffers
  10460. _this._rebuildBuffers();
  10461. // Cache
  10462. _this.wipeCaches(true);
  10463. BABYLON.Tools.Warn("WebGL context successfully restored.");
  10464. _this.onContextRestoredObservable.notifyObservers(_this);
  10465. _this._contextWasLost = false;
  10466. }, 0);
  10467. };
  10468. canvas.addEventListener("webglcontextlost", this._onContextLost, false);
  10469. canvas.addEventListener("webglcontextrestored", this._onContextRestored, false);
  10470. }
  10471. }
  10472. else {
  10473. this._gl = canvasOrContext;
  10474. this._renderingCanvas = this._gl.canvas;
  10475. if (this._gl.renderbufferStorageMultisample) {
  10476. this._webGLVersion = 2.0;
  10477. }
  10478. options.stencil = this._gl.getContextAttributes().stencil;
  10479. }
  10480. // Viewport
  10481. var limitDeviceRatio = options.limitDeviceRatio || window.devicePixelRatio || 1.0;
  10482. this._hardwareScalingLevel = adaptToDeviceRatio ? 1.0 / Math.min(limitDeviceRatio, window.devicePixelRatio || 1.0) : 1.0;
  10483. this.resize();
  10484. this._isStencilEnable = options.stencil ? true : false;
  10485. this._initGLContext();
  10486. if (canvas) {
  10487. // Fullscreen
  10488. this._onFullscreenChange = function () {
  10489. if (document.fullscreen !== undefined) {
  10490. _this.isFullscreen = document.fullscreen;
  10491. }
  10492. else if (document.mozFullScreen !== undefined) {
  10493. _this.isFullscreen = document.mozFullScreen;
  10494. }
  10495. else if (document.webkitIsFullScreen !== undefined) {
  10496. _this.isFullscreen = document.webkitIsFullScreen;
  10497. }
  10498. else if (document.msIsFullScreen !== undefined) {
  10499. _this.isFullscreen = document.msIsFullScreen;
  10500. }
  10501. // Pointer lock
  10502. if (_this.isFullscreen && _this._pointerLockRequested && canvas) {
  10503. canvas.requestPointerLock = canvas.requestPointerLock ||
  10504. canvas.msRequestPointerLock ||
  10505. canvas.mozRequestPointerLock ||
  10506. canvas.webkitRequestPointerLock;
  10507. if (canvas.requestPointerLock) {
  10508. canvas.requestPointerLock();
  10509. }
  10510. }
  10511. };
  10512. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  10513. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  10514. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  10515. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  10516. // Pointer lock
  10517. this._onPointerLockChange = function () {
  10518. _this.isPointerLock = (document.mozPointerLockElement === canvas ||
  10519. document.webkitPointerLockElement === canvas ||
  10520. document.msPointerLockElement === canvas ||
  10521. document.pointerLockElement === canvas);
  10522. };
  10523. document.addEventListener("pointerlockchange", this._onPointerLockChange, false);
  10524. document.addEventListener("mspointerlockchange", this._onPointerLockChange, false);
  10525. document.addEventListener("mozpointerlockchange", this._onPointerLockChange, false);
  10526. document.addEventListener("webkitpointerlockchange", this._onPointerLockChange, false);
  10527. this._onVRDisplayPointerRestricted = function () {
  10528. if (canvas) {
  10529. canvas.requestPointerLock();
  10530. }
  10531. };
  10532. this._onVRDisplayPointerUnrestricted = function () {
  10533. document.exitPointerLock();
  10534. };
  10535. window.addEventListener('vrdisplaypointerrestricted', this._onVRDisplayPointerRestricted, false);
  10536. window.addEventListener('vrdisplaypointerunrestricted', this._onVRDisplayPointerUnrestricted, false);
  10537. }
  10538. if (options.audioEngine && BABYLON.AudioEngine && !Engine.audioEngine) {
  10539. Engine.audioEngine = new BABYLON.AudioEngine();
  10540. }
  10541. // Prepare buffer pointers
  10542. for (var i = 0; i < this._caps.maxVertexAttribs; i++) {
  10543. this._currentBufferPointers[i] = new BufferPointer();
  10544. }
  10545. this._linkTrackers(this._firstBoundInternalTextureTracker, this._lastBoundInternalTextureTracker);
  10546. // Load WebVR Devices
  10547. if (options.autoEnableWebVR) {
  10548. this.initWebVR();
  10549. }
  10550. // Detect if we are running on a faulty buggy OS.
  10551. this._badOS = /iPad/i.test(navigator.userAgent) || /iPhone/i.test(navigator.userAgent);
  10552. // Detect if we are running on a faulty buggy desktop OS.
  10553. this._badDesktopOS = /^((?!chrome|android).)*safari/i.test(navigator.userAgent);
  10554. BABYLON.Tools.Log("Babylon.js engine (v" + Engine.Version + ") launched");
  10555. this.enableOfflineSupport = (BABYLON.Database !== undefined);
  10556. }
  10557. Object.defineProperty(Engine, "LastCreatedEngine", {
  10558. get: function () {
  10559. if (Engine.Instances.length === 0) {
  10560. return null;
  10561. }
  10562. return Engine.Instances[Engine.Instances.length - 1];
  10563. },
  10564. enumerable: true,
  10565. configurable: true
  10566. });
  10567. Object.defineProperty(Engine, "LastCreatedScene", {
  10568. get: function () {
  10569. var lastCreatedEngine = Engine.LastCreatedEngine;
  10570. if (!lastCreatedEngine) {
  10571. return null;
  10572. }
  10573. if (lastCreatedEngine.scenes.length === 0) {
  10574. return null;
  10575. }
  10576. return lastCreatedEngine.scenes[lastCreatedEngine.scenes.length - 1];
  10577. },
  10578. enumerable: true,
  10579. configurable: true
  10580. });
  10581. /**
  10582. * Will flag all materials in all scenes in all engines as dirty to trigger new shader compilation
  10583. */
  10584. Engine.MarkAllMaterialsAsDirty = function (flag, predicate) {
  10585. for (var engineIndex = 0; engineIndex < Engine.Instances.length; engineIndex++) {
  10586. var engine = Engine.Instances[engineIndex];
  10587. for (var sceneIndex = 0; sceneIndex < engine.scenes.length; sceneIndex++) {
  10588. engine.scenes[sceneIndex].markAllMaterialsAsDirty(flag, predicate);
  10589. }
  10590. }
  10591. };
  10592. Object.defineProperty(Engine, "NEVER", {
  10593. get: function () {
  10594. return Engine._NEVER;
  10595. },
  10596. enumerable: true,
  10597. configurable: true
  10598. });
  10599. Object.defineProperty(Engine, "ALWAYS", {
  10600. get: function () {
  10601. return Engine._ALWAYS;
  10602. },
  10603. enumerable: true,
  10604. configurable: true
  10605. });
  10606. Object.defineProperty(Engine, "LESS", {
  10607. get: function () {
  10608. return Engine._LESS;
  10609. },
  10610. enumerable: true,
  10611. configurable: true
  10612. });
  10613. Object.defineProperty(Engine, "EQUAL", {
  10614. get: function () {
  10615. return Engine._EQUAL;
  10616. },
  10617. enumerable: true,
  10618. configurable: true
  10619. });
  10620. Object.defineProperty(Engine, "LEQUAL", {
  10621. get: function () {
  10622. return Engine._LEQUAL;
  10623. },
  10624. enumerable: true,
  10625. configurable: true
  10626. });
  10627. Object.defineProperty(Engine, "GREATER", {
  10628. get: function () {
  10629. return Engine._GREATER;
  10630. },
  10631. enumerable: true,
  10632. configurable: true
  10633. });
  10634. Object.defineProperty(Engine, "GEQUAL", {
  10635. get: function () {
  10636. return Engine._GEQUAL;
  10637. },
  10638. enumerable: true,
  10639. configurable: true
  10640. });
  10641. Object.defineProperty(Engine, "NOTEQUAL", {
  10642. get: function () {
  10643. return Engine._NOTEQUAL;
  10644. },
  10645. enumerable: true,
  10646. configurable: true
  10647. });
  10648. Object.defineProperty(Engine, "KEEP", {
  10649. get: function () {
  10650. return Engine._KEEP;
  10651. },
  10652. enumerable: true,
  10653. configurable: true
  10654. });
  10655. Object.defineProperty(Engine, "REPLACE", {
  10656. get: function () {
  10657. return Engine._REPLACE;
  10658. },
  10659. enumerable: true,
  10660. configurable: true
  10661. });
  10662. Object.defineProperty(Engine, "INCR", {
  10663. get: function () {
  10664. return Engine._INCR;
  10665. },
  10666. enumerable: true,
  10667. configurable: true
  10668. });
  10669. Object.defineProperty(Engine, "DECR", {
  10670. get: function () {
  10671. return Engine._DECR;
  10672. },
  10673. enumerable: true,
  10674. configurable: true
  10675. });
  10676. Object.defineProperty(Engine, "INVERT", {
  10677. get: function () {
  10678. return Engine._INVERT;
  10679. },
  10680. enumerable: true,
  10681. configurable: true
  10682. });
  10683. Object.defineProperty(Engine, "INCR_WRAP", {
  10684. get: function () {
  10685. return Engine._INCR_WRAP;
  10686. },
  10687. enumerable: true,
  10688. configurable: true
  10689. });
  10690. Object.defineProperty(Engine, "DECR_WRAP", {
  10691. get: function () {
  10692. return Engine._DECR_WRAP;
  10693. },
  10694. enumerable: true,
  10695. configurable: true
  10696. });
  10697. Object.defineProperty(Engine, "ALPHA_DISABLE", {
  10698. get: function () {
  10699. return Engine._ALPHA_DISABLE;
  10700. },
  10701. enumerable: true,
  10702. configurable: true
  10703. });
  10704. Object.defineProperty(Engine, "ALPHA_ONEONE", {
  10705. get: function () {
  10706. return Engine._ALPHA_ONEONE;
  10707. },
  10708. enumerable: true,
  10709. configurable: true
  10710. });
  10711. Object.defineProperty(Engine, "ALPHA_ADD", {
  10712. get: function () {
  10713. return Engine._ALPHA_ADD;
  10714. },
  10715. enumerable: true,
  10716. configurable: true
  10717. });
  10718. Object.defineProperty(Engine, "ALPHA_COMBINE", {
  10719. get: function () {
  10720. return Engine._ALPHA_COMBINE;
  10721. },
  10722. enumerable: true,
  10723. configurable: true
  10724. });
  10725. Object.defineProperty(Engine, "ALPHA_SUBTRACT", {
  10726. get: function () {
  10727. return Engine._ALPHA_SUBTRACT;
  10728. },
  10729. enumerable: true,
  10730. configurable: true
  10731. });
  10732. Object.defineProperty(Engine, "ALPHA_MULTIPLY", {
  10733. get: function () {
  10734. return Engine._ALPHA_MULTIPLY;
  10735. },
  10736. enumerable: true,
  10737. configurable: true
  10738. });
  10739. Object.defineProperty(Engine, "ALPHA_MAXIMIZED", {
  10740. get: function () {
  10741. return Engine._ALPHA_MAXIMIZED;
  10742. },
  10743. enumerable: true,
  10744. configurable: true
  10745. });
  10746. Object.defineProperty(Engine, "ALPHA_PREMULTIPLIED", {
  10747. get: function () {
  10748. return Engine._ALPHA_PREMULTIPLIED;
  10749. },
  10750. enumerable: true,
  10751. configurable: true
  10752. });
  10753. Object.defineProperty(Engine, "ALPHA_PREMULTIPLIED_PORTERDUFF", {
  10754. get: function () {
  10755. return Engine._ALPHA_PREMULTIPLIED_PORTERDUFF;
  10756. },
  10757. enumerable: true,
  10758. configurable: true
  10759. });
  10760. Object.defineProperty(Engine, "ALPHA_INTERPOLATE", {
  10761. get: function () {
  10762. return Engine._ALPHA_INTERPOLATE;
  10763. },
  10764. enumerable: true,
  10765. configurable: true
  10766. });
  10767. Object.defineProperty(Engine, "ALPHA_SCREENMODE", {
  10768. get: function () {
  10769. return Engine._ALPHA_SCREENMODE;
  10770. },
  10771. enumerable: true,
  10772. configurable: true
  10773. });
  10774. Object.defineProperty(Engine, "DELAYLOADSTATE_NONE", {
  10775. get: function () {
  10776. return Engine._DELAYLOADSTATE_NONE;
  10777. },
  10778. enumerable: true,
  10779. configurable: true
  10780. });
  10781. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADED", {
  10782. get: function () {
  10783. return Engine._DELAYLOADSTATE_LOADED;
  10784. },
  10785. enumerable: true,
  10786. configurable: true
  10787. });
  10788. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADING", {
  10789. get: function () {
  10790. return Engine._DELAYLOADSTATE_LOADING;
  10791. },
  10792. enumerable: true,
  10793. configurable: true
  10794. });
  10795. Object.defineProperty(Engine, "DELAYLOADSTATE_NOTLOADED", {
  10796. get: function () {
  10797. return Engine._DELAYLOADSTATE_NOTLOADED;
  10798. },
  10799. enumerable: true,
  10800. configurable: true
  10801. });
  10802. Object.defineProperty(Engine, "TEXTUREFORMAT_ALPHA", {
  10803. get: function () {
  10804. return Engine._TEXTUREFORMAT_ALPHA;
  10805. },
  10806. enumerable: true,
  10807. configurable: true
  10808. });
  10809. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE", {
  10810. get: function () {
  10811. return Engine._TEXTUREFORMAT_LUMINANCE;
  10812. },
  10813. enumerable: true,
  10814. configurable: true
  10815. });
  10816. Object.defineProperty(Engine, "TEXTUREFORMAT_R32F", {
  10817. /**
  10818. * R32F
  10819. */
  10820. get: function () {
  10821. return Engine._TEXTUREFORMAT_R32F;
  10822. },
  10823. enumerable: true,
  10824. configurable: true
  10825. });
  10826. Object.defineProperty(Engine, "TEXTUREFORMAT_RG32F", {
  10827. /**
  10828. * RG32F
  10829. */
  10830. get: function () {
  10831. return Engine._TEXTUREFORMAT_RG32F;
  10832. },
  10833. enumerable: true,
  10834. configurable: true
  10835. });
  10836. Object.defineProperty(Engine, "TEXTUREFORMAT_RGB32F", {
  10837. /**
  10838. * RGB32F
  10839. */
  10840. get: function () {
  10841. return Engine._TEXTUREFORMAT_RGB32F;
  10842. },
  10843. enumerable: true,
  10844. configurable: true
  10845. });
  10846. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE_ALPHA", {
  10847. get: function () {
  10848. return Engine._TEXTUREFORMAT_LUMINANCE_ALPHA;
  10849. },
  10850. enumerable: true,
  10851. configurable: true
  10852. });
  10853. Object.defineProperty(Engine, "TEXTUREFORMAT_RGB", {
  10854. get: function () {
  10855. return Engine._TEXTUREFORMAT_RGB;
  10856. },
  10857. enumerable: true,
  10858. configurable: true
  10859. });
  10860. Object.defineProperty(Engine, "TEXTUREFORMAT_RGBA", {
  10861. get: function () {
  10862. return Engine._TEXTUREFORMAT_RGBA;
  10863. },
  10864. enumerable: true,
  10865. configurable: true
  10866. });
  10867. Object.defineProperty(Engine, "TEXTURETYPE_UNSIGNED_INT", {
  10868. get: function () {
  10869. return Engine._TEXTURETYPE_UNSIGNED_INT;
  10870. },
  10871. enumerable: true,
  10872. configurable: true
  10873. });
  10874. Object.defineProperty(Engine, "TEXTURETYPE_FLOAT", {
  10875. get: function () {
  10876. return Engine._TEXTURETYPE_FLOAT;
  10877. },
  10878. enumerable: true,
  10879. configurable: true
  10880. });
  10881. Object.defineProperty(Engine, "TEXTURETYPE_HALF_FLOAT", {
  10882. get: function () {
  10883. return Engine._TEXTURETYPE_HALF_FLOAT;
  10884. },
  10885. enumerable: true,
  10886. configurable: true
  10887. });
  10888. Object.defineProperty(Engine, "SCALEMODE_FLOOR", {
  10889. get: function () {
  10890. return Engine._SCALEMODE_FLOOR;
  10891. },
  10892. enumerable: true,
  10893. configurable: true
  10894. });
  10895. Object.defineProperty(Engine, "SCALEMODE_NEAREST", {
  10896. get: function () {
  10897. return Engine._SCALEMODE_NEAREST;
  10898. },
  10899. enumerable: true,
  10900. configurable: true
  10901. });
  10902. Object.defineProperty(Engine, "SCALEMODE_CEILING", {
  10903. get: function () {
  10904. return Engine._SCALEMODE_CEILING;
  10905. },
  10906. enumerable: true,
  10907. configurable: true
  10908. });
  10909. Object.defineProperty(Engine, "Version", {
  10910. get: function () {
  10911. return "3.2.0-alpha7";
  10912. },
  10913. enumerable: true,
  10914. configurable: true
  10915. });
  10916. Object.defineProperty(Engine.prototype, "isInVRExclusivePointerMode", {
  10917. get: function () {
  10918. return this._vrExclusivePointerMode;
  10919. },
  10920. enumerable: true,
  10921. configurable: true
  10922. });
  10923. Object.defineProperty(Engine.prototype, "supportsUniformBuffers", {
  10924. get: function () {
  10925. return this.webGLVersion > 1 && !this.disableUniformBuffers;
  10926. },
  10927. enumerable: true,
  10928. configurable: true
  10929. });
  10930. Object.defineProperty(Engine.prototype, "needPOTTextures", {
  10931. get: function () {
  10932. return this._webGLVersion < 2 || this.forcePOTTextures;
  10933. },
  10934. enumerable: true,
  10935. configurable: true
  10936. });
  10937. Object.defineProperty(Engine.prototype, "badOS", {
  10938. get: function () {
  10939. return this._badOS;
  10940. },
  10941. enumerable: true,
  10942. configurable: true
  10943. });
  10944. Object.defineProperty(Engine.prototype, "badDesktopOS", {
  10945. get: function () {
  10946. return this._badDesktopOS;
  10947. },
  10948. enumerable: true,
  10949. configurable: true
  10950. });
  10951. Object.defineProperty(Engine.prototype, "performanceMonitor", {
  10952. get: function () {
  10953. return this._performanceMonitor;
  10954. },
  10955. enumerable: true,
  10956. configurable: true
  10957. });
  10958. Object.defineProperty(Engine.prototype, "texturesSupported", {
  10959. get: function () {
  10960. return this._texturesSupported;
  10961. },
  10962. enumerable: true,
  10963. configurable: true
  10964. });
  10965. Object.defineProperty(Engine.prototype, "textureFormatInUse", {
  10966. get: function () {
  10967. return this._textureFormatInUse;
  10968. },
  10969. enumerable: true,
  10970. configurable: true
  10971. });
  10972. Object.defineProperty(Engine.prototype, "currentViewport", {
  10973. get: function () {
  10974. return this._cachedViewport;
  10975. },
  10976. enumerable: true,
  10977. configurable: true
  10978. });
  10979. Object.defineProperty(Engine.prototype, "emptyTexture", {
  10980. // Empty texture
  10981. get: function () {
  10982. if (!this._emptyTexture) {
  10983. this._emptyTexture = this.createRawTexture(new Uint8Array(4), 1, 1, Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  10984. }
  10985. return this._emptyTexture;
  10986. },
  10987. enumerable: true,
  10988. configurable: true
  10989. });
  10990. Object.defineProperty(Engine.prototype, "emptyTexture3D", {
  10991. get: function () {
  10992. if (!this._emptyTexture3D) {
  10993. this._emptyTexture3D = this.createRawTexture3D(new Uint8Array(4), 1, 1, 1, Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  10994. }
  10995. return this._emptyTexture3D;
  10996. },
  10997. enumerable: true,
  10998. configurable: true
  10999. });
  11000. Object.defineProperty(Engine.prototype, "emptyCubeTexture", {
  11001. get: function () {
  11002. if (!this._emptyCubeTexture) {
  11003. var faceData = new Uint8Array(4);
  11004. var cubeData = [faceData, faceData, faceData, faceData, faceData, faceData];
  11005. this._emptyCubeTexture = this.createRawCubeTexture(cubeData, 1, Engine.TEXTUREFORMAT_RGBA, Engine.TEXTURETYPE_UNSIGNED_INT, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  11006. }
  11007. return this._emptyCubeTexture;
  11008. },
  11009. enumerable: true,
  11010. configurable: true
  11011. });
  11012. Engine.prototype._rebuildInternalTextures = function () {
  11013. var currentState = this._internalTexturesCache.slice(); // Do a copy because the rebuild will add proxies
  11014. for (var _i = 0, currentState_1 = currentState; _i < currentState_1.length; _i++) {
  11015. var internalTexture = currentState_1[_i];
  11016. internalTexture._rebuild();
  11017. }
  11018. };
  11019. Engine.prototype._rebuildEffects = function () {
  11020. for (var key in this._compiledEffects) {
  11021. var effect = this._compiledEffects[key];
  11022. effect._prepareEffect();
  11023. }
  11024. BABYLON.Effect.ResetCache();
  11025. };
  11026. Engine.prototype._rebuildBuffers = function () {
  11027. // Index / Vertex
  11028. for (var _i = 0, _a = this.scenes; _i < _a.length; _i++) {
  11029. var scene = _a[_i];
  11030. scene.resetCachedMaterial();
  11031. scene._rebuildGeometries();
  11032. scene._rebuildTextures();
  11033. }
  11034. // Uniforms
  11035. for (var _b = 0, _c = this._uniformBuffers; _b < _c.length; _b++) {
  11036. var uniformBuffer = _c[_b];
  11037. uniformBuffer._rebuild();
  11038. }
  11039. };
  11040. Engine.prototype._initGLContext = function () {
  11041. // Caps
  11042. this._caps = new EngineCapabilities();
  11043. this._caps.maxTexturesImageUnits = this._gl.getParameter(this._gl.MAX_TEXTURE_IMAGE_UNITS);
  11044. this._caps.maxCombinedTexturesImageUnits = this._gl.getParameter(this._gl.MAX_COMBINED_TEXTURE_IMAGE_UNITS);
  11045. this._caps.maxVertexTextureImageUnits = this._gl.getParameter(this._gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS);
  11046. this._caps.maxTextureSize = this._gl.getParameter(this._gl.MAX_TEXTURE_SIZE);
  11047. this._caps.maxCubemapTextureSize = this._gl.getParameter(this._gl.MAX_CUBE_MAP_TEXTURE_SIZE);
  11048. this._caps.maxRenderTextureSize = this._gl.getParameter(this._gl.MAX_RENDERBUFFER_SIZE);
  11049. this._caps.maxVertexAttribs = this._gl.getParameter(this._gl.MAX_VERTEX_ATTRIBS);
  11050. this._caps.maxVaryingVectors = this._gl.getParameter(this._gl.MAX_VARYING_VECTORS);
  11051. this._caps.maxFragmentUniformVectors = this._gl.getParameter(this._gl.MAX_FRAGMENT_UNIFORM_VECTORS);
  11052. this._caps.maxVertexUniformVectors = this._gl.getParameter(this._gl.MAX_VERTEX_UNIFORM_VECTORS);
  11053. // Infos
  11054. this._glVersion = this._gl.getParameter(this._gl.VERSION);
  11055. var rendererInfo = this._gl.getExtension("WEBGL_debug_renderer_info");
  11056. if (rendererInfo != null) {
  11057. this._glRenderer = this._gl.getParameter(rendererInfo.UNMASKED_RENDERER_WEBGL);
  11058. this._glVendor = this._gl.getParameter(rendererInfo.UNMASKED_VENDOR_WEBGL);
  11059. }
  11060. if (!this._glVendor) {
  11061. this._glVendor = "Unknown vendor";
  11062. }
  11063. if (!this._glRenderer) {
  11064. this._glRenderer = "Unknown renderer";
  11065. }
  11066. // Constants
  11067. this._gl.HALF_FLOAT_OES = 0x8D61; // Half floating-point type (16-bit).
  11068. if (this._gl.RGBA16F !== 0x881A) {
  11069. this._gl.RGBA16F = 0x881A; // RGBA 16-bit floating-point color-renderable internal sized format.
  11070. }
  11071. if (this._gl.RGBA32F !== 0x8814) {
  11072. this._gl.RGBA32F = 0x8814; // RGBA 32-bit floating-point color-renderable internal sized format.
  11073. }
  11074. if (this._gl.DEPTH24_STENCIL8 !== 35056) {
  11075. this._gl.DEPTH24_STENCIL8 = 35056;
  11076. }
  11077. // Extensions
  11078. this._caps.standardDerivatives = this._webGLVersion > 1 || (this._gl.getExtension('OES_standard_derivatives') !== null);
  11079. this._caps.astc = this._gl.getExtension('WEBGL_compressed_texture_astc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_astc');
  11080. this._caps.s3tc = this._gl.getExtension('WEBGL_compressed_texture_s3tc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_s3tc');
  11081. this._caps.pvrtc = this._gl.getExtension('WEBGL_compressed_texture_pvrtc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_pvrtc');
  11082. this._caps.etc1 = this._gl.getExtension('WEBGL_compressed_texture_etc1') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_etc1');
  11083. this._caps.etc2 = this._gl.getExtension('WEBGL_compressed_texture_etc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_etc') ||
  11084. this._gl.getExtension('WEBGL_compressed_texture_es3_0'); // also a requirement of OpenGL ES 3
  11085. this._caps.textureAnisotropicFilterExtension = this._gl.getExtension('EXT_texture_filter_anisotropic') || this._gl.getExtension('WEBKIT_EXT_texture_filter_anisotropic') || this._gl.getExtension('MOZ_EXT_texture_filter_anisotropic');
  11086. this._caps.maxAnisotropy = this._caps.textureAnisotropicFilterExtension ? this._gl.getParameter(this._caps.textureAnisotropicFilterExtension.MAX_TEXTURE_MAX_ANISOTROPY_EXT) : 0;
  11087. this._caps.uintIndices = this._webGLVersion > 1 || this._gl.getExtension('OES_element_index_uint') !== null;
  11088. this._caps.fragmentDepthSupported = this._webGLVersion > 1 || this._gl.getExtension('EXT_frag_depth') !== null;
  11089. this._caps.highPrecisionShaderSupported = true;
  11090. this._caps.timerQuery = this._gl.getExtension('EXT_disjoint_timer_query_webgl2') || this._gl.getExtension("EXT_disjoint_timer_query");
  11091. if (this._caps.timerQuery) {
  11092. if (this._webGLVersion === 1) {
  11093. this._gl.getQuery = this._caps.timerQuery.getQueryEXT.bind(this._caps.timerQuery);
  11094. }
  11095. this._caps.canUseTimestampForTimerQuery = this._gl.getQuery(this._caps.timerQuery.TIMESTAMP_EXT, this._caps.timerQuery.QUERY_COUNTER_BITS_EXT) > 0;
  11096. }
  11097. // Checks if some of the format renders first to allow the use of webgl inspector.
  11098. this._caps.colorBufferFloat = this._webGLVersion > 1 && this._gl.getExtension('EXT_color_buffer_float');
  11099. this._caps.textureFloat = this._webGLVersion > 1 || this._gl.getExtension('OES_texture_float');
  11100. this._caps.textureFloatLinearFiltering = this._caps.textureFloat && this._gl.getExtension('OES_texture_float_linear');
  11101. this._caps.textureFloatRender = this._caps.textureFloat && this._canRenderToFloatFramebuffer();
  11102. this._caps.textureHalfFloat = this._webGLVersion > 1 || this._gl.getExtension('OES_texture_half_float');
  11103. this._caps.textureHalfFloatLinearFiltering = this._webGLVersion > 1 || (this._caps.textureHalfFloat && this._gl.getExtension('OES_texture_half_float_linear'));
  11104. if (this._webGLVersion > 1) {
  11105. this._gl.HALF_FLOAT_OES = 0x140B;
  11106. }
  11107. this._caps.textureHalfFloatRender = this._caps.textureHalfFloat && this._canRenderToHalfFloatFramebuffer();
  11108. this._caps.textureLOD = this._webGLVersion > 1 || this._gl.getExtension('EXT_shader_texture_lod');
  11109. // Draw buffers
  11110. if (this._webGLVersion > 1) {
  11111. this._caps.drawBuffersExtension = true;
  11112. }
  11113. else {
  11114. var drawBuffersExtension = this._gl.getExtension('WEBGL_draw_buffers');
  11115. if (drawBuffersExtension !== null) {
  11116. this._caps.drawBuffersExtension = true;
  11117. this._gl.drawBuffers = drawBuffersExtension.drawBuffersWEBGL.bind(drawBuffersExtension);
  11118. this._gl.DRAW_FRAMEBUFFER = this._gl.FRAMEBUFFER;
  11119. for (var i = 0; i < 16; i++) {
  11120. this._gl["COLOR_ATTACHMENT" + i + "_WEBGL"] = drawBuffersExtension["COLOR_ATTACHMENT" + i + "_WEBGL"];
  11121. }
  11122. }
  11123. else {
  11124. this._caps.drawBuffersExtension = false;
  11125. }
  11126. }
  11127. // Depth Texture
  11128. if (this._webGLVersion > 1) {
  11129. this._caps.depthTextureExtension = true;
  11130. }
  11131. else {
  11132. var depthTextureExtension = this._gl.getExtension('WEBGL_depth_texture');
  11133. if (depthTextureExtension != null) {
  11134. this._caps.depthTextureExtension = true;
  11135. }
  11136. }
  11137. // Vertex array object
  11138. if (this._webGLVersion > 1) {
  11139. this._caps.vertexArrayObject = true;
  11140. }
  11141. else {
  11142. var vertexArrayObjectExtension = this._gl.getExtension('OES_vertex_array_object');
  11143. if (vertexArrayObjectExtension != null) {
  11144. this._caps.vertexArrayObject = true;
  11145. this._gl.createVertexArray = vertexArrayObjectExtension.createVertexArrayOES.bind(vertexArrayObjectExtension);
  11146. this._gl.bindVertexArray = vertexArrayObjectExtension.bindVertexArrayOES.bind(vertexArrayObjectExtension);
  11147. this._gl.deleteVertexArray = vertexArrayObjectExtension.deleteVertexArrayOES.bind(vertexArrayObjectExtension);
  11148. }
  11149. else {
  11150. this._caps.vertexArrayObject = false;
  11151. }
  11152. }
  11153. // Instances count
  11154. if (this._webGLVersion > 1) {
  11155. this._caps.instancedArrays = true;
  11156. }
  11157. else {
  11158. var instanceExtension = this._gl.getExtension('ANGLE_instanced_arrays');
  11159. if (instanceExtension != null) {
  11160. this._caps.instancedArrays = true;
  11161. this._gl.drawArraysInstanced = instanceExtension.drawArraysInstancedANGLE.bind(instanceExtension);
  11162. this._gl.drawElementsInstanced = instanceExtension.drawElementsInstancedANGLE.bind(instanceExtension);
  11163. this._gl.vertexAttribDivisor = instanceExtension.vertexAttribDivisorANGLE.bind(instanceExtension);
  11164. }
  11165. else {
  11166. this._caps.instancedArrays = false;
  11167. }
  11168. }
  11169. // Intelligently add supported compressed formats in order to check for.
  11170. // Check for ASTC support first as it is most powerful and to be very cross platform.
  11171. // Next PVRTC & DXT, which are probably superior to ETC1/2.
  11172. // Likely no hardware which supports both PVR & DXT, so order matters little.
  11173. // ETC2 is newer and handles ETC1 (no alpha capability), so check for first.
  11174. if (this._caps.astc)
  11175. this.texturesSupported.push('-astc.ktx');
  11176. if (this._caps.s3tc)
  11177. this.texturesSupported.push('-dxt.ktx');
  11178. if (this._caps.pvrtc)
  11179. this.texturesSupported.push('-pvrtc.ktx');
  11180. if (this._caps.etc2)
  11181. this.texturesSupported.push('-etc2.ktx');
  11182. if (this._caps.etc1)
  11183. this.texturesSupported.push('-etc1.ktx');
  11184. if (this._gl.getShaderPrecisionFormat) {
  11185. var highp = this._gl.getShaderPrecisionFormat(this._gl.FRAGMENT_SHADER, this._gl.HIGH_FLOAT);
  11186. if (highp) {
  11187. this._caps.highPrecisionShaderSupported = highp.precision !== 0;
  11188. }
  11189. }
  11190. // Depth buffer
  11191. this.setDepthBuffer(true);
  11192. this.setDepthFunctionToLessOrEqual();
  11193. this.setDepthWrite(true);
  11194. // Texture maps
  11195. this._maxSimultaneousTextures = this._caps.maxCombinedTexturesImageUnits;
  11196. for (var slot = 0; slot < this._maxSimultaneousTextures; slot++) {
  11197. this._nextFreeTextureSlots.push(slot);
  11198. }
  11199. };
  11200. Object.defineProperty(Engine.prototype, "webGLVersion", {
  11201. get: function () {
  11202. return this._webGLVersion;
  11203. },
  11204. enumerable: true,
  11205. configurable: true
  11206. });
  11207. Object.defineProperty(Engine.prototype, "isStencilEnable", {
  11208. /**
  11209. * Returns true if the stencil buffer has been enabled through the creation option of the context.
  11210. */
  11211. get: function () {
  11212. return this._isStencilEnable;
  11213. },
  11214. enumerable: true,
  11215. configurable: true
  11216. });
  11217. Engine.prototype._prepareWorkingCanvas = function () {
  11218. if (this._workingCanvas) {
  11219. return;
  11220. }
  11221. this._workingCanvas = document.createElement("canvas");
  11222. var context = this._workingCanvas.getContext("2d");
  11223. if (context) {
  11224. this._workingContext = context;
  11225. }
  11226. };
  11227. Engine.prototype.resetTextureCache = function () {
  11228. for (var key in this._boundTexturesCache) {
  11229. var boundTexture = this._boundTexturesCache[key];
  11230. if (boundTexture) {
  11231. this._removeDesignatedSlot(boundTexture);
  11232. }
  11233. this._boundTexturesCache[key] = null;
  11234. }
  11235. if (!this.disableTextureBindingOptimization) {
  11236. this._nextFreeTextureSlots = [];
  11237. for (var slot = 0; slot < this._maxSimultaneousTextures; slot++) {
  11238. this._nextFreeTextureSlots.push(slot);
  11239. }
  11240. }
  11241. this._currentTextureChannel = -1;
  11242. };
  11243. Engine.prototype.isDeterministicLockStep = function () {
  11244. return this._deterministicLockstep;
  11245. };
  11246. Engine.prototype.getLockstepMaxSteps = function () {
  11247. return this._lockstepMaxSteps;
  11248. };
  11249. Engine.prototype.getGlInfo = function () {
  11250. return {
  11251. vendor: this._glVendor,
  11252. renderer: this._glRenderer,
  11253. version: this._glVersion
  11254. };
  11255. };
  11256. Engine.prototype.getAspectRatio = function (camera, useScreen) {
  11257. if (useScreen === void 0) { useScreen = false; }
  11258. var viewport = camera.viewport;
  11259. return (this.getRenderWidth(useScreen) * viewport.width) / (this.getRenderHeight(useScreen) * viewport.height);
  11260. };
  11261. Engine.prototype.getRenderWidth = function (useScreen) {
  11262. if (useScreen === void 0) { useScreen = false; }
  11263. if (!useScreen && this._currentRenderTarget) {
  11264. return this._currentRenderTarget.width;
  11265. }
  11266. return this._gl.drawingBufferWidth;
  11267. };
  11268. Engine.prototype.getRenderHeight = function (useScreen) {
  11269. if (useScreen === void 0) { useScreen = false; }
  11270. if (!useScreen && this._currentRenderTarget) {
  11271. return this._currentRenderTarget.height;
  11272. }
  11273. return this._gl.drawingBufferHeight;
  11274. };
  11275. Engine.prototype.getRenderingCanvas = function () {
  11276. return this._renderingCanvas;
  11277. };
  11278. Engine.prototype.getRenderingCanvasClientRect = function () {
  11279. if (!this._renderingCanvas) {
  11280. return null;
  11281. }
  11282. return this._renderingCanvas.getBoundingClientRect();
  11283. };
  11284. Engine.prototype.setHardwareScalingLevel = function (level) {
  11285. this._hardwareScalingLevel = level;
  11286. this.resize();
  11287. };
  11288. Engine.prototype.getHardwareScalingLevel = function () {
  11289. return this._hardwareScalingLevel;
  11290. };
  11291. Engine.prototype.getLoadedTexturesCache = function () {
  11292. return this._internalTexturesCache;
  11293. };
  11294. Engine.prototype.getCaps = function () {
  11295. return this._caps;
  11296. };
  11297. Object.defineProperty(Engine.prototype, "drawCalls", {
  11298. /** The number of draw calls submitted last frame */
  11299. get: function () {
  11300. BABYLON.Tools.Warn("drawCalls is deprecated. Please use SceneInstrumentation class");
  11301. return 0;
  11302. },
  11303. enumerable: true,
  11304. configurable: true
  11305. });
  11306. Object.defineProperty(Engine.prototype, "drawCallsPerfCounter", {
  11307. get: function () {
  11308. BABYLON.Tools.Warn("drawCallsPerfCounter is deprecated. Please use SceneInstrumentation class");
  11309. return null;
  11310. },
  11311. enumerable: true,
  11312. configurable: true
  11313. });
  11314. Engine.prototype.getDepthFunction = function () {
  11315. return this._depthCullingState.depthFunc;
  11316. };
  11317. Engine.prototype.setDepthFunction = function (depthFunc) {
  11318. this._depthCullingState.depthFunc = depthFunc;
  11319. };
  11320. Engine.prototype.setDepthFunctionToGreater = function () {
  11321. this._depthCullingState.depthFunc = this._gl.GREATER;
  11322. };
  11323. Engine.prototype.setDepthFunctionToGreaterOrEqual = function () {
  11324. this._depthCullingState.depthFunc = this._gl.GEQUAL;
  11325. };
  11326. Engine.prototype.setDepthFunctionToLess = function () {
  11327. this._depthCullingState.depthFunc = this._gl.LESS;
  11328. };
  11329. Engine.prototype.setDepthFunctionToLessOrEqual = function () {
  11330. this._depthCullingState.depthFunc = this._gl.LEQUAL;
  11331. };
  11332. Engine.prototype.getStencilBuffer = function () {
  11333. return this._stencilState.stencilTest;
  11334. };
  11335. Engine.prototype.setStencilBuffer = function (enable) {
  11336. this._stencilState.stencilTest = enable;
  11337. };
  11338. Engine.prototype.getStencilMask = function () {
  11339. return this._stencilState.stencilMask;
  11340. };
  11341. Engine.prototype.setStencilMask = function (mask) {
  11342. this._stencilState.stencilMask = mask;
  11343. };
  11344. Engine.prototype.getStencilFunction = function () {
  11345. return this._stencilState.stencilFunc;
  11346. };
  11347. Engine.prototype.getStencilFunctionReference = function () {
  11348. return this._stencilState.stencilFuncRef;
  11349. };
  11350. Engine.prototype.getStencilFunctionMask = function () {
  11351. return this._stencilState.stencilFuncMask;
  11352. };
  11353. Engine.prototype.setStencilFunction = function (stencilFunc) {
  11354. this._stencilState.stencilFunc = stencilFunc;
  11355. };
  11356. Engine.prototype.setStencilFunctionReference = function (reference) {
  11357. this._stencilState.stencilFuncRef = reference;
  11358. };
  11359. Engine.prototype.setStencilFunctionMask = function (mask) {
  11360. this._stencilState.stencilFuncMask = mask;
  11361. };
  11362. Engine.prototype.getStencilOperationFail = function () {
  11363. return this._stencilState.stencilOpStencilFail;
  11364. };
  11365. Engine.prototype.getStencilOperationDepthFail = function () {
  11366. return this._stencilState.stencilOpDepthFail;
  11367. };
  11368. Engine.prototype.getStencilOperationPass = function () {
  11369. return this._stencilState.stencilOpStencilDepthPass;
  11370. };
  11371. Engine.prototype.setStencilOperationFail = function (operation) {
  11372. this._stencilState.stencilOpStencilFail = operation;
  11373. };
  11374. Engine.prototype.setStencilOperationDepthFail = function (operation) {
  11375. this._stencilState.stencilOpDepthFail = operation;
  11376. };
  11377. Engine.prototype.setStencilOperationPass = function (operation) {
  11378. this._stencilState.stencilOpStencilDepthPass = operation;
  11379. };
  11380. Engine.prototype.setDitheringState = function (value) {
  11381. if (value) {
  11382. this._gl.enable(this._gl.DITHER);
  11383. }
  11384. else {
  11385. this._gl.disable(this._gl.DITHER);
  11386. }
  11387. };
  11388. Engine.prototype.setRasterizerState = function (value) {
  11389. if (value) {
  11390. this._gl.disable(this._gl.RASTERIZER_DISCARD);
  11391. }
  11392. else {
  11393. this._gl.enable(this._gl.RASTERIZER_DISCARD);
  11394. }
  11395. };
  11396. /**
  11397. * stop executing a render loop function and remove it from the execution array
  11398. * @param {Function} [renderFunction] the function to be removed. If not provided all functions will be removed.
  11399. */
  11400. Engine.prototype.stopRenderLoop = function (renderFunction) {
  11401. if (!renderFunction) {
  11402. this._activeRenderLoops = [];
  11403. return;
  11404. }
  11405. var index = this._activeRenderLoops.indexOf(renderFunction);
  11406. if (index >= 0) {
  11407. this._activeRenderLoops.splice(index, 1);
  11408. }
  11409. };
  11410. Engine.prototype._renderLoop = function () {
  11411. if (!this._contextWasLost) {
  11412. var shouldRender = true;
  11413. if (!this.renderEvenInBackground && this._windowIsBackground) {
  11414. shouldRender = false;
  11415. }
  11416. if (shouldRender) {
  11417. // Start new frame
  11418. this.beginFrame();
  11419. for (var index = 0; index < this._activeRenderLoops.length; index++) {
  11420. var renderFunction = this._activeRenderLoops[index];
  11421. renderFunction();
  11422. }
  11423. // Present
  11424. this.endFrame();
  11425. }
  11426. }
  11427. if (this._activeRenderLoops.length > 0) {
  11428. // Register new frame
  11429. var requester = null;
  11430. if (this._vrDisplay && this._vrDisplay.isPresenting)
  11431. requester = this._vrDisplay;
  11432. this._frameHandler = BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction, requester);
  11433. }
  11434. else {
  11435. this._renderingQueueLaunched = false;
  11436. }
  11437. };
  11438. /**
  11439. * Register and execute a render loop. The engine can have more than one render function.
  11440. * @param {Function} renderFunction - the function to continuously execute starting the next render loop.
  11441. * @example
  11442. * engine.runRenderLoop(function () {
  11443. * scene.render()
  11444. * })
  11445. */
  11446. Engine.prototype.runRenderLoop = function (renderFunction) {
  11447. if (this._activeRenderLoops.indexOf(renderFunction) !== -1) {
  11448. return;
  11449. }
  11450. this._activeRenderLoops.push(renderFunction);
  11451. if (!this._renderingQueueLaunched) {
  11452. this._renderingQueueLaunched = true;
  11453. this._bindedRenderFunction = this._renderLoop.bind(this);
  11454. this._frameHandler = BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction);
  11455. }
  11456. };
  11457. /**
  11458. * Toggle full screen mode.
  11459. * @param {boolean} requestPointerLock - should a pointer lock be requested from the user
  11460. * @param {any} options - an options object to be sent to the requestFullscreen function
  11461. */
  11462. Engine.prototype.switchFullscreen = function (requestPointerLock) {
  11463. if (this.isFullscreen) {
  11464. BABYLON.Tools.ExitFullscreen();
  11465. }
  11466. else {
  11467. this._pointerLockRequested = requestPointerLock;
  11468. if (this._renderingCanvas) {
  11469. BABYLON.Tools.RequestFullscreen(this._renderingCanvas);
  11470. }
  11471. }
  11472. };
  11473. Engine.prototype.clear = function (color, backBuffer, depth, stencil) {
  11474. if (stencil === void 0) { stencil = false; }
  11475. this.applyStates();
  11476. var mode = 0;
  11477. if (backBuffer && color) {
  11478. this._gl.clearColor(color.r, color.g, color.b, color.a !== undefined ? color.a : 1.0);
  11479. mode |= this._gl.COLOR_BUFFER_BIT;
  11480. }
  11481. if (depth) {
  11482. this._gl.clearDepth(1.0);
  11483. mode |= this._gl.DEPTH_BUFFER_BIT;
  11484. }
  11485. if (stencil) {
  11486. this._gl.clearStencil(0);
  11487. mode |= this._gl.STENCIL_BUFFER_BIT;
  11488. }
  11489. this._gl.clear(mode);
  11490. };
  11491. Engine.prototype.scissorClear = function (x, y, width, height, clearColor) {
  11492. var gl = this._gl;
  11493. // Save state
  11494. var curScissor = gl.getParameter(gl.SCISSOR_TEST);
  11495. var curScissorBox = gl.getParameter(gl.SCISSOR_BOX);
  11496. // Change state
  11497. gl.enable(gl.SCISSOR_TEST);
  11498. gl.scissor(x, y, width, height);
  11499. // Clear
  11500. this.clear(clearColor, true, true, true);
  11501. // Restore state
  11502. gl.scissor(curScissorBox[0], curScissorBox[1], curScissorBox[2], curScissorBox[3]);
  11503. if (curScissor === true) {
  11504. gl.enable(gl.SCISSOR_TEST);
  11505. }
  11506. else {
  11507. gl.disable(gl.SCISSOR_TEST);
  11508. }
  11509. };
  11510. /**
  11511. * Set the WebGL's viewport
  11512. * @param {BABYLON.Viewport} viewport - the viewport element to be used.
  11513. * @param {number} [requiredWidth] - the width required for rendering. If not provided the rendering canvas' width is used.
  11514. * @param {number} [requiredHeight] - the height required for rendering. If not provided the rendering canvas' height is used.
  11515. */
  11516. Engine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {
  11517. var width = requiredWidth || this.getRenderWidth();
  11518. var height = requiredHeight || this.getRenderHeight();
  11519. var x = viewport.x || 0;
  11520. var y = viewport.y || 0;
  11521. this._cachedViewport = viewport;
  11522. this._gl.viewport(x * width, y * height, width * viewport.width, height * viewport.height);
  11523. };
  11524. /**
  11525. * Directly set the WebGL Viewport
  11526. * The x, y, width & height are directly passed to the WebGL call
  11527. * @return the current viewport Object (if any) that is being replaced by this call. You can restore this viewport later on to go back to the original state.
  11528. */
  11529. Engine.prototype.setDirectViewport = function (x, y, width, height) {
  11530. var currentViewport = this._cachedViewport;
  11531. this._cachedViewport = null;
  11532. this._gl.viewport(x, y, width, height);
  11533. return currentViewport;
  11534. };
  11535. Engine.prototype.beginFrame = function () {
  11536. this.onBeginFrameObservable.notifyObservers(this);
  11537. this._measureFps();
  11538. };
  11539. Engine.prototype.endFrame = function () {
  11540. //force a flush in case we are using a bad OS.
  11541. if (this._badOS) {
  11542. this.flushFramebuffer();
  11543. }
  11544. //submit frame to the vr device, if enabled
  11545. if (this._vrDisplay && this._vrDisplay.isPresenting) {
  11546. // TODO: We should only submit the frame if we read frameData successfully.
  11547. this._vrDisplay.submitFrame();
  11548. }
  11549. this.onEndFrameObservable.notifyObservers(this);
  11550. };
  11551. /**
  11552. * resize the view according to the canvas' size.
  11553. * @example
  11554. * window.addEventListener("resize", function () {
  11555. * engine.resize();
  11556. * });
  11557. */
  11558. Engine.prototype.resize = function () {
  11559. // We're not resizing the size of the canvas while in VR mode & presenting
  11560. if (!(this._vrDisplay && this._vrDisplay.isPresenting)) {
  11561. var width = this._renderingCanvas ? this._renderingCanvas.clientWidth : window.innerWidth;
  11562. var height = this._renderingCanvas ? this._renderingCanvas.clientHeight : window.innerHeight;
  11563. this.setSize(width / this._hardwareScalingLevel, height / this._hardwareScalingLevel);
  11564. }
  11565. };
  11566. /**
  11567. * force a specific size of the canvas
  11568. * @param {number} width - the new canvas' width
  11569. * @param {number} height - the new canvas' height
  11570. */
  11571. Engine.prototype.setSize = function (width, height) {
  11572. if (!this._renderingCanvas) {
  11573. return;
  11574. }
  11575. if (this._renderingCanvas.width === width && this._renderingCanvas.height === height) {
  11576. return;
  11577. }
  11578. this._renderingCanvas.width = width;
  11579. this._renderingCanvas.height = height;
  11580. for (var index = 0; index < this.scenes.length; index++) {
  11581. var scene = this.scenes[index];
  11582. for (var camIndex = 0; camIndex < scene.cameras.length; camIndex++) {
  11583. var cam = scene.cameras[camIndex];
  11584. cam._currentRenderId = 0;
  11585. }
  11586. }
  11587. if (this.onResizeObservable.hasObservers) {
  11588. this.onResizeObservable.notifyObservers(this);
  11589. }
  11590. };
  11591. // WebVR functions
  11592. Engine.prototype.isVRDevicePresent = function () {
  11593. return !!this._vrDisplay;
  11594. };
  11595. Engine.prototype.getVRDevice = function () {
  11596. return this._vrDisplay;
  11597. };
  11598. /**
  11599. * Initializes a webVR display and starts listening to display change events.
  11600. * The onVRDisplayChangedObservable will be notified upon these changes.
  11601. * @returns The onVRDisplayChangedObservable.
  11602. */
  11603. Engine.prototype.initWebVR = function () {
  11604. this.initWebVRAsync();
  11605. return this.onVRDisplayChangedObservable;
  11606. };
  11607. /**
  11608. * Initializes a webVR display and starts listening to display change events.
  11609. * The onVRDisplayChangedObservable will be notified upon these changes.
  11610. * @returns A promise containing a VRDisplay and if vr is supported.
  11611. */
  11612. Engine.prototype.initWebVRAsync = function () {
  11613. var _this = this;
  11614. var notifyObservers = function () {
  11615. var eventArgs = {
  11616. vrDisplay: _this._vrDisplay,
  11617. vrSupported: _this._vrSupported
  11618. };
  11619. _this.onVRDisplayChangedObservable.notifyObservers(eventArgs);
  11620. _this._webVRInitPromise = new Promise(function (res) { res(eventArgs); });
  11621. };
  11622. if (!this._onVrDisplayConnect) {
  11623. this._onVrDisplayConnect = function (event) {
  11624. _this._vrDisplay = event.display;
  11625. notifyObservers();
  11626. };
  11627. this._onVrDisplayDisconnect = function () {
  11628. _this._vrDisplay.cancelAnimationFrame(_this._frameHandler);
  11629. _this._vrDisplay = undefined;
  11630. _this._frameHandler = BABYLON.Tools.QueueNewFrame(_this._bindedRenderFunction);
  11631. notifyObservers();
  11632. };
  11633. this._onVrDisplayPresentChange = function () {
  11634. _this._vrExclusivePointerMode = _this._vrDisplay && _this._vrDisplay.isPresenting;
  11635. };
  11636. window.addEventListener('vrdisplayconnect', this._onVrDisplayConnect);
  11637. window.addEventListener('vrdisplaydisconnect', this._onVrDisplayDisconnect);
  11638. window.addEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  11639. }
  11640. this._webVRInitPromise = this._webVRInitPromise || this._getVRDisplaysAsync();
  11641. this._webVRInitPromise.then(notifyObservers);
  11642. return this._webVRInitPromise;
  11643. };
  11644. Engine.prototype.enableVR = function () {
  11645. var _this = this;
  11646. if (this._vrDisplay && !this._vrDisplay.isPresenting) {
  11647. var onResolved = function () {
  11648. _this.onVRRequestPresentComplete.notifyObservers(true);
  11649. _this._onVRFullScreenTriggered();
  11650. };
  11651. var onRejected = function () {
  11652. _this.onVRRequestPresentComplete.notifyObservers(false);
  11653. };
  11654. this.onVRRequestPresentStart.notifyObservers(this);
  11655. this._vrDisplay.requestPresent([{ source: this.getRenderingCanvas() }]).then(onResolved).catch(onRejected);
  11656. }
  11657. };
  11658. Engine.prototype.disableVR = function () {
  11659. if (this._vrDisplay && this._vrDisplay.isPresenting) {
  11660. this._vrDisplay.exitPresent().then(this._onVRFullScreenTriggered).catch(this._onVRFullScreenTriggered);
  11661. }
  11662. };
  11663. Engine.prototype._getVRDisplaysAsync = function () {
  11664. var _this = this;
  11665. return new Promise(function (res, rej) {
  11666. if (navigator.getVRDisplays) {
  11667. navigator.getVRDisplays().then(function (devices) {
  11668. _this._vrSupported = true;
  11669. // note that devices may actually be an empty array. This is fine;
  11670. // we expect this._vrDisplay to be undefined in this case.
  11671. _this._vrDisplay = devices[0];
  11672. res({
  11673. vrDisplay: _this._vrDisplay,
  11674. vrSupported: _this._vrSupported
  11675. });
  11676. });
  11677. }
  11678. else {
  11679. _this._vrDisplay = undefined;
  11680. _this._vrSupported = false;
  11681. res({
  11682. vrDisplay: _this._vrDisplay,
  11683. vrSupported: _this._vrSupported
  11684. });
  11685. }
  11686. });
  11687. };
  11688. Engine.prototype.bindFramebuffer = function (texture, faceIndex, requiredWidth, requiredHeight, forceFullscreenViewport) {
  11689. if (this._currentRenderTarget) {
  11690. this.unBindFramebuffer(this._currentRenderTarget);
  11691. }
  11692. this._currentRenderTarget = texture;
  11693. this.bindUnboundFramebuffer(texture._MSAAFramebuffer ? texture._MSAAFramebuffer : texture._framebuffer);
  11694. var gl = this._gl;
  11695. if (texture.isCube) {
  11696. if (faceIndex === undefined) {
  11697. faceIndex = 0;
  11698. }
  11699. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture._webGLTexture, 0);
  11700. }
  11701. if (this._cachedViewport && !forceFullscreenViewport) {
  11702. this.setViewport(this._cachedViewport, requiredWidth, requiredHeight);
  11703. }
  11704. else {
  11705. gl.viewport(0, 0, requiredWidth || texture.width, requiredHeight || texture.height);
  11706. }
  11707. this.wipeCaches();
  11708. };
  11709. Engine.prototype.bindUnboundFramebuffer = function (framebuffer) {
  11710. if (this._currentFramebuffer !== framebuffer) {
  11711. this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, framebuffer);
  11712. this._currentFramebuffer = framebuffer;
  11713. }
  11714. };
  11715. Engine.prototype.unBindFramebuffer = function (texture, disableGenerateMipMaps, onBeforeUnbind) {
  11716. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  11717. this._currentRenderTarget = null;
  11718. // If MSAA, we need to bitblt back to main texture
  11719. var gl = this._gl;
  11720. if (texture._MSAAFramebuffer) {
  11721. gl.bindFramebuffer(gl.READ_FRAMEBUFFER, texture._MSAAFramebuffer);
  11722. gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, texture._framebuffer);
  11723. gl.blitFramebuffer(0, 0, texture.width, texture.height, 0, 0, texture.width, texture.height, gl.COLOR_BUFFER_BIT, gl.NEAREST);
  11724. }
  11725. if (texture.generateMipMaps && !disableGenerateMipMaps && !texture.isCube) {
  11726. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  11727. gl.generateMipmap(gl.TEXTURE_2D);
  11728. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  11729. }
  11730. if (onBeforeUnbind) {
  11731. if (texture._MSAAFramebuffer) {
  11732. // Bind the correct framebuffer
  11733. this.bindUnboundFramebuffer(texture._framebuffer);
  11734. }
  11735. onBeforeUnbind();
  11736. }
  11737. this.bindUnboundFramebuffer(null);
  11738. };
  11739. Engine.prototype.unBindMultiColorAttachmentFramebuffer = function (textures, disableGenerateMipMaps, onBeforeUnbind) {
  11740. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  11741. this._currentRenderTarget = null;
  11742. // If MSAA, we need to bitblt back to main texture
  11743. var gl = this._gl;
  11744. if (textures[0]._MSAAFramebuffer) {
  11745. gl.bindFramebuffer(gl.READ_FRAMEBUFFER, textures[0]._MSAAFramebuffer);
  11746. gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, textures[0]._framebuffer);
  11747. var attachments = textures[0]._attachments;
  11748. if (!attachments) {
  11749. attachments = new Array(textures.length);
  11750. textures[0]._attachments = attachments;
  11751. }
  11752. for (var i = 0; i < textures.length; i++) {
  11753. var texture = textures[i];
  11754. for (var j = 0; j < attachments.length; j++) {
  11755. attachments[j] = gl.NONE;
  11756. }
  11757. attachments[i] = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  11758. gl.readBuffer(attachments[i]);
  11759. gl.drawBuffers(attachments);
  11760. gl.blitFramebuffer(0, 0, texture.width, texture.height, 0, 0, texture.width, texture.height, gl.COLOR_BUFFER_BIT, gl.NEAREST);
  11761. }
  11762. for (var i = 0; i < attachments.length; i++) {
  11763. attachments[i] = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  11764. }
  11765. gl.drawBuffers(attachments);
  11766. }
  11767. for (var i = 0; i < textures.length; i++) {
  11768. var texture = textures[i];
  11769. if (texture.generateMipMaps && !disableGenerateMipMaps && !texture.isCube) {
  11770. this._bindTextureDirectly(gl.TEXTURE_2D, texture);
  11771. gl.generateMipmap(gl.TEXTURE_2D);
  11772. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  11773. }
  11774. }
  11775. if (onBeforeUnbind) {
  11776. if (textures[0]._MSAAFramebuffer) {
  11777. // Bind the correct framebuffer
  11778. this.bindUnboundFramebuffer(textures[0]._framebuffer);
  11779. }
  11780. onBeforeUnbind();
  11781. }
  11782. this.bindUnboundFramebuffer(null);
  11783. };
  11784. Engine.prototype.generateMipMapsForCubemap = function (texture) {
  11785. if (texture.generateMipMaps) {
  11786. var gl = this._gl;
  11787. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  11788. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  11789. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  11790. }
  11791. };
  11792. Engine.prototype.flushFramebuffer = function () {
  11793. this._gl.flush();
  11794. };
  11795. Engine.prototype.restoreDefaultFramebuffer = function () {
  11796. if (this._currentRenderTarget) {
  11797. this.unBindFramebuffer(this._currentRenderTarget);
  11798. }
  11799. else {
  11800. this.bindUnboundFramebuffer(null);
  11801. }
  11802. if (this._cachedViewport) {
  11803. this.setViewport(this._cachedViewport);
  11804. }
  11805. this.wipeCaches();
  11806. };
  11807. // UBOs
  11808. Engine.prototype.createUniformBuffer = function (elements) {
  11809. var ubo = this._gl.createBuffer();
  11810. if (!ubo) {
  11811. throw new Error("Unable to create uniform buffer");
  11812. }
  11813. this.bindUniformBuffer(ubo);
  11814. if (elements instanceof Float32Array) {
  11815. this._gl.bufferData(this._gl.UNIFORM_BUFFER, elements, this._gl.STATIC_DRAW);
  11816. }
  11817. else {
  11818. this._gl.bufferData(this._gl.UNIFORM_BUFFER, new Float32Array(elements), this._gl.STATIC_DRAW);
  11819. }
  11820. this.bindUniformBuffer(null);
  11821. ubo.references = 1;
  11822. return ubo;
  11823. };
  11824. Engine.prototype.createDynamicUniformBuffer = function (elements) {
  11825. var ubo = this._gl.createBuffer();
  11826. if (!ubo) {
  11827. throw new Error("Unable to create dynamic uniform buffer");
  11828. }
  11829. this.bindUniformBuffer(ubo);
  11830. if (elements instanceof Float32Array) {
  11831. this._gl.bufferData(this._gl.UNIFORM_BUFFER, elements, this._gl.DYNAMIC_DRAW);
  11832. }
  11833. else {
  11834. this._gl.bufferData(this._gl.UNIFORM_BUFFER, new Float32Array(elements), this._gl.DYNAMIC_DRAW);
  11835. }
  11836. this.bindUniformBuffer(null);
  11837. ubo.references = 1;
  11838. return ubo;
  11839. };
  11840. Engine.prototype.updateUniformBuffer = function (uniformBuffer, elements, offset, count) {
  11841. this.bindUniformBuffer(uniformBuffer);
  11842. if (offset === undefined) {
  11843. offset = 0;
  11844. }
  11845. if (count === undefined) {
  11846. if (elements instanceof Float32Array) {
  11847. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, offset, elements);
  11848. }
  11849. else {
  11850. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, offset, new Float32Array(elements));
  11851. }
  11852. }
  11853. else {
  11854. if (elements instanceof Float32Array) {
  11855. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, 0, elements.subarray(offset, offset + count));
  11856. }
  11857. else {
  11858. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, 0, new Float32Array(elements).subarray(offset, offset + count));
  11859. }
  11860. }
  11861. this.bindUniformBuffer(null);
  11862. };
  11863. // VBOs
  11864. Engine.prototype._resetVertexBufferBinding = function () {
  11865. this.bindArrayBuffer(null);
  11866. this._cachedVertexBuffers = null;
  11867. };
  11868. Engine.prototype.createVertexBuffer = function (vertices) {
  11869. var vbo = this._gl.createBuffer();
  11870. if (!vbo) {
  11871. throw new Error("Unable to create vertex buffer");
  11872. }
  11873. this.bindArrayBuffer(vbo);
  11874. if (vertices instanceof Float32Array) {
  11875. this._gl.bufferData(this._gl.ARRAY_BUFFER, vertices, this._gl.STATIC_DRAW);
  11876. }
  11877. else {
  11878. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(vertices), this._gl.STATIC_DRAW);
  11879. }
  11880. this._resetVertexBufferBinding();
  11881. vbo.references = 1;
  11882. return vbo;
  11883. };
  11884. Engine.prototype.createDynamicVertexBuffer = function (vertices) {
  11885. var vbo = this._gl.createBuffer();
  11886. if (!vbo) {
  11887. throw new Error("Unable to create dynamic vertex buffer");
  11888. }
  11889. this.bindArrayBuffer(vbo);
  11890. if (vertices instanceof Float32Array) {
  11891. this._gl.bufferData(this._gl.ARRAY_BUFFER, vertices, this._gl.DYNAMIC_DRAW);
  11892. }
  11893. else {
  11894. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(vertices), this._gl.DYNAMIC_DRAW);
  11895. }
  11896. this._resetVertexBufferBinding();
  11897. vbo.references = 1;
  11898. return vbo;
  11899. };
  11900. Engine.prototype.updateDynamicIndexBuffer = function (indexBuffer, indices, offset) {
  11901. if (offset === void 0) { offset = 0; }
  11902. // Force cache update
  11903. this._currentBoundBuffer[this._gl.ELEMENT_ARRAY_BUFFER] = null;
  11904. this.bindIndexBuffer(indexBuffer);
  11905. var arrayBuffer;
  11906. if (indices instanceof Uint16Array || indices instanceof Uint32Array) {
  11907. arrayBuffer = indices;
  11908. }
  11909. else {
  11910. arrayBuffer = indexBuffer.is32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  11911. }
  11912. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, this._gl.DYNAMIC_DRAW);
  11913. this._resetIndexBufferBinding();
  11914. };
  11915. Engine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, vertices, offset, count) {
  11916. this.bindArrayBuffer(vertexBuffer);
  11917. if (offset === undefined) {
  11918. offset = 0;
  11919. }
  11920. if (count === undefined) {
  11921. if (vertices instanceof Float32Array) {
  11922. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, vertices);
  11923. }
  11924. else {
  11925. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, new Float32Array(vertices));
  11926. }
  11927. }
  11928. else {
  11929. if (vertices instanceof Float32Array) {
  11930. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, vertices.subarray(offset, offset + count));
  11931. }
  11932. else {
  11933. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, new Float32Array(vertices).subarray(offset, offset + count));
  11934. }
  11935. }
  11936. this._resetVertexBufferBinding();
  11937. };
  11938. Engine.prototype._resetIndexBufferBinding = function () {
  11939. this.bindIndexBuffer(null);
  11940. this._cachedIndexBuffer = null;
  11941. };
  11942. Engine.prototype.createIndexBuffer = function (indices, updatable) {
  11943. var vbo = this._gl.createBuffer();
  11944. if (!vbo) {
  11945. throw new Error("Unable to create index buffer");
  11946. }
  11947. this.bindIndexBuffer(vbo);
  11948. // Check for 32 bits indices
  11949. var arrayBuffer;
  11950. var need32Bits = false;
  11951. if (indices instanceof Uint16Array) {
  11952. arrayBuffer = indices;
  11953. }
  11954. else {
  11955. //check 32 bit support
  11956. if (this._caps.uintIndices) {
  11957. if (indices instanceof Uint32Array) {
  11958. arrayBuffer = indices;
  11959. need32Bits = true;
  11960. }
  11961. else {
  11962. //number[] or Int32Array, check if 32 bit is necessary
  11963. for (var index = 0; index < indices.length; index++) {
  11964. if (indices[index] > 65535) {
  11965. need32Bits = true;
  11966. break;
  11967. }
  11968. }
  11969. arrayBuffer = need32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  11970. }
  11971. }
  11972. else {
  11973. //no 32 bit support, force conversion to 16 bit (values greater 16 bit are lost)
  11974. arrayBuffer = new Uint16Array(indices);
  11975. }
  11976. }
  11977. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, updatable ? this._gl.DYNAMIC_DRAW : this._gl.STATIC_DRAW);
  11978. this._resetIndexBufferBinding();
  11979. vbo.references = 1;
  11980. vbo.is32Bits = need32Bits;
  11981. return vbo;
  11982. };
  11983. Engine.prototype.bindArrayBuffer = function (buffer) {
  11984. if (!this._vaoRecordInProgress) {
  11985. this._unbindVertexArrayObject();
  11986. }
  11987. this.bindBuffer(buffer, this._gl.ARRAY_BUFFER);
  11988. };
  11989. Engine.prototype.bindUniformBuffer = function (buffer) {
  11990. this._gl.bindBuffer(this._gl.UNIFORM_BUFFER, buffer);
  11991. };
  11992. Engine.prototype.bindUniformBufferBase = function (buffer, location) {
  11993. this._gl.bindBufferBase(this._gl.UNIFORM_BUFFER, location, buffer);
  11994. };
  11995. Engine.prototype.bindUniformBlock = function (shaderProgram, blockName, index) {
  11996. var uniformLocation = this._gl.getUniformBlockIndex(shaderProgram, blockName);
  11997. this._gl.uniformBlockBinding(shaderProgram, uniformLocation, index);
  11998. };
  11999. ;
  12000. Engine.prototype.bindIndexBuffer = function (buffer) {
  12001. if (!this._vaoRecordInProgress) {
  12002. this._unbindVertexArrayObject();
  12003. }
  12004. this.bindBuffer(buffer, this._gl.ELEMENT_ARRAY_BUFFER);
  12005. };
  12006. Engine.prototype.bindBuffer = function (buffer, target) {
  12007. if (this._vaoRecordInProgress || this._currentBoundBuffer[target] !== buffer) {
  12008. this._gl.bindBuffer(target, buffer);
  12009. this._currentBoundBuffer[target] = buffer;
  12010. }
  12011. };
  12012. Engine.prototype.updateArrayBuffer = function (data) {
  12013. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  12014. };
  12015. Engine.prototype.vertexAttribPointer = function (buffer, indx, size, type, normalized, stride, offset) {
  12016. var pointer = this._currentBufferPointers[indx];
  12017. var changed = false;
  12018. if (!pointer.active) {
  12019. changed = true;
  12020. pointer.active = true;
  12021. pointer.index = indx;
  12022. pointer.size = size;
  12023. pointer.type = type;
  12024. pointer.normalized = normalized;
  12025. pointer.stride = stride;
  12026. pointer.offset = offset;
  12027. pointer.buffer = buffer;
  12028. }
  12029. else {
  12030. if (pointer.buffer !== buffer) {
  12031. pointer.buffer = buffer;
  12032. changed = true;
  12033. }
  12034. if (pointer.size !== size) {
  12035. pointer.size = size;
  12036. changed = true;
  12037. }
  12038. if (pointer.type !== type) {
  12039. pointer.type = type;
  12040. changed = true;
  12041. }
  12042. if (pointer.normalized !== normalized) {
  12043. pointer.normalized = normalized;
  12044. changed = true;
  12045. }
  12046. if (pointer.stride !== stride) {
  12047. pointer.stride = stride;
  12048. changed = true;
  12049. }
  12050. if (pointer.offset !== offset) {
  12051. pointer.offset = offset;
  12052. changed = true;
  12053. }
  12054. }
  12055. if (changed || this._vaoRecordInProgress) {
  12056. this.bindArrayBuffer(buffer);
  12057. this._gl.vertexAttribPointer(indx, size, type, normalized, stride, offset);
  12058. }
  12059. };
  12060. Engine.prototype._bindIndexBufferWithCache = function (indexBuffer) {
  12061. if (indexBuffer == null) {
  12062. return;
  12063. }
  12064. if (this._cachedIndexBuffer !== indexBuffer) {
  12065. this._cachedIndexBuffer = indexBuffer;
  12066. this.bindIndexBuffer(indexBuffer);
  12067. this._uintIndicesCurrentlySet = indexBuffer.is32Bits;
  12068. }
  12069. };
  12070. Engine.prototype._bindVertexBuffersAttributes = function (vertexBuffers, effect) {
  12071. var attributes = effect.getAttributesNames();
  12072. if (!this._vaoRecordInProgress) {
  12073. this._unbindVertexArrayObject();
  12074. }
  12075. this.unbindAllAttributes();
  12076. for (var index = 0; index < attributes.length; index++) {
  12077. var order = effect.getAttributeLocation(index);
  12078. if (order >= 0) {
  12079. var vertexBuffer = vertexBuffers[attributes[index]];
  12080. if (!vertexBuffer) {
  12081. continue;
  12082. }
  12083. this._gl.enableVertexAttribArray(order);
  12084. if (!this._vaoRecordInProgress) {
  12085. this._vertexAttribArraysEnabled[order] = true;
  12086. }
  12087. var buffer = vertexBuffer.getBuffer();
  12088. if (buffer) {
  12089. this.vertexAttribPointer(buffer, order, vertexBuffer.getSize(), this._gl.FLOAT, false, vertexBuffer.getStrideSize() * 4, vertexBuffer.getOffset() * 4);
  12090. if (vertexBuffer.getIsInstanced()) {
  12091. this._gl.vertexAttribDivisor(order, vertexBuffer.getInstanceDivisor());
  12092. if (!this._vaoRecordInProgress) {
  12093. this._currentInstanceLocations.push(order);
  12094. this._currentInstanceBuffers.push(buffer);
  12095. }
  12096. }
  12097. }
  12098. }
  12099. }
  12100. };
  12101. Engine.prototype.recordVertexArrayObject = function (vertexBuffers, indexBuffer, effect) {
  12102. var vao = this._gl.createVertexArray();
  12103. this._vaoRecordInProgress = true;
  12104. this._gl.bindVertexArray(vao);
  12105. this._mustWipeVertexAttributes = true;
  12106. this._bindVertexBuffersAttributes(vertexBuffers, effect);
  12107. this.bindIndexBuffer(indexBuffer);
  12108. this._vaoRecordInProgress = false;
  12109. this._gl.bindVertexArray(null);
  12110. return vao;
  12111. };
  12112. Engine.prototype.bindVertexArrayObject = function (vertexArrayObject, indexBuffer) {
  12113. if (this._cachedVertexArrayObject !== vertexArrayObject) {
  12114. this._cachedVertexArrayObject = vertexArrayObject;
  12115. this._gl.bindVertexArray(vertexArrayObject);
  12116. this._cachedVertexBuffers = null;
  12117. this._cachedIndexBuffer = null;
  12118. this._uintIndicesCurrentlySet = indexBuffer != null && indexBuffer.is32Bits;
  12119. this._mustWipeVertexAttributes = true;
  12120. }
  12121. };
  12122. Engine.prototype.bindBuffersDirectly = function (vertexBuffer, indexBuffer, vertexDeclaration, vertexStrideSize, effect) {
  12123. if (this._cachedVertexBuffers !== vertexBuffer || this._cachedEffectForVertexBuffers !== effect) {
  12124. this._cachedVertexBuffers = vertexBuffer;
  12125. this._cachedEffectForVertexBuffers = effect;
  12126. var attributesCount = effect.getAttributesCount();
  12127. this._unbindVertexArrayObject();
  12128. this.unbindAllAttributes();
  12129. var offset = 0;
  12130. for (var index = 0; index < attributesCount; index++) {
  12131. if (index < vertexDeclaration.length) {
  12132. var order = effect.getAttributeLocation(index);
  12133. if (order >= 0) {
  12134. this._gl.enableVertexAttribArray(order);
  12135. this._vertexAttribArraysEnabled[order] = true;
  12136. this.vertexAttribPointer(vertexBuffer, order, vertexDeclaration[index], this._gl.FLOAT, false, vertexStrideSize, offset);
  12137. }
  12138. offset += vertexDeclaration[index] * 4;
  12139. }
  12140. }
  12141. }
  12142. this._bindIndexBufferWithCache(indexBuffer);
  12143. };
  12144. Engine.prototype._unbindVertexArrayObject = function () {
  12145. if (!this._cachedVertexArrayObject) {
  12146. return;
  12147. }
  12148. this._cachedVertexArrayObject = null;
  12149. this._gl.bindVertexArray(null);
  12150. };
  12151. Engine.prototype.bindBuffers = function (vertexBuffers, indexBuffer, effect) {
  12152. if (this._cachedVertexBuffers !== vertexBuffers || this._cachedEffectForVertexBuffers !== effect) {
  12153. this._cachedVertexBuffers = vertexBuffers;
  12154. this._cachedEffectForVertexBuffers = effect;
  12155. this._bindVertexBuffersAttributes(vertexBuffers, effect);
  12156. }
  12157. this._bindIndexBufferWithCache(indexBuffer);
  12158. };
  12159. Engine.prototype.unbindInstanceAttributes = function () {
  12160. var boundBuffer;
  12161. for (var i = 0, ul = this._currentInstanceLocations.length; i < ul; i++) {
  12162. var instancesBuffer = this._currentInstanceBuffers[i];
  12163. if (boundBuffer != instancesBuffer && instancesBuffer.references) {
  12164. boundBuffer = instancesBuffer;
  12165. this.bindArrayBuffer(instancesBuffer);
  12166. }
  12167. var offsetLocation = this._currentInstanceLocations[i];
  12168. this._gl.vertexAttribDivisor(offsetLocation, 0);
  12169. }
  12170. this._currentInstanceBuffers.length = 0;
  12171. this._currentInstanceLocations.length = 0;
  12172. };
  12173. Engine.prototype.releaseVertexArrayObject = function (vao) {
  12174. this._gl.deleteVertexArray(vao);
  12175. };
  12176. Engine.prototype._releaseBuffer = function (buffer) {
  12177. buffer.references--;
  12178. if (buffer.references === 0) {
  12179. this._gl.deleteBuffer(buffer);
  12180. return true;
  12181. }
  12182. return false;
  12183. };
  12184. Engine.prototype.createInstancesBuffer = function (capacity) {
  12185. var buffer = this._gl.createBuffer();
  12186. if (!buffer) {
  12187. throw new Error("Unable to create instance buffer");
  12188. }
  12189. buffer.capacity = capacity;
  12190. this.bindArrayBuffer(buffer);
  12191. this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
  12192. return buffer;
  12193. };
  12194. Engine.prototype.deleteInstancesBuffer = function (buffer) {
  12195. this._gl.deleteBuffer(buffer);
  12196. };
  12197. Engine.prototype.updateAndBindInstancesBuffer = function (instancesBuffer, data, offsetLocations) {
  12198. this.bindArrayBuffer(instancesBuffer);
  12199. if (data) {
  12200. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  12201. }
  12202. if (offsetLocations[0].index !== undefined) {
  12203. var stride = 0;
  12204. for (var i = 0; i < offsetLocations.length; i++) {
  12205. var ai = offsetLocations[i];
  12206. stride += ai.attributeSize * 4;
  12207. }
  12208. for (var i = 0; i < offsetLocations.length; i++) {
  12209. var ai = offsetLocations[i];
  12210. if (!this._vertexAttribArraysEnabled[ai.index]) {
  12211. this._gl.enableVertexAttribArray(ai.index);
  12212. this._vertexAttribArraysEnabled[ai.index] = true;
  12213. }
  12214. this.vertexAttribPointer(instancesBuffer, ai.index, ai.attributeSize, ai.attribyteType || this._gl.FLOAT, ai.normalized || false, stride, ai.offset);
  12215. this._gl.vertexAttribDivisor(ai.index, 1);
  12216. this._currentInstanceLocations.push(ai.index);
  12217. this._currentInstanceBuffers.push(instancesBuffer);
  12218. }
  12219. }
  12220. else {
  12221. for (var index = 0; index < 4; index++) {
  12222. var offsetLocation = offsetLocations[index];
  12223. if (!this._vertexAttribArraysEnabled[offsetLocation]) {
  12224. this._gl.enableVertexAttribArray(offsetLocation);
  12225. this._vertexAttribArraysEnabled[offsetLocation] = true;
  12226. }
  12227. this.vertexAttribPointer(instancesBuffer, offsetLocation, 4, this._gl.FLOAT, false, 64, index * 16);
  12228. this._gl.vertexAttribDivisor(offsetLocation, 1);
  12229. this._currentInstanceLocations.push(offsetLocation);
  12230. this._currentInstanceBuffers.push(instancesBuffer);
  12231. }
  12232. }
  12233. };
  12234. Engine.prototype.applyStates = function () {
  12235. this._depthCullingState.apply(this._gl);
  12236. this._stencilState.apply(this._gl);
  12237. this._alphaState.apply(this._gl);
  12238. };
  12239. Engine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {
  12240. this.drawElementsType(useTriangles ? BABYLON.Material.TriangleFillMode : BABYLON.Material.WireFrameFillMode, indexStart, indexCount, instancesCount);
  12241. };
  12242. Engine.prototype.drawPointClouds = function (verticesStart, verticesCount, instancesCount) {
  12243. this.drawArraysType(BABYLON.Material.PointFillMode, verticesStart, verticesCount, instancesCount);
  12244. };
  12245. Engine.prototype.drawUnIndexed = function (useTriangles, verticesStart, verticesCount, instancesCount) {
  12246. this.drawArraysType(useTriangles ? BABYLON.Material.TriangleFillMode : BABYLON.Material.WireFrameFillMode, verticesStart, verticesCount, instancesCount);
  12247. };
  12248. Engine.prototype.drawElementsType = function (fillMode, indexStart, indexCount, instancesCount) {
  12249. // Apply states
  12250. this.applyStates();
  12251. this._drawCalls.addCount(1, false);
  12252. // Render
  12253. var drawMode = this.DrawMode(fillMode);
  12254. var indexFormat = this._uintIndicesCurrentlySet ? this._gl.UNSIGNED_INT : this._gl.UNSIGNED_SHORT;
  12255. var mult = this._uintIndicesCurrentlySet ? 4 : 2;
  12256. if (instancesCount) {
  12257. this._gl.drawElementsInstanced(drawMode, indexCount, indexFormat, indexStart * mult, instancesCount);
  12258. }
  12259. else {
  12260. this._gl.drawElements(drawMode, indexCount, indexFormat, indexStart * mult);
  12261. }
  12262. };
  12263. Engine.prototype.drawArraysType = function (fillMode, verticesStart, verticesCount, instancesCount) {
  12264. // Apply states
  12265. this.applyStates();
  12266. this._drawCalls.addCount(1, false);
  12267. var drawMode = this.DrawMode(fillMode);
  12268. if (instancesCount) {
  12269. this._gl.drawArraysInstanced(drawMode, verticesStart, verticesCount, instancesCount);
  12270. }
  12271. else {
  12272. this._gl.drawArrays(drawMode, verticesStart, verticesCount);
  12273. }
  12274. };
  12275. Engine.prototype.DrawMode = function (fillMode) {
  12276. switch (fillMode) {
  12277. // Triangle views
  12278. case BABYLON.Material.TriangleFillMode:
  12279. return this._gl.TRIANGLES;
  12280. case BABYLON.Material.PointFillMode:
  12281. return this._gl.POINTS;
  12282. case BABYLON.Material.WireFrameFillMode:
  12283. return this._gl.LINES;
  12284. // Draw modes
  12285. case BABYLON.Material.PointListDrawMode:
  12286. return this._gl.POINTS;
  12287. case BABYLON.Material.LineListDrawMode:
  12288. return this._gl.LINES;
  12289. case BABYLON.Material.LineLoopDrawMode:
  12290. return this._gl.LINE_LOOP;
  12291. case BABYLON.Material.LineStripDrawMode:
  12292. return this._gl.LINE_STRIP;
  12293. case BABYLON.Material.TriangleStripDrawMode:
  12294. return this._gl.TRIANGLE_STRIP;
  12295. case BABYLON.Material.TriangleFanDrawMode:
  12296. return this._gl.TRIANGLE_FAN;
  12297. default:
  12298. return this._gl.TRIANGLES;
  12299. }
  12300. };
  12301. // Shaders
  12302. Engine.prototype._releaseEffect = function (effect) {
  12303. if (this._compiledEffects[effect._key]) {
  12304. delete this._compiledEffects[effect._key];
  12305. this._deleteProgram(effect.getProgram());
  12306. }
  12307. };
  12308. Engine.prototype._deleteProgram = function (program) {
  12309. if (program) {
  12310. program.__SPECTOR_rebuildProgram = null;
  12311. if (program.transformFeedback) {
  12312. this.deleteTransformFeedback(program.transformFeedback);
  12313. program.transformFeedback = null;
  12314. }
  12315. this._gl.deleteProgram(program);
  12316. }
  12317. };
  12318. /**
  12319. * @param baseName The base name of the effect (The name of file without .fragment.fx or .vertex.fx)
  12320. * @param samplers An array of string used to represent textures
  12321. */
  12322. Engine.prototype.createEffect = function (baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, defines, fallbacks, onCompiled, onError, indexParameters) {
  12323. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  12324. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  12325. var name = vertex + "+" + fragment + "@" + (defines ? defines : attributesNamesOrOptions.defines);
  12326. if (this._compiledEffects[name]) {
  12327. var compiledEffect = this._compiledEffects[name];
  12328. if (onCompiled && compiledEffect.isReady()) {
  12329. onCompiled(compiledEffect);
  12330. }
  12331. return compiledEffect;
  12332. }
  12333. var effect = new BABYLON.Effect(baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, this, defines, fallbacks, onCompiled, onError, indexParameters);
  12334. effect._key = name;
  12335. this._compiledEffects[name] = effect;
  12336. return effect;
  12337. };
  12338. Engine.prototype.createEffectForParticles = function (fragmentName, uniformsNames, samplers, defines, fallbacks, onCompiled, onError) {
  12339. if (uniformsNames === void 0) { uniformsNames = []; }
  12340. if (samplers === void 0) { samplers = []; }
  12341. if (defines === void 0) { defines = ""; }
  12342. return this.createEffect({
  12343. vertex: "particles",
  12344. fragmentElement: fragmentName
  12345. }, ["position", "color", "options"], ["view", "projection"].concat(uniformsNames), ["diffuseSampler"].concat(samplers), defines, fallbacks, onCompiled, onError);
  12346. };
  12347. Engine.prototype.createRawShaderProgram = function (vertexCode, fragmentCode, context, transformFeedbackVaryings) {
  12348. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  12349. context = context || this._gl;
  12350. var vertexShader = compileRawShader(context, vertexCode, "vertex");
  12351. var fragmentShader = compileRawShader(context, fragmentCode, "fragment");
  12352. return this._createShaderProgram(vertexShader, fragmentShader, context, transformFeedbackVaryings);
  12353. };
  12354. Engine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines, context, transformFeedbackVaryings) {
  12355. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  12356. context = context || this._gl;
  12357. this.onBeforeShaderCompilationObservable.notifyObservers(this);
  12358. var shaderVersion = (this._webGLVersion > 1) ? "#version 300 es\n" : "";
  12359. var vertexShader = compileShader(context, vertexCode, "vertex", defines, shaderVersion);
  12360. var fragmentShader = compileShader(context, fragmentCode, "fragment", defines, shaderVersion);
  12361. var program = this._createShaderProgram(vertexShader, fragmentShader, context, transformFeedbackVaryings);
  12362. this.onAfterShaderCompilationObservable.notifyObservers(this);
  12363. return program;
  12364. };
  12365. Engine.prototype._createShaderProgram = function (vertexShader, fragmentShader, context, transformFeedbackVaryings) {
  12366. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  12367. var shaderProgram = context.createProgram();
  12368. if (!shaderProgram) {
  12369. throw new Error("Unable to create program");
  12370. }
  12371. context.attachShader(shaderProgram, vertexShader);
  12372. context.attachShader(shaderProgram, fragmentShader);
  12373. if (this.webGLVersion > 1 && transformFeedbackVaryings) {
  12374. var transformFeedback = this.createTransformFeedback();
  12375. this.bindTransformFeedback(transformFeedback);
  12376. this.setTranformFeedbackVaryings(shaderProgram, transformFeedbackVaryings);
  12377. shaderProgram.transformFeedback = transformFeedback;
  12378. }
  12379. context.linkProgram(shaderProgram);
  12380. if (this.webGLVersion > 1 && transformFeedbackVaryings) {
  12381. this.bindTransformFeedback(null);
  12382. }
  12383. var linked = context.getProgramParameter(shaderProgram, context.LINK_STATUS);
  12384. if (!linked) {
  12385. context.validateProgram(shaderProgram);
  12386. var error = context.getProgramInfoLog(shaderProgram);
  12387. if (error) {
  12388. throw new Error(error);
  12389. }
  12390. }
  12391. context.deleteShader(vertexShader);
  12392. context.deleteShader(fragmentShader);
  12393. return shaderProgram;
  12394. };
  12395. Engine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
  12396. var results = new Array();
  12397. for (var index = 0; index < uniformsNames.length; index++) {
  12398. results.push(this._gl.getUniformLocation(shaderProgram, uniformsNames[index]));
  12399. }
  12400. return results;
  12401. };
  12402. Engine.prototype.getAttributes = function (shaderProgram, attributesNames) {
  12403. var results = [];
  12404. for (var index = 0; index < attributesNames.length; index++) {
  12405. try {
  12406. results.push(this._gl.getAttribLocation(shaderProgram, attributesNames[index]));
  12407. }
  12408. catch (e) {
  12409. results.push(-1);
  12410. }
  12411. }
  12412. return results;
  12413. };
  12414. Engine.prototype.enableEffect = function (effect) {
  12415. if (!effect) {
  12416. return;
  12417. }
  12418. // Use program
  12419. this.bindSamplers(effect);
  12420. this._currentEffect = effect;
  12421. if (effect.onBind) {
  12422. effect.onBind(effect);
  12423. }
  12424. effect.onBindObservable.notifyObservers(effect);
  12425. };
  12426. Engine.prototype.setIntArray = function (uniform, array) {
  12427. if (!uniform)
  12428. return;
  12429. this._gl.uniform1iv(uniform, array);
  12430. };
  12431. Engine.prototype.setIntArray2 = function (uniform, array) {
  12432. if (!uniform || array.length % 2 !== 0)
  12433. return;
  12434. this._gl.uniform2iv(uniform, array);
  12435. };
  12436. Engine.prototype.setIntArray3 = function (uniform, array) {
  12437. if (!uniform || array.length % 3 !== 0)
  12438. return;
  12439. this._gl.uniform3iv(uniform, array);
  12440. };
  12441. Engine.prototype.setIntArray4 = function (uniform, array) {
  12442. if (!uniform || array.length % 4 !== 0)
  12443. return;
  12444. this._gl.uniform4iv(uniform, array);
  12445. };
  12446. Engine.prototype.setFloatArray = function (uniform, array) {
  12447. if (!uniform)
  12448. return;
  12449. this._gl.uniform1fv(uniform, array);
  12450. };
  12451. Engine.prototype.setFloatArray2 = function (uniform, array) {
  12452. if (!uniform || array.length % 2 !== 0)
  12453. return;
  12454. this._gl.uniform2fv(uniform, array);
  12455. };
  12456. Engine.prototype.setFloatArray3 = function (uniform, array) {
  12457. if (!uniform || array.length % 3 !== 0)
  12458. return;
  12459. this._gl.uniform3fv(uniform, array);
  12460. };
  12461. Engine.prototype.setFloatArray4 = function (uniform, array) {
  12462. if (!uniform || array.length % 4 !== 0)
  12463. return;
  12464. this._gl.uniform4fv(uniform, array);
  12465. };
  12466. Engine.prototype.setArray = function (uniform, array) {
  12467. if (!uniform)
  12468. return;
  12469. this._gl.uniform1fv(uniform, array);
  12470. };
  12471. Engine.prototype.setArray2 = function (uniform, array) {
  12472. if (!uniform || array.length % 2 !== 0)
  12473. return;
  12474. this._gl.uniform2fv(uniform, array);
  12475. };
  12476. Engine.prototype.setArray3 = function (uniform, array) {
  12477. if (!uniform || array.length % 3 !== 0)
  12478. return;
  12479. this._gl.uniform3fv(uniform, array);
  12480. };
  12481. Engine.prototype.setArray4 = function (uniform, array) {
  12482. if (!uniform || array.length % 4 !== 0)
  12483. return;
  12484. this._gl.uniform4fv(uniform, array);
  12485. };
  12486. Engine.prototype.setMatrices = function (uniform, matrices) {
  12487. if (!uniform)
  12488. return;
  12489. this._gl.uniformMatrix4fv(uniform, false, matrices);
  12490. };
  12491. Engine.prototype.setMatrix = function (uniform, matrix) {
  12492. if (!uniform)
  12493. return;
  12494. this._gl.uniformMatrix4fv(uniform, false, matrix.toArray());
  12495. };
  12496. Engine.prototype.setMatrix3x3 = function (uniform, matrix) {
  12497. if (!uniform)
  12498. return;
  12499. this._gl.uniformMatrix3fv(uniform, false, matrix);
  12500. };
  12501. Engine.prototype.setMatrix2x2 = function (uniform, matrix) {
  12502. if (!uniform)
  12503. return;
  12504. this._gl.uniformMatrix2fv(uniform, false, matrix);
  12505. };
  12506. Engine.prototype.setInt = function (uniform, value) {
  12507. if (!uniform)
  12508. return;
  12509. this._gl.uniform1i(uniform, value);
  12510. };
  12511. Engine.prototype.setFloat = function (uniform, value) {
  12512. if (!uniform)
  12513. return;
  12514. this._gl.uniform1f(uniform, value);
  12515. };
  12516. Engine.prototype.setFloat2 = function (uniform, x, y) {
  12517. if (!uniform)
  12518. return;
  12519. this._gl.uniform2f(uniform, x, y);
  12520. };
  12521. Engine.prototype.setFloat3 = function (uniform, x, y, z) {
  12522. if (!uniform)
  12523. return;
  12524. this._gl.uniform3f(uniform, x, y, z);
  12525. };
  12526. Engine.prototype.setBool = function (uniform, bool) {
  12527. if (!uniform)
  12528. return;
  12529. this._gl.uniform1i(uniform, bool);
  12530. };
  12531. Engine.prototype.setFloat4 = function (uniform, x, y, z, w) {
  12532. if (!uniform)
  12533. return;
  12534. this._gl.uniform4f(uniform, x, y, z, w);
  12535. };
  12536. Engine.prototype.setColor3 = function (uniform, color3) {
  12537. if (!uniform)
  12538. return;
  12539. this._gl.uniform3f(uniform, color3.r, color3.g, color3.b);
  12540. };
  12541. Engine.prototype.setColor4 = function (uniform, color3, alpha) {
  12542. if (!uniform)
  12543. return;
  12544. this._gl.uniform4f(uniform, color3.r, color3.g, color3.b, alpha);
  12545. };
  12546. /**
  12547. * Sets a Color4 on a uniform variable
  12548. * @param uniform defines the uniform location
  12549. * @param color4 defines the value to be set
  12550. */
  12551. Engine.prototype.setDirectColor4 = function (uniform, color4) {
  12552. if (!uniform)
  12553. return;
  12554. this._gl.uniform4f(uniform, color4.r, color4.g, color4.b, color4.a);
  12555. };
  12556. // States
  12557. Engine.prototype.setState = function (culling, zOffset, force, reverseSide) {
  12558. if (zOffset === void 0) { zOffset = 0; }
  12559. if (reverseSide === void 0) { reverseSide = false; }
  12560. // Culling
  12561. if (this._depthCullingState.cull !== culling || force) {
  12562. this._depthCullingState.cull = culling;
  12563. }
  12564. // Cull face
  12565. var cullFace = this.cullBackFaces ? this._gl.BACK : this._gl.FRONT;
  12566. if (this._depthCullingState.cullFace !== cullFace || force) {
  12567. this._depthCullingState.cullFace = cullFace;
  12568. }
  12569. // Z offset
  12570. this.setZOffset(zOffset);
  12571. // Front face
  12572. var frontFace = reverseSide ? this._gl.CW : this._gl.CCW;
  12573. if (this._depthCullingState.frontFace !== frontFace || force) {
  12574. this._depthCullingState.frontFace = frontFace;
  12575. }
  12576. };
  12577. Engine.prototype.setZOffset = function (value) {
  12578. this._depthCullingState.zOffset = value;
  12579. };
  12580. Engine.prototype.getZOffset = function () {
  12581. return this._depthCullingState.zOffset;
  12582. };
  12583. Engine.prototype.setDepthBuffer = function (enable) {
  12584. this._depthCullingState.depthTest = enable;
  12585. };
  12586. Engine.prototype.getDepthWrite = function () {
  12587. return this._depthCullingState.depthMask;
  12588. };
  12589. Engine.prototype.setDepthWrite = function (enable) {
  12590. this._depthCullingState.depthMask = enable;
  12591. };
  12592. Engine.prototype.setColorWrite = function (enable) {
  12593. this._gl.colorMask(enable, enable, enable, enable);
  12594. this._colorWrite = enable;
  12595. };
  12596. Engine.prototype.getColorWrite = function () {
  12597. return this._colorWrite;
  12598. };
  12599. Engine.prototype.setAlphaConstants = function (r, g, b, a) {
  12600. this._alphaState.setAlphaBlendConstants(r, g, b, a);
  12601. };
  12602. Engine.prototype.setAlphaMode = function (mode, noDepthWriteChange) {
  12603. if (noDepthWriteChange === void 0) { noDepthWriteChange = false; }
  12604. if (this._alphaMode === mode) {
  12605. return;
  12606. }
  12607. switch (mode) {
  12608. case Engine.ALPHA_DISABLE:
  12609. this._alphaState.alphaBlend = false;
  12610. break;
  12611. case Engine.ALPHA_PREMULTIPLIED:
  12612. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  12613. this._alphaState.alphaBlend = true;
  12614. break;
  12615. case Engine.ALPHA_PREMULTIPLIED_PORTERDUFF:
  12616. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA);
  12617. this._alphaState.alphaBlend = true;
  12618. break;
  12619. case Engine.ALPHA_COMBINE:
  12620. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  12621. this._alphaState.alphaBlend = true;
  12622. break;
  12623. case Engine.ALPHA_ONEONE:
  12624. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  12625. this._alphaState.alphaBlend = true;
  12626. break;
  12627. case Engine.ALPHA_ADD:
  12628. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  12629. this._alphaState.alphaBlend = true;
  12630. break;
  12631. case Engine.ALPHA_SUBTRACT:
  12632. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ZERO, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  12633. this._alphaState.alphaBlend = true;
  12634. break;
  12635. case Engine.ALPHA_MULTIPLY:
  12636. this._alphaState.setAlphaBlendFunctionParameters(this._gl.DST_COLOR, this._gl.ZERO, this._gl.ONE, this._gl.ONE);
  12637. this._alphaState.alphaBlend = true;
  12638. break;
  12639. case Engine.ALPHA_MAXIMIZED:
  12640. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  12641. this._alphaState.alphaBlend = true;
  12642. break;
  12643. case Engine.ALPHA_INTERPOLATE:
  12644. this._alphaState.setAlphaBlendFunctionParameters(this._gl.CONSTANT_COLOR, this._gl.ONE_MINUS_CONSTANT_COLOR, this._gl.CONSTANT_ALPHA, this._gl.ONE_MINUS_CONSTANT_ALPHA);
  12645. this._alphaState.alphaBlend = true;
  12646. break;
  12647. case Engine.ALPHA_SCREENMODE:
  12648. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA);
  12649. this._alphaState.alphaBlend = true;
  12650. break;
  12651. }
  12652. if (!noDepthWriteChange) {
  12653. this.setDepthWrite(mode === Engine.ALPHA_DISABLE);
  12654. }
  12655. this._alphaMode = mode;
  12656. };
  12657. Engine.prototype.getAlphaMode = function () {
  12658. return this._alphaMode;
  12659. };
  12660. // Textures
  12661. Engine.prototype.wipeCaches = function (bruteForce) {
  12662. if (this.preventCacheWipeBetweenFrames && !bruteForce) {
  12663. return;
  12664. }
  12665. this._currentEffect = null;
  12666. // 6/8/2017: deltakosh: Should not be required anymore.
  12667. // This message is then mostly for the future myself who will scream out loud when seeing that it was actually required :)
  12668. if (bruteForce) {
  12669. this.resetTextureCache();
  12670. this._currentProgram = null;
  12671. this._stencilState.reset();
  12672. this._depthCullingState.reset();
  12673. this.setDepthFunctionToLessOrEqual();
  12674. this._alphaState.reset();
  12675. }
  12676. this._resetVertexBufferBinding();
  12677. this._cachedIndexBuffer = null;
  12678. this._cachedEffectForVertexBuffers = null;
  12679. this._unbindVertexArrayObject();
  12680. this.bindIndexBuffer(null);
  12681. };
  12682. /**
  12683. * Set the compressed texture format to use, based on the formats you have, and the formats
  12684. * supported by the hardware / browser.
  12685. *
  12686. * Khronos Texture Container (.ktx) files are used to support this. This format has the
  12687. * advantage of being specifically designed for OpenGL. Header elements directly correspond
  12688. * to API arguments needed to compressed textures. This puts the burden on the container
  12689. * generator to house the arcane code for determining these for current & future formats.
  12690. *
  12691. * for description see https://www.khronos.org/opengles/sdk/tools/KTX/
  12692. * for file layout see https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/
  12693. *
  12694. * Note: The result of this call is not taken into account when a texture is base64.
  12695. *
  12696. * @param {Array<string>} formatsAvailable- The list of those format families you have created
  12697. * on your server. Syntax: '-' + format family + '.ktx'. (Case and order do not matter.)
  12698. *
  12699. * Current families are astc, dxt, pvrtc, etc2, & etc1.
  12700. * @returns The extension selected.
  12701. */
  12702. Engine.prototype.setTextureFormatToUse = function (formatsAvailable) {
  12703. for (var i = 0, len1 = this.texturesSupported.length; i < len1; i++) {
  12704. for (var j = 0, len2 = formatsAvailable.length; j < len2; j++) {
  12705. if (this._texturesSupported[i] === formatsAvailable[j].toLowerCase()) {
  12706. return this._textureFormatInUse = this._texturesSupported[i];
  12707. }
  12708. }
  12709. }
  12710. // actively set format to nothing, to allow this to be called more than once
  12711. // and possibly fail the 2nd time
  12712. this._textureFormatInUse = null;
  12713. return null;
  12714. };
  12715. Engine.prototype._createTexture = function () {
  12716. var texture = this._gl.createTexture();
  12717. if (!texture) {
  12718. throw new Error("Unable to create texture");
  12719. }
  12720. return texture;
  12721. };
  12722. /**
  12723. * Usually called from BABYLON.Texture.ts. Passed information to create a WebGLTexture.
  12724. * @param {string} urlArg- This contains one of the following:
  12725. * 1. A conventional http URL, e.g. 'http://...' or 'file://...'
  12726. * 2. A base64 string of in-line texture data, e.g. 'data:image/jpg;base64,/...'
  12727. * 3. An indicator that data being passed using the buffer parameter, e.g. 'data:mytexture.jpg'
  12728. *
  12729. * @param {boolean} noMipmap- When true, no mipmaps shall be generated. Ignored for compressed textures. They must be in the file.
  12730. * @param {boolean} invertY- When true, image is flipped when loaded. You probably want true. Ignored for compressed textures. Must be flipped in the file.
  12731. * @param {Scene} scene- Needed for loading to the correct scene.
  12732. * @param {number} samplingMode- Mode with should be used sample / access the texture. Default: TRILINEAR
  12733. * @param {callback} onLoad- Optional callback to be called upon successful completion.
  12734. * @param {callback} onError- Optional callback to be called upon failure.
  12735. * @param {ArrayBuffer | HTMLImageElement} buffer- A source of a file previously fetched as either an ArrayBuffer (compressed or image format) or HTMLImageElement (image format)
  12736. * @param {WebGLTexture} fallback- An internal argument in case the function must be called again, due to etc1 not having alpha capabilities.
  12737. * @param {number} format- Internal format. Default: RGB when extension is '.jpg' else RGBA. Ignored for compressed textures.
  12738. *
  12739. * @returns {WebGLTexture} for assignment back into BABYLON.Texture
  12740. */
  12741. Engine.prototype.createTexture = function (urlArg, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer, fallBack, format) {
  12742. var _this = this;
  12743. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  12744. if (onLoad === void 0) { onLoad = null; }
  12745. if (onError === void 0) { onError = null; }
  12746. if (buffer === void 0) { buffer = null; }
  12747. if (fallBack === void 0) { fallBack = null; }
  12748. if (format === void 0) { format = null; }
  12749. var url = String(urlArg); // assign a new string, so that the original is still available in case of fallback
  12750. var fromData = url.substr(0, 5) === "data:";
  12751. var fromBlob = url.substr(0, 5) === "blob:";
  12752. var isBase64 = fromData && url.indexOf("base64") !== -1;
  12753. var texture = fallBack ? fallBack : new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_URL);
  12754. // establish the file extension, if possible
  12755. var lastDot = url.lastIndexOf('.');
  12756. var extension = (lastDot > 0) ? url.substring(lastDot).toLowerCase() : "";
  12757. var isDDS = this.getCaps().s3tc && (extension.indexOf(".dds") === 0);
  12758. var isTGA = (extension.indexOf(".tga") === 0);
  12759. // determine if a ktx file should be substituted
  12760. var isKTX = false;
  12761. if (this._textureFormatInUse && !isBase64 && !fallBack) {
  12762. url = url.substring(0, lastDot) + this._textureFormatInUse;
  12763. isKTX = true;
  12764. }
  12765. if (scene) {
  12766. scene._addPendingData(texture);
  12767. }
  12768. texture.url = url;
  12769. texture.generateMipMaps = !noMipmap;
  12770. texture.samplingMode = samplingMode;
  12771. texture.invertY = invertY;
  12772. if (!this._doNotHandleContextLost) {
  12773. // Keep a link to the buffer only if we plan to handle context lost
  12774. texture._buffer = buffer;
  12775. }
  12776. var onLoadObserver = null;
  12777. if (onLoad && !fallBack) {
  12778. onLoadObserver = texture.onLoadedObservable.add(onLoad);
  12779. }
  12780. if (!fallBack)
  12781. this._internalTexturesCache.push(texture);
  12782. var onerror = function (message, exception) {
  12783. if (scene) {
  12784. scene._removePendingData(texture);
  12785. }
  12786. if (onLoadObserver) {
  12787. texture.onLoadedObservable.remove(onLoadObserver);
  12788. }
  12789. // fallback for when compressed file not found to try again. For instance, etc1 does not have an alpha capable type
  12790. if (isKTX) {
  12791. _this.createTexture(urlArg, noMipmap, invertY, scene, samplingMode, null, onError, buffer, texture);
  12792. }
  12793. else if (BABYLON.Tools.UseFallbackTexture) {
  12794. _this.createTexture(BABYLON.Tools.fallbackTexture, noMipmap, invertY, scene, samplingMode, null, onError, buffer, texture);
  12795. }
  12796. if (onError) {
  12797. onError(message || "Unknown error", exception);
  12798. }
  12799. };
  12800. var callback = null;
  12801. // processing for non-image formats
  12802. if (isKTX || isTGA || isDDS) {
  12803. if (isKTX) {
  12804. callback = function (data) {
  12805. var ktx = new BABYLON.KhronosTextureContainer(data, 1);
  12806. _this._prepareWebGLTexture(texture, scene, ktx.pixelWidth, ktx.pixelHeight, invertY, false, true, function () {
  12807. ktx.uploadLevels(_this._gl, !noMipmap);
  12808. return false;
  12809. }, samplingMode);
  12810. };
  12811. }
  12812. else if (isTGA) {
  12813. callback = function (arrayBuffer) {
  12814. var data = new Uint8Array(arrayBuffer);
  12815. var header = BABYLON.TGATools.GetTGAHeader(data);
  12816. _this._prepareWebGLTexture(texture, scene, header.width, header.height, invertY, noMipmap, false, function () {
  12817. BABYLON.TGATools.UploadContent(_this._gl, data);
  12818. return false;
  12819. }, samplingMode);
  12820. };
  12821. }
  12822. else if (isDDS) {
  12823. callback = function (data) {
  12824. var info = BABYLON.DDSTools.GetDDSInfo(data);
  12825. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap && ((info.width >> (info.mipmapCount - 1)) === 1);
  12826. _this._prepareWebGLTexture(texture, scene, info.width, info.height, invertY, !loadMipmap, info.isFourCC, function () {
  12827. BABYLON.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, loadMipmap, 1);
  12828. return false;
  12829. }, samplingMode);
  12830. };
  12831. }
  12832. if (!buffer) {
  12833. this._loadFile(url, function (data) {
  12834. if (callback) {
  12835. callback(data);
  12836. }
  12837. }, undefined, scene ? scene.database : undefined, true, function (request, exception) {
  12838. onerror("Unable to load " + (request ? request.responseURL : url, exception));
  12839. });
  12840. }
  12841. else {
  12842. if (callback) {
  12843. callback(buffer);
  12844. }
  12845. }
  12846. // image format processing
  12847. }
  12848. else {
  12849. var onload = function (img) {
  12850. if (fromBlob && !_this._doNotHandleContextLost) {
  12851. // We need to store the image if we need to rebuild the texture
  12852. // in case of a webgl context lost
  12853. texture._buffer = img;
  12854. }
  12855. _this._prepareWebGLTexture(texture, scene, img.width, img.height, invertY, noMipmap, false, function (potWidth, potHeight, continuationCallback) {
  12856. var gl = _this._gl;
  12857. var isPot = (img.width === potWidth && img.height === potHeight);
  12858. var internalFormat = format ? _this._getInternalFormat(format) : ((extension === ".jpg") ? gl.RGB : gl.RGBA);
  12859. if (isPot) {
  12860. gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, img);
  12861. return false;
  12862. }
  12863. // Using shaders to rescale because canvas.drawImage is lossy
  12864. var source = new BABYLON.InternalTexture(_this, BABYLON.InternalTexture.DATASOURCE_TEMP);
  12865. _this._bindTextureDirectly(gl.TEXTURE_2D, source, true);
  12866. gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, img);
  12867. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  12868. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
  12869. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  12870. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  12871. _this._rescaleTexture(source, texture, scene, internalFormat, function () {
  12872. _this._releaseTexture(source);
  12873. _this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  12874. continuationCallback();
  12875. });
  12876. return true;
  12877. }, samplingMode);
  12878. };
  12879. if (!fromData || isBase64)
  12880. if (buffer instanceof HTMLImageElement) {
  12881. onload(buffer);
  12882. }
  12883. else {
  12884. BABYLON.Tools.LoadImage(url, onload, onerror, scene ? scene.database : null);
  12885. }
  12886. else if (buffer instanceof Array || typeof buffer === "string" || buffer instanceof ArrayBuffer)
  12887. BABYLON.Tools.LoadImage(buffer, onload, onerror, scene ? scene.database : null);
  12888. else
  12889. onload(buffer);
  12890. }
  12891. return texture;
  12892. };
  12893. Engine.prototype._rescaleTexture = function (source, destination, scene, internalFormat, onComplete) {
  12894. var _this = this;
  12895. var rtt = this.createRenderTargetTexture({
  12896. width: destination.width,
  12897. height: destination.height,
  12898. }, {
  12899. generateMipMaps: false,
  12900. type: Engine.TEXTURETYPE_UNSIGNED_INT,
  12901. samplingMode: BABYLON.Texture.BILINEAR_SAMPLINGMODE,
  12902. generateDepthBuffer: false,
  12903. generateStencilBuffer: false
  12904. });
  12905. if (!this._rescalePostProcess) {
  12906. this._rescalePostProcess = new BABYLON.PassPostProcess("rescale", 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this, false, Engine.TEXTURETYPE_UNSIGNED_INT);
  12907. }
  12908. this._rescalePostProcess.getEffect().executeWhenCompiled(function () {
  12909. _this._rescalePostProcess.onApply = function (effect) {
  12910. effect._bindTexture("textureSampler", source);
  12911. };
  12912. var hostingScene = scene;
  12913. if (!hostingScene) {
  12914. hostingScene = _this.scenes[_this.scenes.length - 1];
  12915. }
  12916. hostingScene.postProcessManager.directRender([_this._rescalePostProcess], rtt, true);
  12917. _this._bindTextureDirectly(_this._gl.TEXTURE_2D, destination, true);
  12918. _this._gl.copyTexImage2D(_this._gl.TEXTURE_2D, 0, internalFormat, 0, 0, destination.width, destination.height, 0);
  12919. _this.unBindFramebuffer(rtt);
  12920. _this._releaseTexture(rtt);
  12921. if (onComplete) {
  12922. onComplete();
  12923. }
  12924. });
  12925. };
  12926. Engine.prototype._getInternalFormat = function (format) {
  12927. var internalFormat = this._gl.RGBA;
  12928. switch (format) {
  12929. case Engine.TEXTUREFORMAT_ALPHA:
  12930. internalFormat = this._gl.ALPHA;
  12931. break;
  12932. case Engine.TEXTUREFORMAT_LUMINANCE:
  12933. internalFormat = this._gl.LUMINANCE;
  12934. break;
  12935. case Engine.TEXTUREFORMAT_LUMINANCE_ALPHA:
  12936. internalFormat = this._gl.LUMINANCE_ALPHA;
  12937. break;
  12938. case Engine.TEXTUREFORMAT_RGB:
  12939. case Engine.TEXTUREFORMAT_RGB32F:
  12940. internalFormat = this._gl.RGB;
  12941. break;
  12942. case Engine.TEXTUREFORMAT_RGBA:
  12943. internalFormat = this._gl.RGBA;
  12944. break;
  12945. case Engine.TEXTUREFORMAT_R32F:
  12946. internalFormat = this._gl.RED;
  12947. break;
  12948. case Engine.TEXTUREFORMAT_RG32F:
  12949. internalFormat = this._gl.RG;
  12950. break;
  12951. }
  12952. return internalFormat;
  12953. };
  12954. Engine.prototype.updateRawTexture = function (texture, data, format, invertY, compression, type) {
  12955. if (compression === void 0) { compression = null; }
  12956. if (type === void 0) { type = Engine.TEXTURETYPE_UNSIGNED_INT; }
  12957. if (!texture) {
  12958. return;
  12959. }
  12960. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(type, format);
  12961. var internalFormat = this._getInternalFormat(format);
  12962. var textureType = this._getWebGLTextureType(type);
  12963. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  12964. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  12965. if (!this._doNotHandleContextLost) {
  12966. texture._bufferView = data;
  12967. texture.format = format;
  12968. texture.type = type;
  12969. texture.invertY = invertY;
  12970. texture._compression = compression;
  12971. }
  12972. if (texture.width % 4 !== 0) {
  12973. this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT, 1);
  12974. }
  12975. if (compression && data) {
  12976. this._gl.compressedTexImage2D(this._gl.TEXTURE_2D, 0, this.getCaps().s3tc[compression], texture.width, texture.height, 0, data);
  12977. }
  12978. else {
  12979. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalSizedFomat, texture.width, texture.height, 0, internalFormat, textureType, data);
  12980. }
  12981. if (texture.generateMipMaps) {
  12982. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  12983. }
  12984. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  12985. // this.resetTextureCache();
  12986. texture.isReady = true;
  12987. };
  12988. Engine.prototype.createRawTexture = function (data, width, height, format, generateMipMaps, invertY, samplingMode, compression, type) {
  12989. if (compression === void 0) { compression = null; }
  12990. if (type === void 0) { type = Engine.TEXTURETYPE_UNSIGNED_INT; }
  12991. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RAW);
  12992. texture.baseWidth = width;
  12993. texture.baseHeight = height;
  12994. texture.width = width;
  12995. texture.height = height;
  12996. texture.format = format;
  12997. texture.generateMipMaps = generateMipMaps;
  12998. texture.samplingMode = samplingMode;
  12999. texture.invertY = invertY;
  13000. texture._compression = compression;
  13001. texture.type = type;
  13002. if (!this._doNotHandleContextLost) {
  13003. texture._bufferView = data;
  13004. }
  13005. this.updateRawTexture(texture, data, format, invertY, compression, type);
  13006. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  13007. // Filters
  13008. var filters = getSamplingParameters(samplingMode, generateMipMaps, this._gl);
  13009. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  13010. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  13011. if (generateMipMaps) {
  13012. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  13013. }
  13014. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  13015. this._internalTexturesCache.push(texture);
  13016. return texture;
  13017. };
  13018. Engine.prototype.createDynamicTexture = function (width, height, generateMipMaps, samplingMode) {
  13019. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_DYNAMIC);
  13020. texture.baseWidth = width;
  13021. texture.baseHeight = height;
  13022. if (generateMipMaps) {
  13023. width = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(width, this._caps.maxTextureSize) : width;
  13024. height = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(height, this._caps.maxTextureSize) : height;
  13025. }
  13026. // this.resetTextureCache();
  13027. texture.width = width;
  13028. texture.height = height;
  13029. texture.isReady = false;
  13030. texture.generateMipMaps = generateMipMaps;
  13031. texture.samplingMode = samplingMode;
  13032. this.updateTextureSamplingMode(samplingMode, texture);
  13033. this._internalTexturesCache.push(texture);
  13034. return texture;
  13035. };
  13036. Engine.prototype.updateTextureSamplingMode = function (samplingMode, texture) {
  13037. var filters = getSamplingParameters(samplingMode, texture.generateMipMaps, this._gl);
  13038. if (texture.isCube) {
  13039. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture, true);
  13040. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  13041. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MIN_FILTER, filters.min);
  13042. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  13043. }
  13044. else if (texture.is3D) {
  13045. this._bindTextureDirectly(this._gl.TEXTURE_3D, texture, true);
  13046. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  13047. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  13048. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  13049. }
  13050. else {
  13051. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  13052. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  13053. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  13054. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  13055. }
  13056. texture.samplingMode = samplingMode;
  13057. };
  13058. Engine.prototype.updateDynamicTexture = function (texture, canvas, invertY, premulAlpha, format) {
  13059. if (premulAlpha === void 0) { premulAlpha = false; }
  13060. if (!texture) {
  13061. return;
  13062. }
  13063. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  13064. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 1 : 0);
  13065. if (premulAlpha) {
  13066. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 1);
  13067. }
  13068. var internalFormat = format ? this._getInternalFormat(format) : this._gl.RGBA;
  13069. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalFormat, internalFormat, this._gl.UNSIGNED_BYTE, canvas);
  13070. if (texture.generateMipMaps) {
  13071. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  13072. }
  13073. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  13074. if (premulAlpha) {
  13075. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 0);
  13076. }
  13077. texture.isReady = true;
  13078. };
  13079. Engine.prototype.updateVideoTexture = function (texture, video, invertY) {
  13080. if (!texture || texture._isDisabled) {
  13081. return;
  13082. }
  13083. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  13084. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 0 : 1); // Video are upside down by default
  13085. try {
  13086. // Testing video texture support
  13087. if (this._videoTextureSupported === undefined) {
  13088. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  13089. if (this._gl.getError() !== 0) {
  13090. this._videoTextureSupported = false;
  13091. }
  13092. else {
  13093. this._videoTextureSupported = true;
  13094. }
  13095. }
  13096. // Copy video through the current working canvas if video texture is not supported
  13097. if (!this._videoTextureSupported) {
  13098. if (!texture._workingCanvas) {
  13099. texture._workingCanvas = document.createElement("canvas");
  13100. var context = texture._workingCanvas.getContext("2d");
  13101. if (!context) {
  13102. throw new Error("Unable to get 2d context");
  13103. }
  13104. texture._workingContext = context;
  13105. texture._workingCanvas.width = texture.width;
  13106. texture._workingCanvas.height = texture.height;
  13107. }
  13108. texture._workingContext.drawImage(video, 0, 0, video.videoWidth, video.videoHeight, 0, 0, texture.width, texture.height);
  13109. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, texture._workingCanvas);
  13110. }
  13111. else {
  13112. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  13113. }
  13114. if (texture.generateMipMaps) {
  13115. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  13116. }
  13117. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  13118. // this.resetTextureCache();
  13119. texture.isReady = true;
  13120. }
  13121. catch (ex) {
  13122. // Something unexpected
  13123. // Let's disable the texture
  13124. texture._isDisabled = true;
  13125. }
  13126. };
  13127. Engine.prototype.createRenderTargetTexture = function (size, options) {
  13128. var fullOptions = new RenderTargetCreationOptions();
  13129. if (options !== undefined && typeof options === "object") {
  13130. fullOptions.generateMipMaps = options.generateMipMaps;
  13131. fullOptions.generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  13132. fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && options.generateStencilBuffer;
  13133. fullOptions.type = options.type === undefined ? Engine.TEXTURETYPE_UNSIGNED_INT : options.type;
  13134. fullOptions.samplingMode = options.samplingMode === undefined ? BABYLON.Texture.TRILINEAR_SAMPLINGMODE : options.samplingMode;
  13135. }
  13136. else {
  13137. fullOptions.generateMipMaps = options;
  13138. fullOptions.generateDepthBuffer = true;
  13139. fullOptions.generateStencilBuffer = false;
  13140. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  13141. fullOptions.samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  13142. }
  13143. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  13144. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  13145. fullOptions.samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  13146. }
  13147. else if (fullOptions.type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  13148. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  13149. fullOptions.samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  13150. }
  13151. var gl = this._gl;
  13152. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  13153. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  13154. var width = size.width || size;
  13155. var height = size.height || size;
  13156. var filters = getSamplingParameters(fullOptions.samplingMode, fullOptions.generateMipMaps ? true : false, gl);
  13157. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  13158. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  13159. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  13160. }
  13161. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  13162. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  13163. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  13164. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  13165. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(fullOptions.type), width, height, 0, gl.RGBA, this._getWebGLTextureType(fullOptions.type), null);
  13166. // Create the framebuffer
  13167. var framebuffer = gl.createFramebuffer();
  13168. this.bindUnboundFramebuffer(framebuffer);
  13169. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture._webGLTexture, 0);
  13170. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(fullOptions.generateStencilBuffer ? true : false, fullOptions.generateDepthBuffer, width, height);
  13171. if (fullOptions.generateMipMaps) {
  13172. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  13173. }
  13174. // Unbind
  13175. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  13176. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  13177. this.bindUnboundFramebuffer(null);
  13178. texture._framebuffer = framebuffer;
  13179. texture.baseWidth = width;
  13180. texture.baseHeight = height;
  13181. texture.width = width;
  13182. texture.height = height;
  13183. texture.isReady = true;
  13184. texture.samples = 1;
  13185. texture.generateMipMaps = fullOptions.generateMipMaps ? true : false;
  13186. texture.samplingMode = fullOptions.samplingMode;
  13187. texture.type = fullOptions.type;
  13188. texture._generateDepthBuffer = fullOptions.generateDepthBuffer;
  13189. texture._generateStencilBuffer = fullOptions.generateStencilBuffer ? true : false;
  13190. // this.resetTextureCache();
  13191. this._internalTexturesCache.push(texture);
  13192. return texture;
  13193. };
  13194. Engine.prototype.createMultipleRenderTarget = function (size, options) {
  13195. var generateMipMaps = false;
  13196. var generateDepthBuffer = true;
  13197. var generateStencilBuffer = false;
  13198. var generateDepthTexture = false;
  13199. var textureCount = 1;
  13200. var defaultType = Engine.TEXTURETYPE_UNSIGNED_INT;
  13201. var defaultSamplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  13202. var types = [], samplingModes = [];
  13203. if (options !== undefined) {
  13204. generateMipMaps = options.generateMipMaps;
  13205. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  13206. generateStencilBuffer = options.generateStencilBuffer;
  13207. generateDepthTexture = options.generateDepthTexture;
  13208. textureCount = options.textureCount || 1;
  13209. if (options.types) {
  13210. types = options.types;
  13211. }
  13212. if (options.samplingModes) {
  13213. samplingModes = options.samplingModes;
  13214. }
  13215. }
  13216. var gl = this._gl;
  13217. // Create the framebuffer
  13218. var framebuffer = gl.createFramebuffer();
  13219. this.bindUnboundFramebuffer(framebuffer);
  13220. var width = size.width || size;
  13221. var height = size.height || size;
  13222. var textures = [];
  13223. var attachments = [];
  13224. var depthStencilBuffer = this._setupFramebufferDepthAttachments(generateStencilBuffer, generateDepthBuffer, width, height);
  13225. for (var i = 0; i < textureCount; i++) {
  13226. var samplingMode = samplingModes[i] || defaultSamplingMode;
  13227. var type = types[i] || defaultType;
  13228. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  13229. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  13230. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  13231. }
  13232. else if (type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  13233. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  13234. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  13235. }
  13236. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  13237. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  13238. type = Engine.TEXTURETYPE_UNSIGNED_INT;
  13239. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  13240. }
  13241. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_MULTIRENDERTARGET);
  13242. var attachment = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  13243. textures.push(texture);
  13244. attachments.push(attachment);
  13245. gl.activeTexture(gl["TEXTURE" + i]);
  13246. gl.bindTexture(gl.TEXTURE_2D, texture._webGLTexture);
  13247. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  13248. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  13249. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  13250. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  13251. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), width, height, 0, gl.RGBA, this._getWebGLTextureType(type), null);
  13252. gl.framebufferTexture2D(gl.DRAW_FRAMEBUFFER, attachment, gl.TEXTURE_2D, texture._webGLTexture, 0);
  13253. if (generateMipMaps) {
  13254. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  13255. }
  13256. // Unbind
  13257. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  13258. texture._framebuffer = framebuffer;
  13259. texture._depthStencilBuffer = depthStencilBuffer;
  13260. texture.baseWidth = width;
  13261. texture.baseHeight = height;
  13262. texture.width = width;
  13263. texture.height = height;
  13264. texture.isReady = true;
  13265. texture.samples = 1;
  13266. texture.generateMipMaps = generateMipMaps;
  13267. texture.samplingMode = samplingMode;
  13268. texture.type = type;
  13269. texture._generateDepthBuffer = generateDepthBuffer;
  13270. texture._generateStencilBuffer = generateStencilBuffer;
  13271. texture._attachments = attachments;
  13272. this._internalTexturesCache.push(texture);
  13273. }
  13274. if (generateDepthTexture && this._caps.depthTextureExtension) {
  13275. // Depth texture
  13276. var depthTexture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_MULTIRENDERTARGET);
  13277. gl.activeTexture(gl.TEXTURE0);
  13278. gl.bindTexture(gl.TEXTURE_2D, depthTexture._webGLTexture);
  13279. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  13280. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  13281. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  13282. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  13283. gl.texImage2D(gl.TEXTURE_2D, 0, this.webGLVersion < 2 ? gl.DEPTH_COMPONENT : gl.DEPTH_COMPONENT16, width, height, 0, gl.DEPTH_COMPONENT, gl.UNSIGNED_SHORT, null);
  13284. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_2D, depthTexture._webGLTexture, 0);
  13285. depthTexture._framebuffer = framebuffer;
  13286. depthTexture.baseWidth = width;
  13287. depthTexture.baseHeight = height;
  13288. depthTexture.width = width;
  13289. depthTexture.height = height;
  13290. depthTexture.isReady = true;
  13291. depthTexture.samples = 1;
  13292. depthTexture.generateMipMaps = generateMipMaps;
  13293. depthTexture.samplingMode = gl.NEAREST;
  13294. depthTexture._generateDepthBuffer = generateDepthBuffer;
  13295. depthTexture._generateStencilBuffer = generateStencilBuffer;
  13296. textures.push(depthTexture);
  13297. this._internalTexturesCache.push(depthTexture);
  13298. }
  13299. gl.drawBuffers(attachments);
  13300. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  13301. this.bindUnboundFramebuffer(null);
  13302. this.resetTextureCache();
  13303. return textures;
  13304. };
  13305. Engine.prototype._setupFramebufferDepthAttachments = function (generateStencilBuffer, generateDepthBuffer, width, height, samples) {
  13306. if (samples === void 0) { samples = 1; }
  13307. var depthStencilBuffer = null;
  13308. var gl = this._gl;
  13309. // Create the depth/stencil buffer
  13310. if (generateStencilBuffer) {
  13311. depthStencilBuffer = gl.createRenderbuffer();
  13312. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  13313. if (samples > 1) {
  13314. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.DEPTH24_STENCIL8, width, height);
  13315. }
  13316. else {
  13317. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_STENCIL, width, height);
  13318. }
  13319. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  13320. }
  13321. else if (generateDepthBuffer) {
  13322. depthStencilBuffer = gl.createRenderbuffer();
  13323. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  13324. if (samples > 1) {
  13325. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.DEPTH_COMPONENT16, width, height);
  13326. }
  13327. else {
  13328. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, width, height);
  13329. }
  13330. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  13331. }
  13332. return depthStencilBuffer;
  13333. };
  13334. Engine.prototype.updateRenderTargetTextureSampleCount = function (texture, samples) {
  13335. if (this.webGLVersion < 2 || !texture) {
  13336. return 1;
  13337. }
  13338. if (texture.samples === samples) {
  13339. return samples;
  13340. }
  13341. var gl = this._gl;
  13342. samples = Math.min(samples, gl.getParameter(gl.MAX_SAMPLES));
  13343. // Dispose previous render buffers
  13344. if (texture._depthStencilBuffer) {
  13345. gl.deleteRenderbuffer(texture._depthStencilBuffer);
  13346. texture._depthStencilBuffer = null;
  13347. }
  13348. if (texture._MSAAFramebuffer) {
  13349. gl.deleteFramebuffer(texture._MSAAFramebuffer);
  13350. texture._MSAAFramebuffer = null;
  13351. }
  13352. if (texture._MSAARenderBuffer) {
  13353. gl.deleteRenderbuffer(texture._MSAARenderBuffer);
  13354. texture._MSAARenderBuffer = null;
  13355. }
  13356. if (samples > 1) {
  13357. var framebuffer = gl.createFramebuffer();
  13358. if (!framebuffer) {
  13359. throw new Error("Unable to create multi sampled framebuffer");
  13360. }
  13361. texture._MSAAFramebuffer = framebuffer;
  13362. this.bindUnboundFramebuffer(texture._MSAAFramebuffer);
  13363. var colorRenderbuffer = gl.createRenderbuffer();
  13364. if (!colorRenderbuffer) {
  13365. throw new Error("Unable to create multi sampled framebuffer");
  13366. }
  13367. gl.bindRenderbuffer(gl.RENDERBUFFER, colorRenderbuffer);
  13368. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, this._getRGBAMultiSampleBufferFormat(texture.type), texture.width, texture.height);
  13369. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.RENDERBUFFER, colorRenderbuffer);
  13370. texture._MSAARenderBuffer = colorRenderbuffer;
  13371. }
  13372. else {
  13373. this.bindUnboundFramebuffer(texture._framebuffer);
  13374. }
  13375. texture.samples = samples;
  13376. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(texture._generateStencilBuffer, texture._generateDepthBuffer, texture.width, texture.height, samples);
  13377. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  13378. this.bindUnboundFramebuffer(null);
  13379. return samples;
  13380. };
  13381. Engine.prototype.updateMultipleRenderTargetTextureSampleCount = function (textures, samples) {
  13382. if (this.webGLVersion < 2 || !textures || textures.length == 0) {
  13383. return 1;
  13384. }
  13385. if (textures[0].samples === samples) {
  13386. return samples;
  13387. }
  13388. var gl = this._gl;
  13389. samples = Math.min(samples, gl.getParameter(gl.MAX_SAMPLES));
  13390. // Dispose previous render buffers
  13391. if (textures[0]._depthStencilBuffer) {
  13392. gl.deleteRenderbuffer(textures[0]._depthStencilBuffer);
  13393. textures[0]._depthStencilBuffer = null;
  13394. }
  13395. if (textures[0]._MSAAFramebuffer) {
  13396. gl.deleteFramebuffer(textures[0]._MSAAFramebuffer);
  13397. textures[0]._MSAAFramebuffer = null;
  13398. }
  13399. for (var i = 0; i < textures.length; i++) {
  13400. if (textures[i]._MSAARenderBuffer) {
  13401. gl.deleteRenderbuffer(textures[i]._MSAARenderBuffer);
  13402. textures[i]._MSAARenderBuffer = null;
  13403. }
  13404. }
  13405. if (samples > 1) {
  13406. var framebuffer = gl.createFramebuffer();
  13407. if (!framebuffer) {
  13408. throw new Error("Unable to create multi sampled framebuffer");
  13409. }
  13410. this.bindUnboundFramebuffer(framebuffer);
  13411. var depthStencilBuffer = this._setupFramebufferDepthAttachments(textures[0]._generateStencilBuffer, textures[0]._generateDepthBuffer, textures[0].width, textures[0].height, samples);
  13412. var attachments = [];
  13413. for (var i = 0; i < textures.length; i++) {
  13414. var texture = textures[i];
  13415. var attachment = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  13416. var colorRenderbuffer = gl.createRenderbuffer();
  13417. if (!colorRenderbuffer) {
  13418. throw new Error("Unable to create multi sampled framebuffer");
  13419. }
  13420. gl.bindRenderbuffer(gl.RENDERBUFFER, colorRenderbuffer);
  13421. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, this._getRGBAMultiSampleBufferFormat(texture.type), texture.width, texture.height);
  13422. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, attachment, gl.RENDERBUFFER, colorRenderbuffer);
  13423. texture._MSAAFramebuffer = framebuffer;
  13424. texture._MSAARenderBuffer = colorRenderbuffer;
  13425. texture.samples = samples;
  13426. texture._depthStencilBuffer = depthStencilBuffer;
  13427. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  13428. attachments.push(attachment);
  13429. }
  13430. gl.drawBuffers(attachments);
  13431. }
  13432. else {
  13433. this.bindUnboundFramebuffer(textures[0]._framebuffer);
  13434. }
  13435. this.bindUnboundFramebuffer(null);
  13436. return samples;
  13437. };
  13438. Engine.prototype._uploadDataToTexture = function (target, lod, internalFormat, width, height, format, type, data) {
  13439. this._gl.texImage2D(target, lod, internalFormat, width, height, 0, format, type, data);
  13440. };
  13441. Engine.prototype._uploadCompressedDataToTexture = function (target, lod, internalFormat, width, height, data) {
  13442. this._gl.compressedTexImage2D(target, lod, internalFormat, width, height, 0, data);
  13443. };
  13444. Engine.prototype.createRenderTargetCubeTexture = function (size, options) {
  13445. var fullOptions = __assign({ generateMipMaps: true, generateDepthBuffer: true, generateStencilBuffer: false, type: Engine.TEXTURETYPE_UNSIGNED_INT, samplingMode: BABYLON.Texture.TRILINEAR_SAMPLINGMODE }, options);
  13446. fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && fullOptions.generateStencilBuffer;
  13447. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  13448. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  13449. fullOptions.samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  13450. }
  13451. else if (fullOptions.type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  13452. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  13453. fullOptions.samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  13454. }
  13455. var gl = this._gl;
  13456. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  13457. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  13458. var filters = getSamplingParameters(fullOptions.samplingMode, fullOptions.generateMipMaps, gl);
  13459. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  13460. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  13461. BABYLON.Tools.Warn("Float textures are not supported. Cube render target forced to TEXTURETYPE_UNESIGNED_BYTE type");
  13462. }
  13463. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  13464. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  13465. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  13466. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  13467. for (var face = 0; face < 6; face++) {
  13468. gl.texImage2D((gl.TEXTURE_CUBE_MAP_POSITIVE_X + face), 0, this._getRGBABufferInternalSizedFormat(fullOptions.type), size, size, 0, gl.RGBA, this._getWebGLTextureType(fullOptions.type), null);
  13469. }
  13470. // Create the framebuffer
  13471. var framebuffer = gl.createFramebuffer();
  13472. this.bindUnboundFramebuffer(framebuffer);
  13473. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(fullOptions.generateStencilBuffer, fullOptions.generateDepthBuffer, size, size);
  13474. // MipMaps
  13475. if (fullOptions.generateMipMaps) {
  13476. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  13477. }
  13478. // Unbind
  13479. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  13480. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  13481. this.bindUnboundFramebuffer(null);
  13482. texture._framebuffer = framebuffer;
  13483. texture.width = size;
  13484. texture.height = size;
  13485. texture.isReady = true;
  13486. texture.isCube = true;
  13487. texture.samples = 1;
  13488. texture.generateMipMaps = fullOptions.generateMipMaps;
  13489. texture.samplingMode = fullOptions.samplingMode;
  13490. texture.type = fullOptions.type;
  13491. texture._generateDepthBuffer = fullOptions.generateDepthBuffer;
  13492. texture._generateStencilBuffer = fullOptions.generateStencilBuffer;
  13493. this._internalTexturesCache.push(texture);
  13494. return texture;
  13495. };
  13496. Engine.prototype.createPrefilteredCubeTexture = function (rootUrl, scene, scale, offset, onLoad, onError, format, forcedExtension) {
  13497. var _this = this;
  13498. if (onLoad === void 0) { onLoad = null; }
  13499. if (onError === void 0) { onError = null; }
  13500. if (forcedExtension === void 0) { forcedExtension = null; }
  13501. var callback = function (loadData) {
  13502. if (!loadData) {
  13503. if (onLoad) {
  13504. onLoad(null);
  13505. }
  13506. return;
  13507. }
  13508. var texture = loadData.texture;
  13509. texture._dataSource = BABYLON.InternalTexture.DATASOURCE_CUBEPREFILTERED;
  13510. texture._lodGenerationScale = scale;
  13511. texture._lodGenerationOffset = offset;
  13512. if (_this._caps.textureLOD) {
  13513. // Do not add extra process if texture lod is supported.
  13514. if (onLoad) {
  13515. onLoad(texture);
  13516. }
  13517. return;
  13518. }
  13519. var mipSlices = 3;
  13520. var gl = _this._gl;
  13521. var width = loadData.width;
  13522. if (!width) {
  13523. return;
  13524. }
  13525. var textures = [];
  13526. for (var i = 0; i < mipSlices; i++) {
  13527. //compute LOD from even spacing in smoothness (matching shader calculation)
  13528. var smoothness = i / (mipSlices - 1);
  13529. var roughness = 1 - smoothness;
  13530. var minLODIndex = offset; // roughness = 0
  13531. var maxLODIndex = BABYLON.Scalar.Log2(width) * scale + offset; // roughness = 1
  13532. var lodIndex = minLODIndex + (maxLODIndex - minLODIndex) * roughness;
  13533. var mipmapIndex = Math.round(Math.min(Math.max(lodIndex, 0), maxLODIndex));
  13534. var glTextureFromLod = new BABYLON.InternalTexture(_this, BABYLON.InternalTexture.DATASOURCE_TEMP);
  13535. glTextureFromLod.isCube = true;
  13536. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, glTextureFromLod, true);
  13537. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  13538. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
  13539. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  13540. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  13541. if (loadData.isDDS) {
  13542. var info = loadData.info;
  13543. var data = loadData.data;
  13544. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, info.isCompressed ? 1 : 0);
  13545. BABYLON.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, true, 6, mipmapIndex);
  13546. }
  13547. else {
  13548. BABYLON.Tools.Warn("DDS is the only prefiltered cube map supported so far.");
  13549. }
  13550. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  13551. // Wrap in a base texture for easy binding.
  13552. var lodTexture = new BABYLON.BaseTexture(scene);
  13553. lodTexture.isCube = true;
  13554. lodTexture._texture = glTextureFromLod;
  13555. glTextureFromLod.isReady = true;
  13556. textures.push(lodTexture);
  13557. }
  13558. texture._lodTextureHigh = textures[2];
  13559. texture._lodTextureMid = textures[1];
  13560. texture._lodTextureLow = textures[0];
  13561. if (onLoad) {
  13562. onLoad(texture);
  13563. }
  13564. };
  13565. return this.createCubeTexture(rootUrl, scene, null, false, callback, onError, format, forcedExtension);
  13566. };
  13567. Engine.prototype.createCubeTexture = function (rootUrl, scene, files, noMipmap, onLoad, onError, format, forcedExtension) {
  13568. var _this = this;
  13569. if (onLoad === void 0) { onLoad = null; }
  13570. if (onError === void 0) { onError = null; }
  13571. if (forcedExtension === void 0) { forcedExtension = null; }
  13572. var gl = this._gl;
  13573. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_CUBE);
  13574. texture.isCube = true;
  13575. texture.url = rootUrl;
  13576. texture.generateMipMaps = !noMipmap;
  13577. if (!this._doNotHandleContextLost) {
  13578. texture._extension = forcedExtension;
  13579. texture._files = files;
  13580. }
  13581. var isKTX = false;
  13582. var isDDS = false;
  13583. var lastDot = rootUrl.lastIndexOf('.');
  13584. var extension = forcedExtension ? forcedExtension : (lastDot > -1 ? rootUrl.substring(lastDot).toLowerCase() : "");
  13585. if (this._textureFormatInUse) {
  13586. extension = this._textureFormatInUse;
  13587. rootUrl = (lastDot > -1 ? rootUrl.substring(0, lastDot) : rootUrl) + this._textureFormatInUse;
  13588. isKTX = true;
  13589. }
  13590. else {
  13591. isDDS = (extension === ".dds");
  13592. }
  13593. var onerror = function (request, exception) {
  13594. if (onError && request) {
  13595. onError(request.status + " " + request.statusText, exception);
  13596. }
  13597. };
  13598. if (isKTX) {
  13599. this._loadFile(rootUrl, function (data) {
  13600. var ktx = new BABYLON.KhronosTextureContainer(data, 6);
  13601. var loadMipmap = ktx.numberOfMipmapLevels > 1 && !noMipmap;
  13602. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  13603. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 1);
  13604. ktx.uploadLevels(_this._gl, !noMipmap);
  13605. _this.setCubeMapTextureParams(gl, loadMipmap);
  13606. texture.width = ktx.pixelWidth;
  13607. texture.height = ktx.pixelHeight;
  13608. texture.isReady = true;
  13609. }, undefined, undefined, true, onerror);
  13610. }
  13611. else if (isDDS) {
  13612. if (files && files.length === 6) {
  13613. this._cascadeLoadFiles(rootUrl, scene, function (imgs) {
  13614. var info;
  13615. var loadMipmap = false;
  13616. var width = 0;
  13617. for (var index = 0; index < imgs.length; index++) {
  13618. var data = imgs[index];
  13619. info = BABYLON.DDSTools.GetDDSInfo(data);
  13620. loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap;
  13621. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  13622. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, info.isCompressed ? 1 : 0);
  13623. BABYLON.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, loadMipmap, 6, -1, index);
  13624. if (!noMipmap && !info.isFourCC && info.mipmapCount === 1) {
  13625. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  13626. }
  13627. texture.width = info.width;
  13628. texture.height = info.height;
  13629. texture.type = info.textureType;
  13630. width = info.width;
  13631. }
  13632. _this.setCubeMapTextureParams(gl, loadMipmap);
  13633. texture.isReady = true;
  13634. if (onLoad) {
  13635. onLoad({ isDDS: true, width: width, info: info, imgs: imgs, texture: texture });
  13636. }
  13637. }, files, onError);
  13638. }
  13639. else {
  13640. this._loadFile(rootUrl, function (data) {
  13641. var info = BABYLON.DDSTools.GetDDSInfo(data);
  13642. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap;
  13643. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  13644. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, info.isCompressed ? 1 : 0);
  13645. BABYLON.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, loadMipmap, 6);
  13646. if (!noMipmap && !info.isFourCC && info.mipmapCount === 1) {
  13647. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  13648. }
  13649. _this.setCubeMapTextureParams(gl, loadMipmap);
  13650. texture.width = info.width;
  13651. texture.height = info.height;
  13652. texture.isReady = true;
  13653. texture.type = info.textureType;
  13654. if (onLoad) {
  13655. onLoad({ isDDS: true, width: info.width, info: info, data: data, texture: texture });
  13656. }
  13657. }, undefined, undefined, true, onerror);
  13658. }
  13659. }
  13660. else {
  13661. if (!files) {
  13662. throw new Error("Cannot load cubemap because files were not defined");
  13663. }
  13664. cascadeLoadImgs(rootUrl, scene, function (imgs) {
  13665. var width = _this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(imgs[0].width, _this._caps.maxCubemapTextureSize) : imgs[0].width;
  13666. var height = width;
  13667. _this._prepareWorkingCanvas();
  13668. if (!_this._workingCanvas || !_this._workingContext) {
  13669. return;
  13670. }
  13671. _this._workingCanvas.width = width;
  13672. _this._workingCanvas.height = height;
  13673. var faces = [
  13674. gl.TEXTURE_CUBE_MAP_POSITIVE_X, gl.TEXTURE_CUBE_MAP_POSITIVE_Y, gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
  13675. gl.TEXTURE_CUBE_MAP_NEGATIVE_X, gl.TEXTURE_CUBE_MAP_NEGATIVE_Y, gl.TEXTURE_CUBE_MAP_NEGATIVE_Z
  13676. ];
  13677. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  13678. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  13679. var internalFormat = format ? _this._getInternalFormat(format) : _this._gl.RGBA;
  13680. for (var index = 0; index < faces.length; index++) {
  13681. _this._workingContext.drawImage(imgs[index], 0, 0, imgs[index].width, imgs[index].height, 0, 0, width, height);
  13682. gl.texImage2D(faces[index], 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, _this._workingCanvas);
  13683. }
  13684. if (!noMipmap) {
  13685. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  13686. }
  13687. _this.setCubeMapTextureParams(gl, !noMipmap);
  13688. texture.width = width;
  13689. texture.height = height;
  13690. texture.isReady = true;
  13691. if (format) {
  13692. texture.format = format;
  13693. }
  13694. texture.onLoadedObservable.notifyObservers(texture);
  13695. texture.onLoadedObservable.clear();
  13696. if (onLoad) {
  13697. onLoad();
  13698. }
  13699. }, files, onError);
  13700. }
  13701. this._internalTexturesCache.push(texture);
  13702. return texture;
  13703. };
  13704. Engine.prototype.setCubeMapTextureParams = function (gl, loadMipmap) {
  13705. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  13706. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, loadMipmap ? gl.LINEAR_MIPMAP_LINEAR : gl.LINEAR);
  13707. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  13708. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  13709. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  13710. // this.resetTextureCache();
  13711. };
  13712. Engine.prototype.updateRawCubeTexture = function (texture, data, format, type, invertY, compression, level) {
  13713. if (compression === void 0) { compression = null; }
  13714. if (level === void 0) { level = 0; }
  13715. texture._bufferViewArray = data;
  13716. texture.format = format;
  13717. texture.type = type;
  13718. texture.invertY = invertY;
  13719. texture._compression = compression;
  13720. var gl = this._gl;
  13721. var textureType = this._getWebGLTextureType(type);
  13722. var internalFormat = this._getInternalFormat(format);
  13723. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(type);
  13724. var needConversion = false;
  13725. if (internalFormat === gl.RGB) {
  13726. internalFormat = gl.RGBA;
  13727. needConversion = true;
  13728. }
  13729. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  13730. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  13731. if (texture.width % 4 !== 0) {
  13732. gl.pixelStorei(gl.UNPACK_ALIGNMENT, 1);
  13733. }
  13734. // Data are known to be in +X +Y +Z -X -Y -Z
  13735. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  13736. var faceData = data[faceIndex];
  13737. if (compression) {
  13738. gl.compressedTexImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, level, (this.getCaps().s3tc)[compression], texture.width, texture.height, 0, faceData);
  13739. }
  13740. else {
  13741. if (needConversion) {
  13742. faceData = this._convertRGBtoRGBATextureData(faceData, texture.width, texture.height, type);
  13743. }
  13744. gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, level, internalSizedFomat, texture.width, texture.height, 0, internalFormat, textureType, faceData);
  13745. }
  13746. }
  13747. var isPot = !this.needPOTTextures || (BABYLON.Tools.IsExponentOfTwo(texture.width) && BABYLON.Tools.IsExponentOfTwo(texture.height));
  13748. if (isPot && texture.generateMipMaps && level === 0) {
  13749. this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP);
  13750. }
  13751. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  13752. // this.resetTextureCache();
  13753. texture.isReady = true;
  13754. };
  13755. Engine.prototype.createRawCubeTexture = function (data, size, format, type, generateMipMaps, invertY, samplingMode, compression) {
  13756. if (compression === void 0) { compression = null; }
  13757. var gl = this._gl;
  13758. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_CUBERAW);
  13759. texture.isCube = true;
  13760. texture.generateMipMaps = generateMipMaps;
  13761. texture.format = format;
  13762. texture.type = type;
  13763. if (!this._doNotHandleContextLost) {
  13764. texture._bufferViewArray = data;
  13765. }
  13766. var textureType = this._getWebGLTextureType(type);
  13767. var internalFormat = this._getInternalFormat(format);
  13768. if (internalFormat === gl.RGB) {
  13769. internalFormat = gl.RGBA;
  13770. }
  13771. var width = size;
  13772. var height = width;
  13773. texture.width = width;
  13774. texture.height = height;
  13775. // Double check on POT to generate Mips.
  13776. var isPot = !this.needPOTTextures || (BABYLON.Tools.IsExponentOfTwo(texture.width) && BABYLON.Tools.IsExponentOfTwo(texture.height));
  13777. if (!isPot) {
  13778. generateMipMaps = false;
  13779. }
  13780. // Upload data if needed. The texture won't be ready until then.
  13781. if (data) {
  13782. this.updateRawCubeTexture(texture, data, format, type, invertY, compression);
  13783. }
  13784. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture, true);
  13785. // Filters
  13786. if (data && generateMipMaps) {
  13787. this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP);
  13788. }
  13789. if (textureType === gl.FLOAT && !this._caps.textureFloatLinearFiltering) {
  13790. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  13791. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  13792. }
  13793. else if (textureType === this._gl.HALF_FLOAT_OES && !this._caps.textureHalfFloatLinearFiltering) {
  13794. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  13795. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  13796. }
  13797. else {
  13798. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  13799. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  13800. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  13801. }
  13802. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  13803. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  13804. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  13805. return texture;
  13806. };
  13807. Engine.prototype.createRawCubeTextureFromUrl = function (url, scene, size, format, type, noMipmap, callback, mipmmapGenerator, onLoad, onError, samplingMode, invertY) {
  13808. var _this = this;
  13809. if (onLoad === void 0) { onLoad = null; }
  13810. if (onError === void 0) { onError = null; }
  13811. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  13812. if (invertY === void 0) { invertY = false; }
  13813. var gl = this._gl;
  13814. var texture = this.createRawCubeTexture(null, size, format, type, !noMipmap, invertY, samplingMode);
  13815. scene._addPendingData(texture);
  13816. texture.url = url;
  13817. this._internalTexturesCache.push(texture);
  13818. var onerror = function (request, exception) {
  13819. scene._removePendingData(texture);
  13820. if (onError && request) {
  13821. onError(request.status + " " + request.statusText, exception);
  13822. }
  13823. };
  13824. var internalCallback = function (data) {
  13825. var width = texture.width;
  13826. var faceDataArrays = callback(data);
  13827. if (!faceDataArrays) {
  13828. return;
  13829. }
  13830. if (mipmmapGenerator) {
  13831. var textureType = _this._getWebGLTextureType(type);
  13832. var internalFormat = _this._getInternalFormat(format);
  13833. var internalSizedFomat = _this._getRGBABufferInternalSizedFormat(type);
  13834. var needConversion = false;
  13835. if (internalFormat === gl.RGB) {
  13836. internalFormat = gl.RGBA;
  13837. needConversion = true;
  13838. }
  13839. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  13840. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  13841. var mipData = mipmmapGenerator(faceDataArrays);
  13842. for (var level = 0; level < mipData.length; level++) {
  13843. var mipSize = width >> level;
  13844. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  13845. var mipFaceData = mipData[level][faceIndex];
  13846. if (needConversion) {
  13847. mipFaceData = _this._convertRGBtoRGBATextureData(mipFaceData, mipSize, mipSize, type);
  13848. }
  13849. gl.texImage2D(faceIndex, level, internalSizedFomat, mipSize, mipSize, 0, internalFormat, textureType, mipFaceData);
  13850. }
  13851. }
  13852. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  13853. }
  13854. else {
  13855. texture.generateMipMaps = !noMipmap;
  13856. _this.updateRawCubeTexture(texture, faceDataArrays, format, type, invertY);
  13857. }
  13858. texture.isReady = true;
  13859. // this.resetTextureCache();
  13860. scene._removePendingData(texture);
  13861. if (onLoad) {
  13862. onLoad();
  13863. }
  13864. };
  13865. this._loadFile(url, function (data) {
  13866. internalCallback(data);
  13867. }, undefined, scene.database, true, onerror);
  13868. return texture;
  13869. };
  13870. ;
  13871. Engine.prototype.updateRawTexture3D = function (texture, data, format, invertY, compression) {
  13872. if (compression === void 0) { compression = null; }
  13873. var internalFormat = this._getInternalFormat(format);
  13874. this._bindTextureDirectly(this._gl.TEXTURE_3D, texture, true);
  13875. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  13876. if (!this._doNotHandleContextLost) {
  13877. texture._bufferView = data;
  13878. texture.format = format;
  13879. texture.invertY = invertY;
  13880. texture._compression = compression;
  13881. }
  13882. if (texture.width % 4 !== 0) {
  13883. this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT, 1);
  13884. }
  13885. if (compression && data) {
  13886. this._gl.compressedTexImage3D(this._gl.TEXTURE_3D, 0, this.getCaps().s3tc[compression], texture.width, texture.height, texture.depth, 0, data);
  13887. }
  13888. else {
  13889. this._gl.texImage3D(this._gl.TEXTURE_3D, 0, internalFormat, texture.width, texture.height, texture.depth, 0, internalFormat, this._gl.UNSIGNED_BYTE, data);
  13890. }
  13891. if (texture.generateMipMaps) {
  13892. this._gl.generateMipmap(this._gl.TEXTURE_3D);
  13893. }
  13894. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  13895. // this.resetTextureCache();
  13896. texture.isReady = true;
  13897. };
  13898. Engine.prototype.createRawTexture3D = function (data, width, height, depth, format, generateMipMaps, invertY, samplingMode, compression) {
  13899. if (compression === void 0) { compression = null; }
  13900. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RAW3D);
  13901. texture.baseWidth = width;
  13902. texture.baseHeight = height;
  13903. texture.baseDepth = depth;
  13904. texture.width = width;
  13905. texture.height = height;
  13906. texture.depth = depth;
  13907. texture.format = format;
  13908. texture.generateMipMaps = generateMipMaps;
  13909. texture.samplingMode = samplingMode;
  13910. texture.is3D = true;
  13911. if (!this._doNotHandleContextLost) {
  13912. texture._bufferView = data;
  13913. }
  13914. this.updateRawTexture3D(texture, data, format, invertY, compression);
  13915. this._bindTextureDirectly(this._gl.TEXTURE_3D, texture, true);
  13916. // Filters
  13917. var filters = getSamplingParameters(samplingMode, generateMipMaps, this._gl);
  13918. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  13919. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  13920. if (generateMipMaps) {
  13921. this._gl.generateMipmap(this._gl.TEXTURE_3D);
  13922. }
  13923. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  13924. this._internalTexturesCache.push(texture);
  13925. return texture;
  13926. };
  13927. Engine.prototype._prepareWebGLTextureContinuation = function (texture, scene, noMipmap, isCompressed, samplingMode) {
  13928. var gl = this._gl;
  13929. if (!gl) {
  13930. return;
  13931. }
  13932. var filters = getSamplingParameters(samplingMode, !noMipmap, gl);
  13933. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  13934. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  13935. if (!noMipmap && !isCompressed) {
  13936. gl.generateMipmap(gl.TEXTURE_2D);
  13937. }
  13938. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  13939. // this.resetTextureCache();
  13940. if (scene) {
  13941. scene._removePendingData(texture);
  13942. }
  13943. texture.onLoadedObservable.notifyObservers(texture);
  13944. texture.onLoadedObservable.clear();
  13945. };
  13946. Engine.prototype._prepareWebGLTexture = function (texture, scene, width, height, invertY, noMipmap, isCompressed, processFunction, samplingMode) {
  13947. var _this = this;
  13948. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  13949. var potWidth = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(width, this.getCaps().maxTextureSize) : width;
  13950. var potHeight = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(height, this.getCaps().maxTextureSize) : height;
  13951. var gl = this._gl;
  13952. if (!gl) {
  13953. return;
  13954. }
  13955. if (!texture._webGLTexture) {
  13956. // this.resetTextureCache();
  13957. if (scene) {
  13958. scene._removePendingData(texture);
  13959. }
  13960. return;
  13961. }
  13962. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  13963. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  13964. texture.baseWidth = width;
  13965. texture.baseHeight = height;
  13966. texture.width = potWidth;
  13967. texture.height = potHeight;
  13968. texture.isReady = true;
  13969. if (processFunction(potWidth, potHeight, function () {
  13970. _this._prepareWebGLTextureContinuation(texture, scene, noMipmap, isCompressed, samplingMode);
  13971. })) {
  13972. // Returning as texture needs extra async steps
  13973. return;
  13974. }
  13975. this._prepareWebGLTextureContinuation(texture, scene, noMipmap, isCompressed, samplingMode);
  13976. };
  13977. Engine.prototype._convertRGBtoRGBATextureData = function (rgbData, width, height, textureType) {
  13978. // Create new RGBA data container.
  13979. var rgbaData;
  13980. if (textureType === Engine.TEXTURETYPE_FLOAT) {
  13981. rgbaData = new Float32Array(width * height * 4);
  13982. }
  13983. else {
  13984. rgbaData = new Uint32Array(width * height * 4);
  13985. }
  13986. // Convert each pixel.
  13987. for (var x = 0; x < width; x++) {
  13988. for (var y = 0; y < height; y++) {
  13989. var index = (y * width + x) * 3;
  13990. var newIndex = (y * width + x) * 4;
  13991. // Map Old Value to new value.
  13992. rgbaData[newIndex + 0] = rgbData[index + 0];
  13993. rgbaData[newIndex + 1] = rgbData[index + 1];
  13994. rgbaData[newIndex + 2] = rgbData[index + 2];
  13995. // Add fully opaque alpha channel.
  13996. rgbaData[newIndex + 3] = 1;
  13997. }
  13998. }
  13999. return rgbaData;
  14000. };
  14001. Engine.prototype._releaseFramebufferObjects = function (texture) {
  14002. var gl = this._gl;
  14003. if (texture._framebuffer) {
  14004. gl.deleteFramebuffer(texture._framebuffer);
  14005. texture._framebuffer = null;
  14006. }
  14007. if (texture._depthStencilBuffer) {
  14008. gl.deleteRenderbuffer(texture._depthStencilBuffer);
  14009. texture._depthStencilBuffer = null;
  14010. }
  14011. if (texture._MSAAFramebuffer) {
  14012. gl.deleteFramebuffer(texture._MSAAFramebuffer);
  14013. texture._MSAAFramebuffer = null;
  14014. }
  14015. if (texture._MSAARenderBuffer) {
  14016. gl.deleteRenderbuffer(texture._MSAARenderBuffer);
  14017. texture._MSAARenderBuffer = null;
  14018. }
  14019. };
  14020. Engine.prototype._releaseTexture = function (texture) {
  14021. var gl = this._gl;
  14022. this._releaseFramebufferObjects(texture);
  14023. gl.deleteTexture(texture._webGLTexture);
  14024. // Unbind channels
  14025. this.unbindAllTextures();
  14026. var index = this._internalTexturesCache.indexOf(texture);
  14027. if (index !== -1) {
  14028. this._internalTexturesCache.splice(index, 1);
  14029. }
  14030. // Integrated fixed lod samplers.
  14031. if (texture._lodTextureHigh) {
  14032. texture._lodTextureHigh.dispose();
  14033. }
  14034. if (texture._lodTextureMid) {
  14035. texture._lodTextureMid.dispose();
  14036. }
  14037. if (texture._lodTextureLow) {
  14038. texture._lodTextureLow.dispose();
  14039. }
  14040. };
  14041. Engine.prototype.setProgram = function (program) {
  14042. if (this._currentProgram !== program) {
  14043. this._gl.useProgram(program);
  14044. this._currentProgram = program;
  14045. }
  14046. };
  14047. Engine.prototype.bindSamplers = function (effect) {
  14048. this.setProgram(effect.getProgram());
  14049. var samplers = effect.getSamplers();
  14050. for (var index = 0; index < samplers.length; index++) {
  14051. var uniform = effect.getUniform(samplers[index]);
  14052. if (uniform) {
  14053. this._boundUniforms[index] = uniform;
  14054. }
  14055. }
  14056. this._currentEffect = null;
  14057. };
  14058. Engine.prototype._moveBoundTextureOnTop = function (internalTexture) {
  14059. if (this.disableTextureBindingOptimization || this._lastBoundInternalTextureTracker.previous === internalTexture) {
  14060. return;
  14061. }
  14062. // Remove
  14063. this._linkTrackers(internalTexture.previous, internalTexture.next);
  14064. // Bind last to it
  14065. this._linkTrackers(this._lastBoundInternalTextureTracker.previous, internalTexture);
  14066. // Bind to dummy
  14067. this._linkTrackers(internalTexture, this._lastBoundInternalTextureTracker);
  14068. };
  14069. Engine.prototype._getCorrectTextureChannel = function (channel, internalTexture) {
  14070. if (!internalTexture) {
  14071. return -1;
  14072. }
  14073. internalTexture._initialSlot = channel;
  14074. if (this.disableTextureBindingOptimization) {
  14075. if (channel !== internalTexture._designatedSlot) {
  14076. this._textureCollisions.addCount(1, false);
  14077. }
  14078. }
  14079. else {
  14080. if (channel !== internalTexture._designatedSlot) {
  14081. if (internalTexture._designatedSlot > -1) {
  14082. return internalTexture._designatedSlot;
  14083. }
  14084. else {
  14085. // No slot for this texture, let's pick a new one (if we find a free slot)
  14086. if (this._nextFreeTextureSlots.length) {
  14087. return this._nextFreeTextureSlots[0];
  14088. }
  14089. // We need to recycle the oldest bound texture, sorry.
  14090. this._textureCollisions.addCount(1, false);
  14091. return this._removeDesignatedSlot(this._firstBoundInternalTextureTracker.next);
  14092. }
  14093. }
  14094. }
  14095. return channel;
  14096. };
  14097. Engine.prototype._linkTrackers = function (previous, next) {
  14098. previous.next = next;
  14099. next.previous = previous;
  14100. };
  14101. Engine.prototype._removeDesignatedSlot = function (internalTexture) {
  14102. var currentSlot = internalTexture._designatedSlot;
  14103. if (currentSlot === -1) {
  14104. return -1;
  14105. }
  14106. internalTexture._designatedSlot = -1;
  14107. if (this.disableTextureBindingOptimization) {
  14108. return -1;
  14109. }
  14110. // Remove from bound list
  14111. this._linkTrackers(internalTexture.previous, internalTexture.next);
  14112. // Free the slot
  14113. this._boundTexturesCache[currentSlot] = null;
  14114. this._nextFreeTextureSlots.push(currentSlot);
  14115. return currentSlot;
  14116. };
  14117. Engine.prototype._activateCurrentTexture = function () {
  14118. if (this._currentTextureChannel !== this._activeChannel) {
  14119. this._gl.activeTexture(this._gl.TEXTURE0 + this._activeChannel);
  14120. this._currentTextureChannel = this._activeChannel;
  14121. }
  14122. };
  14123. Engine.prototype._bindTextureDirectly = function (target, texture, forTextureDataUpdate) {
  14124. if (forTextureDataUpdate === void 0) { forTextureDataUpdate = false; }
  14125. if (forTextureDataUpdate && texture && texture._designatedSlot > -1) {
  14126. this._activeChannel = texture._designatedSlot;
  14127. }
  14128. var currentTextureBound = this._boundTexturesCache[this._activeChannel];
  14129. var isTextureForRendering = texture && texture._initialSlot > -1;
  14130. if (currentTextureBound !== texture) {
  14131. if (currentTextureBound) {
  14132. this._removeDesignatedSlot(currentTextureBound);
  14133. }
  14134. this._activateCurrentTexture();
  14135. this._gl.bindTexture(target, texture ? texture._webGLTexture : null);
  14136. this._boundTexturesCache[this._activeChannel] = texture;
  14137. if (texture) {
  14138. if (!this.disableTextureBindingOptimization) {
  14139. var slotIndex = this._nextFreeTextureSlots.indexOf(this._activeChannel);
  14140. if (slotIndex > -1) {
  14141. this._nextFreeTextureSlots.splice(slotIndex, 1);
  14142. }
  14143. this._linkTrackers(this._lastBoundInternalTextureTracker.previous, texture);
  14144. this._linkTrackers(texture, this._lastBoundInternalTextureTracker);
  14145. }
  14146. texture._designatedSlot = this._activeChannel;
  14147. }
  14148. }
  14149. else if (forTextureDataUpdate) {
  14150. this._activateCurrentTexture();
  14151. }
  14152. if (isTextureForRendering && !forTextureDataUpdate) {
  14153. this._bindSamplerUniformToChannel(texture._initialSlot, this._activeChannel);
  14154. }
  14155. };
  14156. Engine.prototype._bindTexture = function (channel, texture) {
  14157. if (channel < 0) {
  14158. return;
  14159. }
  14160. if (texture) {
  14161. channel = this._getCorrectTextureChannel(channel, texture);
  14162. }
  14163. this._activeChannel = channel;
  14164. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  14165. };
  14166. Engine.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  14167. this._bindTexture(channel, postProcess ? postProcess._textures.data[postProcess._currentRenderTextureInd] : null);
  14168. };
  14169. Engine.prototype.unbindAllTextures = function () {
  14170. for (var channel = 0; channel < this._maxSimultaneousTextures; channel++) {
  14171. this._activeChannel = channel;
  14172. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  14173. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  14174. if (this.webGLVersion > 1) {
  14175. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  14176. }
  14177. }
  14178. };
  14179. Engine.prototype.setTexture = function (channel, uniform, texture) {
  14180. if (channel < 0) {
  14181. return;
  14182. }
  14183. if (uniform) {
  14184. this._boundUniforms[channel] = uniform;
  14185. }
  14186. this._setTexture(channel, texture);
  14187. };
  14188. Engine.prototype._bindSamplerUniformToChannel = function (sourceSlot, destination) {
  14189. var uniform = this._boundUniforms[sourceSlot];
  14190. if (uniform._currentState === destination) {
  14191. return;
  14192. }
  14193. this._gl.uniform1i(uniform, destination);
  14194. uniform._currentState = destination;
  14195. };
  14196. Engine.prototype._setTexture = function (channel, texture, isPartOfTextureArray) {
  14197. if (isPartOfTextureArray === void 0) { isPartOfTextureArray = false; }
  14198. // Not ready?
  14199. if (!texture) {
  14200. if (this._boundTexturesCache[channel] != null) {
  14201. this._activeChannel = channel;
  14202. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  14203. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  14204. if (this.webGLVersion > 1) {
  14205. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  14206. }
  14207. }
  14208. return false;
  14209. }
  14210. // Video
  14211. if (texture.video) {
  14212. this._activeChannel = channel;
  14213. texture.update();
  14214. }
  14215. else if (texture.delayLoadState === Engine.DELAYLOADSTATE_NOTLOADED) {
  14216. texture.delayLoad();
  14217. return false;
  14218. }
  14219. var internalTexture;
  14220. if (texture.isReady()) {
  14221. internalTexture = texture.getInternalTexture();
  14222. }
  14223. else if (texture.isCube) {
  14224. internalTexture = this.emptyCubeTexture;
  14225. }
  14226. else if (texture.is3D) {
  14227. internalTexture = this.emptyTexture3D;
  14228. }
  14229. else {
  14230. internalTexture = this.emptyTexture;
  14231. }
  14232. if (!isPartOfTextureArray) {
  14233. channel = this._getCorrectTextureChannel(channel, internalTexture);
  14234. }
  14235. if (this._boundTexturesCache[channel] === internalTexture) {
  14236. this._moveBoundTextureOnTop(internalTexture);
  14237. if (!isPartOfTextureArray) {
  14238. this._bindSamplerUniformToChannel(internalTexture._initialSlot, channel);
  14239. }
  14240. return false;
  14241. }
  14242. this._activeChannel = channel;
  14243. if (internalTexture && internalTexture.is3D) {
  14244. this._bindTextureDirectly(this._gl.TEXTURE_3D, internalTexture, isPartOfTextureArray);
  14245. if (internalTexture && internalTexture._cachedWrapU !== texture.wrapU) {
  14246. internalTexture._cachedWrapU = texture.wrapU;
  14247. switch (texture.wrapU) {
  14248. case BABYLON.Texture.WRAP_ADDRESSMODE:
  14249. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_S, this._gl.REPEAT);
  14250. break;
  14251. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  14252. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_S, this._gl.CLAMP_TO_EDGE);
  14253. break;
  14254. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  14255. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_S, this._gl.MIRRORED_REPEAT);
  14256. break;
  14257. }
  14258. }
  14259. if (internalTexture && internalTexture._cachedWrapV !== texture.wrapV) {
  14260. internalTexture._cachedWrapV = texture.wrapV;
  14261. switch (texture.wrapV) {
  14262. case BABYLON.Texture.WRAP_ADDRESSMODE:
  14263. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_T, this._gl.REPEAT);
  14264. break;
  14265. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  14266. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_T, this._gl.CLAMP_TO_EDGE);
  14267. break;
  14268. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  14269. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_T, this._gl.MIRRORED_REPEAT);
  14270. break;
  14271. }
  14272. }
  14273. if (internalTexture && internalTexture._cachedWrapR !== texture.wrapR) {
  14274. internalTexture._cachedWrapR = texture.wrapR;
  14275. switch (texture.wrapR) {
  14276. case BABYLON.Texture.WRAP_ADDRESSMODE:
  14277. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_R, this._gl.REPEAT);
  14278. break;
  14279. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  14280. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_R, this._gl.CLAMP_TO_EDGE);
  14281. break;
  14282. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  14283. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_R, this._gl.MIRRORED_REPEAT);
  14284. break;
  14285. }
  14286. }
  14287. this._setAnisotropicLevel(this._gl.TEXTURE_3D, texture);
  14288. }
  14289. else if (internalTexture && internalTexture.isCube) {
  14290. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, internalTexture, isPartOfTextureArray);
  14291. if (internalTexture._cachedCoordinatesMode !== texture.coordinatesMode) {
  14292. internalTexture._cachedCoordinatesMode = texture.coordinatesMode;
  14293. // CUBIC_MODE and SKYBOX_MODE both require CLAMP_TO_EDGE. All other modes use REPEAT.
  14294. var textureWrapMode = (texture.coordinatesMode !== BABYLON.Texture.CUBIC_MODE && texture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) ? this._gl.REPEAT : this._gl.CLAMP_TO_EDGE;
  14295. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_S, textureWrapMode);
  14296. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_T, textureWrapMode);
  14297. }
  14298. this._setAnisotropicLevel(this._gl.TEXTURE_CUBE_MAP, texture);
  14299. }
  14300. else {
  14301. this._bindTextureDirectly(this._gl.TEXTURE_2D, internalTexture, isPartOfTextureArray);
  14302. if (internalTexture && internalTexture._cachedWrapU !== texture.wrapU) {
  14303. internalTexture._cachedWrapU = texture.wrapU;
  14304. switch (texture.wrapU) {
  14305. case BABYLON.Texture.WRAP_ADDRESSMODE:
  14306. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.REPEAT);
  14307. break;
  14308. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  14309. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.CLAMP_TO_EDGE);
  14310. break;
  14311. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  14312. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.MIRRORED_REPEAT);
  14313. break;
  14314. }
  14315. }
  14316. if (internalTexture && internalTexture._cachedWrapV !== texture.wrapV) {
  14317. internalTexture._cachedWrapV = texture.wrapV;
  14318. switch (texture.wrapV) {
  14319. case BABYLON.Texture.WRAP_ADDRESSMODE:
  14320. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.REPEAT);
  14321. break;
  14322. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  14323. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.CLAMP_TO_EDGE);
  14324. break;
  14325. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  14326. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.MIRRORED_REPEAT);
  14327. break;
  14328. }
  14329. }
  14330. this._setAnisotropicLevel(this._gl.TEXTURE_2D, texture);
  14331. }
  14332. return true;
  14333. };
  14334. Engine.prototype.setTextureArray = function (channel, uniform, textures) {
  14335. if (channel < 0 || !uniform) {
  14336. return;
  14337. }
  14338. if (!this._textureUnits || this._textureUnits.length !== textures.length) {
  14339. this._textureUnits = new Int32Array(textures.length);
  14340. }
  14341. for (var i = 0; i < textures.length; i++) {
  14342. this._textureUnits[i] = this._getCorrectTextureChannel(channel + i, textures[i].getInternalTexture());
  14343. }
  14344. this._gl.uniform1iv(uniform, this._textureUnits);
  14345. for (var index = 0; index < textures.length; index++) {
  14346. this._setTexture(this._textureUnits[index], textures[index], true);
  14347. }
  14348. };
  14349. Engine.prototype._setAnisotropicLevel = function (key, texture) {
  14350. var internalTexture = texture.getInternalTexture();
  14351. if (!internalTexture) {
  14352. return;
  14353. }
  14354. var anisotropicFilterExtension = this._caps.textureAnisotropicFilterExtension;
  14355. var value = texture.anisotropicFilteringLevel;
  14356. if (internalTexture.samplingMode !== BABYLON.Texture.LINEAR_LINEAR_MIPNEAREST
  14357. && internalTexture.samplingMode !== BABYLON.Texture.LINEAR_LINEAR_MIPLINEAR
  14358. && internalTexture.samplingMode !== BABYLON.Texture.LINEAR_LINEAR) {
  14359. value = 1; // Forcing the anisotropic to 1 because else webgl will force filters to linear
  14360. }
  14361. if (anisotropicFilterExtension && internalTexture._cachedAnisotropicFilteringLevel !== value) {
  14362. this._gl.texParameterf(key, anisotropicFilterExtension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min(value, this._caps.maxAnisotropy));
  14363. internalTexture._cachedAnisotropicFilteringLevel = value;
  14364. }
  14365. };
  14366. Engine.prototype.readPixels = function (x, y, width, height) {
  14367. var data = new Uint8Array(height * width * 4);
  14368. this._gl.readPixels(x, y, width, height, this._gl.RGBA, this._gl.UNSIGNED_BYTE, data);
  14369. return data;
  14370. };
  14371. /**
  14372. * Add an externaly attached data from its key.
  14373. * This method call will fail and return false, if such key already exists.
  14374. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  14375. * @param key the unique key that identifies the data
  14376. * @param data the data object to associate to the key for this Engine instance
  14377. * @return true if no such key were already present and the data was added successfully, false otherwise
  14378. */
  14379. Engine.prototype.addExternalData = function (key, data) {
  14380. if (!this._externalData) {
  14381. this._externalData = new BABYLON.StringDictionary();
  14382. }
  14383. return this._externalData.add(key, data);
  14384. };
  14385. /**
  14386. * Get an externaly attached data from its key
  14387. * @param key the unique key that identifies the data
  14388. * @return the associated data, if present (can be null), or undefined if not present
  14389. */
  14390. Engine.prototype.getExternalData = function (key) {
  14391. if (!this._externalData) {
  14392. this._externalData = new BABYLON.StringDictionary();
  14393. }
  14394. return this._externalData.get(key);
  14395. };
  14396. /**
  14397. * Get an externaly attached data from its key, create it using a factory if it's not already present
  14398. * @param key the unique key that identifies the data
  14399. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  14400. * @return the associated data, can be null if the factory returned null.
  14401. */
  14402. Engine.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  14403. if (!this._externalData) {
  14404. this._externalData = new BABYLON.StringDictionary();
  14405. }
  14406. return this._externalData.getOrAddWithFactory(key, factory);
  14407. };
  14408. /**
  14409. * Remove an externaly attached data from the Engine instance
  14410. * @param key the unique key that identifies the data
  14411. * @return true if the data was successfully removed, false if it doesn't exist
  14412. */
  14413. Engine.prototype.removeExternalData = function (key) {
  14414. if (!this._externalData) {
  14415. this._externalData = new BABYLON.StringDictionary();
  14416. }
  14417. return this._externalData.remove(key);
  14418. };
  14419. Engine.prototype.unbindAllAttributes = function () {
  14420. if (this._mustWipeVertexAttributes) {
  14421. this._mustWipeVertexAttributes = false;
  14422. for (var i = 0; i < this._caps.maxVertexAttribs; i++) {
  14423. this._gl.disableVertexAttribArray(i);
  14424. this._vertexAttribArraysEnabled[i] = false;
  14425. this._currentBufferPointers[i].active = false;
  14426. }
  14427. return;
  14428. }
  14429. for (var i = 0, ul = this._vertexAttribArraysEnabled.length; i < ul; i++) {
  14430. if (i >= this._caps.maxVertexAttribs || !this._vertexAttribArraysEnabled[i]) {
  14431. continue;
  14432. }
  14433. this._gl.disableVertexAttribArray(i);
  14434. this._vertexAttribArraysEnabled[i] = false;
  14435. this._currentBufferPointers[i].active = false;
  14436. }
  14437. };
  14438. Engine.prototype.releaseEffects = function () {
  14439. for (var name in this._compiledEffects) {
  14440. this._deleteProgram(this._compiledEffects[name]._program);
  14441. }
  14442. this._compiledEffects = {};
  14443. };
  14444. // Dispose
  14445. Engine.prototype.dispose = function () {
  14446. this.hideLoadingUI();
  14447. this.stopRenderLoop();
  14448. // Release postProcesses
  14449. while (this.postProcesses.length) {
  14450. this.postProcesses[0].dispose();
  14451. }
  14452. // Empty texture
  14453. if (this._emptyTexture) {
  14454. this._releaseTexture(this._emptyTexture);
  14455. this._emptyTexture = null;
  14456. }
  14457. if (this._emptyCubeTexture) {
  14458. this._releaseTexture(this._emptyCubeTexture);
  14459. this._emptyCubeTexture = null;
  14460. }
  14461. // Rescale PP
  14462. if (this._rescalePostProcess) {
  14463. this._rescalePostProcess.dispose();
  14464. }
  14465. // Release scenes
  14466. while (this.scenes.length) {
  14467. this.scenes[0].dispose();
  14468. }
  14469. // Release audio engine
  14470. if (Engine.audioEngine) {
  14471. Engine.audioEngine.dispose();
  14472. }
  14473. // Release effects
  14474. this.releaseEffects();
  14475. // Unbind
  14476. this.unbindAllAttributes();
  14477. if (this._dummyFramebuffer) {
  14478. this._gl.deleteFramebuffer(this._dummyFramebuffer);
  14479. }
  14480. //WebVR
  14481. this.disableVR();
  14482. // Events
  14483. if (BABYLON.Tools.IsWindowObjectExist()) {
  14484. window.removeEventListener("blur", this._onBlur);
  14485. window.removeEventListener("focus", this._onFocus);
  14486. window.removeEventListener('vrdisplaypointerrestricted', this._onVRDisplayPointerRestricted);
  14487. window.removeEventListener('vrdisplaypointerunrestricted', this._onVRDisplayPointerUnrestricted);
  14488. if (this._renderingCanvas) {
  14489. this._renderingCanvas.removeEventListener("focus", this._onCanvasFocus);
  14490. this._renderingCanvas.removeEventListener("blur", this._onCanvasBlur);
  14491. this._renderingCanvas.removeEventListener("pointerout", this._onCanvasBlur);
  14492. if (!this._doNotHandleContextLost) {
  14493. this._renderingCanvas.removeEventListener("webglcontextlost", this._onContextLost);
  14494. this._renderingCanvas.removeEventListener("webglcontextrestored", this._onContextRestored);
  14495. }
  14496. }
  14497. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  14498. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  14499. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  14500. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  14501. document.removeEventListener("pointerlockchange", this._onPointerLockChange);
  14502. document.removeEventListener("mspointerlockchange", this._onPointerLockChange);
  14503. document.removeEventListener("mozpointerlockchange", this._onPointerLockChange);
  14504. document.removeEventListener("webkitpointerlockchange", this._onPointerLockChange);
  14505. if (this._onVrDisplayConnect) {
  14506. window.removeEventListener('vrdisplayconnect', this._onVrDisplayConnect);
  14507. if (this._onVrDisplayDisconnect) {
  14508. window.removeEventListener('vrdisplaydisconnect', this._onVrDisplayDisconnect);
  14509. }
  14510. if (this._onVrDisplayPresentChange) {
  14511. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  14512. }
  14513. this._onVrDisplayConnect = null;
  14514. this._onVrDisplayDisconnect = null;
  14515. }
  14516. }
  14517. // Remove from Instances
  14518. var index = Engine.Instances.indexOf(this);
  14519. if (index >= 0) {
  14520. Engine.Instances.splice(index, 1);
  14521. }
  14522. this._workingCanvas = null;
  14523. this._workingContext = null;
  14524. this._currentBufferPointers = [];
  14525. this._renderingCanvas = null;
  14526. this._currentProgram = null;
  14527. this.onResizeObservable.clear();
  14528. this.onCanvasBlurObservable.clear();
  14529. this.onCanvasFocusObservable.clear();
  14530. this.onCanvasPointerOutObservable.clear();
  14531. this.onBeginFrameObservable.clear();
  14532. this.onEndFrameObservable.clear();
  14533. BABYLON.Effect.ResetCache();
  14534. // Abort active requests
  14535. for (var _i = 0, _a = this._activeRequests; _i < _a.length; _i++) {
  14536. var request = _a[_i];
  14537. request.abort();
  14538. }
  14539. };
  14540. // Loading screen
  14541. Engine.prototype.displayLoadingUI = function () {
  14542. if (!BABYLON.Tools.IsWindowObjectExist()) {
  14543. return;
  14544. }
  14545. var loadingScreen = this.loadingScreen;
  14546. if (loadingScreen) {
  14547. loadingScreen.displayLoadingUI();
  14548. }
  14549. };
  14550. Engine.prototype.hideLoadingUI = function () {
  14551. if (!BABYLON.Tools.IsWindowObjectExist()) {
  14552. return;
  14553. }
  14554. var loadingScreen = this.loadingScreen;
  14555. if (loadingScreen) {
  14556. loadingScreen.hideLoadingUI();
  14557. }
  14558. };
  14559. Object.defineProperty(Engine.prototype, "loadingScreen", {
  14560. get: function () {
  14561. if (!this._loadingScreen && BABYLON.DefaultLoadingScreen && this._renderingCanvas)
  14562. this._loadingScreen = new BABYLON.DefaultLoadingScreen(this._renderingCanvas);
  14563. return this._loadingScreen;
  14564. },
  14565. set: function (loadingScreen) {
  14566. this._loadingScreen = loadingScreen;
  14567. },
  14568. enumerable: true,
  14569. configurable: true
  14570. });
  14571. Object.defineProperty(Engine.prototype, "loadingUIText", {
  14572. set: function (text) {
  14573. this.loadingScreen.loadingUIText = text;
  14574. },
  14575. enumerable: true,
  14576. configurable: true
  14577. });
  14578. Object.defineProperty(Engine.prototype, "loadingUIBackgroundColor", {
  14579. set: function (color) {
  14580. this.loadingScreen.loadingUIBackgroundColor = color;
  14581. },
  14582. enumerable: true,
  14583. configurable: true
  14584. });
  14585. Engine.prototype.attachContextLostEvent = function (callback) {
  14586. if (this._renderingCanvas) {
  14587. this._renderingCanvas.addEventListener("webglcontextlost", callback, false);
  14588. }
  14589. };
  14590. Engine.prototype.attachContextRestoredEvent = function (callback) {
  14591. if (this._renderingCanvas) {
  14592. this._renderingCanvas.addEventListener("webglcontextrestored", callback, false);
  14593. }
  14594. };
  14595. Engine.prototype.getVertexShaderSource = function (program) {
  14596. var shaders = this._gl.getAttachedShaders(program);
  14597. if (!shaders) {
  14598. return null;
  14599. }
  14600. return this._gl.getShaderSource(shaders[0]);
  14601. };
  14602. Engine.prototype.getFragmentShaderSource = function (program) {
  14603. var shaders = this._gl.getAttachedShaders(program);
  14604. if (!shaders) {
  14605. return null;
  14606. }
  14607. return this._gl.getShaderSource(shaders[1]);
  14608. };
  14609. Engine.prototype.getError = function () {
  14610. return this._gl.getError();
  14611. };
  14612. // FPS
  14613. Engine.prototype.getFps = function () {
  14614. return this._fps;
  14615. };
  14616. Engine.prototype.getDeltaTime = function () {
  14617. return this._deltaTime;
  14618. };
  14619. Engine.prototype._measureFps = function () {
  14620. this._performanceMonitor.sampleFrame();
  14621. this._fps = this._performanceMonitor.averageFPS;
  14622. this._deltaTime = this._performanceMonitor.instantaneousFrameTime || 0;
  14623. };
  14624. Engine.prototype._readTexturePixels = function (texture, width, height, faceIndex) {
  14625. if (faceIndex === void 0) { faceIndex = -1; }
  14626. var gl = this._gl;
  14627. if (!this._dummyFramebuffer) {
  14628. var dummy = gl.createFramebuffer();
  14629. if (!dummy) {
  14630. throw new Error("Unable to create dummy framebuffer");
  14631. }
  14632. this._dummyFramebuffer = dummy;
  14633. }
  14634. gl.bindFramebuffer(gl.FRAMEBUFFER, this._dummyFramebuffer);
  14635. if (faceIndex > -1) {
  14636. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture._webGLTexture, 0);
  14637. }
  14638. else {
  14639. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture._webGLTexture, 0);
  14640. }
  14641. var readType = (texture.type !== undefined) ? this._getWebGLTextureType(texture.type) : gl.UNSIGNED_BYTE;
  14642. var buffer;
  14643. switch (readType) {
  14644. case gl.UNSIGNED_BYTE:
  14645. buffer = new Uint8Array(4 * width * height);
  14646. readType = gl.UNSIGNED_BYTE;
  14647. break;
  14648. default:
  14649. buffer = new Float32Array(4 * width * height);
  14650. readType = gl.FLOAT;
  14651. break;
  14652. }
  14653. gl.readPixels(0, 0, width, height, gl.RGBA, readType, buffer);
  14654. gl.bindFramebuffer(gl.FRAMEBUFFER, this._currentFramebuffer);
  14655. return buffer;
  14656. };
  14657. Engine.prototype._canRenderToFloatFramebuffer = function () {
  14658. if (this._webGLVersion > 1) {
  14659. return this._caps.colorBufferFloat;
  14660. }
  14661. return this._canRenderToFramebuffer(Engine.TEXTURETYPE_FLOAT);
  14662. };
  14663. Engine.prototype._canRenderToHalfFloatFramebuffer = function () {
  14664. if (this._webGLVersion > 1) {
  14665. return this._caps.colorBufferFloat;
  14666. }
  14667. return this._canRenderToFramebuffer(Engine.TEXTURETYPE_HALF_FLOAT);
  14668. };
  14669. // Thank you : http://stackoverflow.com/questions/28827511/webgl-ios-render-to-floating-point-texture
  14670. Engine.prototype._canRenderToFramebuffer = function (type) {
  14671. var gl = this._gl;
  14672. //clear existing errors
  14673. while (gl.getError() !== gl.NO_ERROR) { }
  14674. var successful = true;
  14675. var texture = gl.createTexture();
  14676. gl.bindTexture(gl.TEXTURE_2D, texture);
  14677. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), 1, 1, 0, gl.RGBA, this._getWebGLTextureType(type), null);
  14678. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  14679. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  14680. var fb = gl.createFramebuffer();
  14681. gl.bindFramebuffer(gl.FRAMEBUFFER, fb);
  14682. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);
  14683. var status = gl.checkFramebufferStatus(gl.FRAMEBUFFER);
  14684. successful = successful && (status === gl.FRAMEBUFFER_COMPLETE);
  14685. successful = successful && (gl.getError() === gl.NO_ERROR);
  14686. //try render by clearing frame buffer's color buffer
  14687. if (successful) {
  14688. gl.clear(gl.COLOR_BUFFER_BIT);
  14689. successful = successful && (gl.getError() === gl.NO_ERROR);
  14690. }
  14691. //try reading from frame to ensure render occurs (just creating the FBO is not sufficient to determine if rendering is supported)
  14692. if (successful) {
  14693. //in practice it's sufficient to just read from the backbuffer rather than handle potentially issues reading from the texture
  14694. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  14695. var readFormat = gl.RGBA;
  14696. var readType = gl.UNSIGNED_BYTE;
  14697. var buffer = new Uint8Array(4);
  14698. gl.readPixels(0, 0, 1, 1, readFormat, readType, buffer);
  14699. successful = successful && (gl.getError() === gl.NO_ERROR);
  14700. }
  14701. //clean up
  14702. gl.deleteTexture(texture);
  14703. gl.deleteFramebuffer(fb);
  14704. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  14705. //clear accumulated errors
  14706. while (!successful && (gl.getError() !== gl.NO_ERROR)) { }
  14707. return successful;
  14708. };
  14709. Engine.prototype._getWebGLTextureType = function (type) {
  14710. if (type === Engine.TEXTURETYPE_FLOAT) {
  14711. return this._gl.FLOAT;
  14712. }
  14713. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  14714. // Add Half Float Constant.
  14715. return this._gl.HALF_FLOAT_OES;
  14716. }
  14717. return this._gl.UNSIGNED_BYTE;
  14718. };
  14719. ;
  14720. /** @ignore */
  14721. Engine.prototype._getRGBABufferInternalSizedFormat = function (type, format) {
  14722. if (this._webGLVersion === 1) {
  14723. return this._gl.RGBA;
  14724. }
  14725. if (type === Engine.TEXTURETYPE_FLOAT) {
  14726. if (format) {
  14727. switch (format) {
  14728. case Engine.TEXTUREFORMAT_R32F:
  14729. return this._gl.R32F;
  14730. case Engine.TEXTUREFORMAT_RG32F:
  14731. return this._gl.RG32F;
  14732. case Engine.TEXTUREFORMAT_RGB32F:
  14733. return this._gl.RGB32F;
  14734. }
  14735. }
  14736. return this._gl.RGBA32F;
  14737. }
  14738. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  14739. return this._gl.RGBA16F;
  14740. }
  14741. return this._gl.RGBA;
  14742. };
  14743. ;
  14744. Engine.prototype._getRGBAMultiSampleBufferFormat = function (type) {
  14745. if (type === Engine.TEXTURETYPE_FLOAT) {
  14746. return this._gl.RGBA32F;
  14747. }
  14748. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  14749. return this._gl.RGBA16F;
  14750. }
  14751. return this._gl.RGBA8;
  14752. };
  14753. ;
  14754. Engine.prototype.createQuery = function () {
  14755. return this._gl.createQuery();
  14756. };
  14757. Engine.prototype.deleteQuery = function (query) {
  14758. this._gl.deleteQuery(query);
  14759. return this;
  14760. };
  14761. Engine.prototype.isQueryResultAvailable = function (query) {
  14762. return this._gl.getQueryParameter(query, this._gl.QUERY_RESULT_AVAILABLE);
  14763. };
  14764. Engine.prototype.getQueryResult = function (query) {
  14765. return this._gl.getQueryParameter(query, this._gl.QUERY_RESULT);
  14766. };
  14767. Engine.prototype.beginOcclusionQuery = function (algorithmType, query) {
  14768. var glAlgorithm = this.getGlAlgorithmType(algorithmType);
  14769. this._gl.beginQuery(glAlgorithm, query);
  14770. return this;
  14771. };
  14772. Engine.prototype.endOcclusionQuery = function (algorithmType) {
  14773. var glAlgorithm = this.getGlAlgorithmType(algorithmType);
  14774. this._gl.endQuery(glAlgorithm);
  14775. return this;
  14776. };
  14777. /* Time queries */
  14778. Engine.prototype._createTimeQuery = function () {
  14779. var timerQuery = this._caps.timerQuery;
  14780. if (timerQuery.createQueryEXT) {
  14781. return timerQuery.createQueryEXT();
  14782. }
  14783. return this.createQuery();
  14784. };
  14785. Engine.prototype._deleteTimeQuery = function (query) {
  14786. var timerQuery = this._caps.timerQuery;
  14787. if (timerQuery.deleteQueryEXT) {
  14788. timerQuery.deleteQueryEXT(query);
  14789. return;
  14790. }
  14791. this.deleteQuery(query);
  14792. };
  14793. Engine.prototype._getTimeQueryResult = function (query) {
  14794. var timerQuery = this._caps.timerQuery;
  14795. if (timerQuery.getQueryObjectEXT) {
  14796. return timerQuery.getQueryObjectEXT(query, timerQuery.QUERY_RESULT_EXT);
  14797. }
  14798. return this.getQueryResult(query);
  14799. };
  14800. Engine.prototype._getTimeQueryAvailability = function (query) {
  14801. var timerQuery = this._caps.timerQuery;
  14802. if (timerQuery.getQueryObjectEXT) {
  14803. return timerQuery.getQueryObjectEXT(query, timerQuery.QUERY_RESULT_AVAILABLE_EXT);
  14804. }
  14805. return this.isQueryResultAvailable(query);
  14806. };
  14807. Engine.prototype.startTimeQuery = function () {
  14808. var timerQuery = this._caps.timerQuery;
  14809. if (!timerQuery) {
  14810. return null;
  14811. }
  14812. var token = new BABYLON._TimeToken();
  14813. this._gl.getParameter(timerQuery.GPU_DISJOINT_EXT);
  14814. if (this._caps.canUseTimestampForTimerQuery) {
  14815. token._startTimeQuery = this._createTimeQuery();
  14816. timerQuery.queryCounterEXT(token._startTimeQuery, timerQuery.TIMESTAMP_EXT);
  14817. }
  14818. else {
  14819. if (this._currentNonTimestampToken) {
  14820. return this._currentNonTimestampToken;
  14821. }
  14822. token._timeElapsedQuery = this._createTimeQuery();
  14823. if (timerQuery.beginQueryEXT) {
  14824. timerQuery.beginQueryEXT(timerQuery.TIME_ELAPSED_EXT, token._timeElapsedQuery);
  14825. }
  14826. else {
  14827. this._gl.beginQuery(timerQuery.TIME_ELAPSED_EXT, token._timeElapsedQuery);
  14828. }
  14829. this._currentNonTimestampToken = token;
  14830. }
  14831. return token;
  14832. };
  14833. Engine.prototype.endTimeQuery = function (token) {
  14834. var timerQuery = this._caps.timerQuery;
  14835. if (!timerQuery || !token) {
  14836. return -1;
  14837. }
  14838. if (this._caps.canUseTimestampForTimerQuery) {
  14839. if (!token._startTimeQuery) {
  14840. return -1;
  14841. }
  14842. if (!token._endTimeQuery) {
  14843. token._endTimeQuery = this._createTimeQuery();
  14844. timerQuery.queryCounterEXT(token._endTimeQuery, timerQuery.TIMESTAMP_EXT);
  14845. }
  14846. }
  14847. else if (!token._timeElapsedQueryEnded) {
  14848. if (!token._timeElapsedQuery) {
  14849. return -1;
  14850. }
  14851. if (timerQuery.endQueryEXT) {
  14852. timerQuery.endQueryEXT(timerQuery.TIME_ELAPSED_EXT);
  14853. }
  14854. else {
  14855. this._gl.endQuery(timerQuery.TIME_ELAPSED_EXT);
  14856. }
  14857. token._timeElapsedQueryEnded = true;
  14858. }
  14859. var disjoint = this._gl.getParameter(timerQuery.GPU_DISJOINT_EXT);
  14860. var available = false;
  14861. if (token._endTimeQuery) {
  14862. available = this._getTimeQueryAvailability(token._endTimeQuery);
  14863. }
  14864. else if (token._timeElapsedQuery) {
  14865. available = this._getTimeQueryAvailability(token._timeElapsedQuery);
  14866. }
  14867. if (available && !disjoint) {
  14868. var result = 0;
  14869. if (this._caps.canUseTimestampForTimerQuery) {
  14870. if (!token._startTimeQuery || !token._endTimeQuery) {
  14871. return -1;
  14872. }
  14873. var timeStart = this._getTimeQueryResult(token._startTimeQuery);
  14874. var timeEnd = this._getTimeQueryResult(token._endTimeQuery);
  14875. result = timeEnd - timeStart;
  14876. this._deleteTimeQuery(token._startTimeQuery);
  14877. this._deleteTimeQuery(token._endTimeQuery);
  14878. token._startTimeQuery = null;
  14879. token._endTimeQuery = null;
  14880. }
  14881. else {
  14882. if (!token._timeElapsedQuery) {
  14883. return -1;
  14884. }
  14885. result = this._getTimeQueryResult(token._timeElapsedQuery);
  14886. this._deleteTimeQuery(token._timeElapsedQuery);
  14887. token._timeElapsedQuery = null;
  14888. token._timeElapsedQueryEnded = false;
  14889. this._currentNonTimestampToken = null;
  14890. }
  14891. return result;
  14892. }
  14893. return -1;
  14894. };
  14895. Engine.prototype.getGlAlgorithmType = function (algorithmType) {
  14896. return algorithmType === BABYLON.AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE ? this._gl.ANY_SAMPLES_PASSED_CONSERVATIVE : this._gl.ANY_SAMPLES_PASSED;
  14897. };
  14898. // Transform feedback
  14899. Engine.prototype.createTransformFeedback = function () {
  14900. return this._gl.createTransformFeedback();
  14901. };
  14902. Engine.prototype.deleteTransformFeedback = function (value) {
  14903. this._gl.deleteTransformFeedback(value);
  14904. };
  14905. Engine.prototype.bindTransformFeedback = function (value) {
  14906. this._gl.bindTransformFeedback(this._gl.TRANSFORM_FEEDBACK, value);
  14907. };
  14908. Engine.prototype.beginTransformFeedback = function (usePoints) {
  14909. if (usePoints === void 0) { usePoints = true; }
  14910. this._gl.beginTransformFeedback(usePoints ? this._gl.POINTS : this._gl.TRIANGLES);
  14911. };
  14912. Engine.prototype.endTransformFeedback = function () {
  14913. this._gl.endTransformFeedback();
  14914. };
  14915. Engine.prototype.setTranformFeedbackVaryings = function (program, value) {
  14916. this._gl.transformFeedbackVaryings(program, value, this._gl.INTERLEAVED_ATTRIBS);
  14917. };
  14918. Engine.prototype.bindTransformFeedbackBuffer = function (value) {
  14919. this._gl.bindBufferBase(this._gl.TRANSFORM_FEEDBACK_BUFFER, 0, value);
  14920. };
  14921. Engine.prototype._loadFile = function (url, onSuccess, onProgress, database, useArrayBuffer, onError) {
  14922. var _this = this;
  14923. var request = BABYLON.Tools.LoadFile(url, onSuccess, onProgress, database, useArrayBuffer, onError);
  14924. this._activeRequests.push(request);
  14925. request.onCompleteObservable.add(function (request) {
  14926. _this._activeRequests.splice(_this._activeRequests.indexOf(request), 1);
  14927. });
  14928. return request;
  14929. };
  14930. /** @ignore */
  14931. Engine.prototype._loadFileAsync = function (url, database, useArrayBuffer) {
  14932. var _this = this;
  14933. return new Promise(function (resolve, reject) {
  14934. _this._loadFile(url, function (data) {
  14935. resolve(data);
  14936. }, undefined, database, useArrayBuffer, function (request, exception) {
  14937. reject(exception);
  14938. });
  14939. });
  14940. };
  14941. Engine.prototype._partialLoadFile = function (url, index, loadedFiles, scene, onfinish, onErrorCallBack) {
  14942. if (onErrorCallBack === void 0) { onErrorCallBack = null; }
  14943. var onload = function (data) {
  14944. loadedFiles[index] = data;
  14945. loadedFiles._internalCount++;
  14946. if (loadedFiles._internalCount === 6) {
  14947. onfinish(loadedFiles);
  14948. }
  14949. };
  14950. var onerror = function (request, exception) {
  14951. if (onErrorCallBack && request) {
  14952. onErrorCallBack(request.status + " " + request.statusText, exception);
  14953. }
  14954. };
  14955. this._loadFile(url, onload, undefined, undefined, true, onerror);
  14956. };
  14957. Engine.prototype._cascadeLoadFiles = function (rootUrl, scene, onfinish, files, onError) {
  14958. if (onError === void 0) { onError = null; }
  14959. var loadedFiles = [];
  14960. loadedFiles._internalCount = 0;
  14961. for (var index = 0; index < 6; index++) {
  14962. this._partialLoadFile(files[index], index, loadedFiles, scene, onfinish, onError);
  14963. }
  14964. };
  14965. // Statics
  14966. Engine.isSupported = function () {
  14967. try {
  14968. var tempcanvas = document.createElement("canvas");
  14969. var gl = tempcanvas.getContext("webgl") || tempcanvas.getContext("experimental-webgl");
  14970. return gl != null && !!window.WebGLRenderingContext;
  14971. }
  14972. catch (e) {
  14973. return false;
  14974. }
  14975. };
  14976. /** Use this array to turn off some WebGL2 features on known buggy browsers version */
  14977. Engine.ExceptionList = [
  14978. { key: "Chrome/63.0", capture: "63\\.0\\.3239\\.(\\d+)", captureConstraint: 108, targets: ["uniformBuffer"] },
  14979. { key: "Firefox/58", capture: null, captureConstraint: null, targets: ["uniformBuffer"] },
  14980. { key: "Firefox/59", capture: null, captureConstraint: null, targets: ["uniformBuffer"] },
  14981. { key: "Macintosh", capture: null, captureConstraint: null, targets: ["textureBindingOptimization"] },
  14982. { key: "iPhone", capture: null, captureConstraint: null, targets: ["textureBindingOptimization"] },
  14983. ];
  14984. Engine.Instances = new Array();
  14985. // Const statics
  14986. Engine._ALPHA_DISABLE = 0;
  14987. Engine._ALPHA_ADD = 1;
  14988. Engine._ALPHA_COMBINE = 2;
  14989. Engine._ALPHA_SUBTRACT = 3;
  14990. Engine._ALPHA_MULTIPLY = 4;
  14991. Engine._ALPHA_MAXIMIZED = 5;
  14992. Engine._ALPHA_ONEONE = 6;
  14993. Engine._ALPHA_PREMULTIPLIED = 7;
  14994. Engine._ALPHA_PREMULTIPLIED_PORTERDUFF = 8;
  14995. Engine._ALPHA_INTERPOLATE = 9;
  14996. Engine._ALPHA_SCREENMODE = 10;
  14997. Engine._DELAYLOADSTATE_NONE = 0;
  14998. Engine._DELAYLOADSTATE_LOADED = 1;
  14999. Engine._DELAYLOADSTATE_LOADING = 2;
  15000. Engine._DELAYLOADSTATE_NOTLOADED = 4;
  15001. Engine._TEXTUREFORMAT_ALPHA = 0;
  15002. Engine._TEXTUREFORMAT_LUMINANCE = 1;
  15003. Engine._TEXTUREFORMAT_LUMINANCE_ALPHA = 2;
  15004. Engine._TEXTUREFORMAT_RGB = 4;
  15005. Engine._TEXTUREFORMAT_RGBA = 5;
  15006. Engine._TEXTUREFORMAT_R32F = 6;
  15007. Engine._TEXTUREFORMAT_RG32F = 7;
  15008. Engine._TEXTUREFORMAT_RGB32F = 8;
  15009. Engine._TEXTURETYPE_UNSIGNED_INT = 0;
  15010. Engine._TEXTURETYPE_FLOAT = 1;
  15011. Engine._TEXTURETYPE_HALF_FLOAT = 2;
  15012. // Depht or Stencil test Constants.
  15013. Engine._NEVER = 0x0200; // Passed to depthFunction or stencilFunction to specify depth or stencil tests will never pass. i.e. Nothing will be drawn.
  15014. Engine._ALWAYS = 0x0207; // Passed to depthFunction or stencilFunction to specify depth or stencil tests will always pass. i.e. Pixels will be drawn in the order they are drawn.
  15015. Engine._LESS = 0x0201; // Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is less than the stored value.
  15016. Engine._EQUAL = 0x0202; // Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is equals to the stored value.
  15017. Engine._LEQUAL = 0x0203; // Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is less than or equal to the stored value.
  15018. Engine._GREATER = 0x0204; // Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is greater than the stored value.
  15019. Engine._GEQUAL = 0x0206; // Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is greater than or equal to the stored value.
  15020. Engine._NOTEQUAL = 0x0205; // Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is not equal to the stored value.
  15021. // Stencil Actions Constants.
  15022. Engine._KEEP = 0x1E00;
  15023. Engine._REPLACE = 0x1E01;
  15024. Engine._INCR = 0x1E02;
  15025. Engine._DECR = 0x1E03;
  15026. Engine._INVERT = 0x150A;
  15027. Engine._INCR_WRAP = 0x8507;
  15028. Engine._DECR_WRAP = 0x8508;
  15029. // Texture rescaling mode
  15030. Engine._SCALEMODE_FLOOR = 1;
  15031. Engine._SCALEMODE_NEAREST = 2;
  15032. Engine._SCALEMODE_CEILING = 3;
  15033. // Updatable statics so stick with vars here
  15034. Engine.CollisionsEpsilon = 0.001;
  15035. Engine.CodeRepository = "src/";
  15036. Engine.ShadersRepository = "src/Shaders/";
  15037. return Engine;
  15038. }());
  15039. BABYLON.Engine = Engine;
  15040. })(BABYLON || (BABYLON = {}));
  15041. //# sourceMappingURL=babylon.engine.js.map
  15042. var BABYLON;
  15043. (function (BABYLON) {
  15044. /**
  15045. * Node is the basic class for all scene objects (Mesh, Light Camera).
  15046. */
  15047. var Node = /** @class */ (function () {
  15048. /**
  15049. * Creates a new Node
  15050. * @param {string} name - the name and id to be given to this node
  15051. * @param {BABYLON.Scene} the scene this node will be added to
  15052. */
  15053. function Node(name, scene) {
  15054. if (scene === void 0) { scene = null; }
  15055. /**
  15056. * Gets or sets a string used to store user defined state for the node
  15057. */
  15058. this.state = "";
  15059. /**
  15060. * Gets or sets an object used to store user defined information for the node
  15061. */
  15062. this.metadata = null;
  15063. /**
  15064. * Gets or sets a boolean used to define if the node must be serialized
  15065. */
  15066. this.doNotSerialize = false;
  15067. /** @ignore */
  15068. this._isDisposed = false;
  15069. /**
  15070. * Gets a list of {BABYLON.Animation} associated with the node
  15071. */
  15072. this.animations = new Array();
  15073. this._ranges = {};
  15074. this._isEnabled = true;
  15075. this._isReady = true;
  15076. /** @ignore */
  15077. this._currentRenderId = -1;
  15078. this._parentRenderId = -1;
  15079. /**
  15080. * An event triggered when the mesh is disposed
  15081. * @type {BABYLON.Observable}
  15082. */
  15083. this.onDisposeObservable = new BABYLON.Observable();
  15084. // Behaviors
  15085. this._behaviors = new Array();
  15086. this.name = name;
  15087. this.id = name;
  15088. this._scene = (scene || BABYLON.Engine.LastCreatedScene);
  15089. this.uniqueId = this._scene.getUniqueId();
  15090. this._initCache();
  15091. }
  15092. /**
  15093. * Gets a boolean indicating if the node has been disposed
  15094. * @returns true if the node was disposed
  15095. */
  15096. Node.prototype.isDisposed = function () {
  15097. return this._isDisposed;
  15098. };
  15099. Object.defineProperty(Node.prototype, "parent", {
  15100. get: function () {
  15101. return this._parentNode;
  15102. },
  15103. /**
  15104. * Gets or sets the parent of the node
  15105. */
  15106. set: function (parent) {
  15107. if (this._parentNode === parent) {
  15108. return;
  15109. }
  15110. // Remove self from list of children of parent
  15111. if (this._parentNode && this._parentNode._children !== undefined && this._parentNode._children !== null) {
  15112. var index = this._parentNode._children.indexOf(this);
  15113. if (index !== -1) {
  15114. this._parentNode._children.splice(index, 1);
  15115. }
  15116. }
  15117. // Store new parent
  15118. this._parentNode = parent;
  15119. // Add as child to new parent
  15120. if (this._parentNode) {
  15121. if (this._parentNode._children === undefined || this._parentNode._children === null) {
  15122. this._parentNode._children = new Array();
  15123. }
  15124. this._parentNode._children.push(this);
  15125. }
  15126. },
  15127. enumerable: true,
  15128. configurable: true
  15129. });
  15130. /**
  15131. * Gets a string idenfifying the name of the class
  15132. * @returns "Node" string
  15133. */
  15134. Node.prototype.getClassName = function () {
  15135. return "Node";
  15136. };
  15137. Object.defineProperty(Node.prototype, "onDispose", {
  15138. /**
  15139. * Sets a callback that will be raised when the node will be disposed
  15140. */
  15141. set: function (callback) {
  15142. if (this._onDisposeObserver) {
  15143. this.onDisposeObservable.remove(this._onDisposeObserver);
  15144. }
  15145. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  15146. },
  15147. enumerable: true,
  15148. configurable: true
  15149. });
  15150. /**
  15151. * Gets the scene of the node
  15152. * @returns a {BABYLON.Scene}
  15153. */
  15154. Node.prototype.getScene = function () {
  15155. return this._scene;
  15156. };
  15157. /**
  15158. * Gets the engine of the node
  15159. * @returns a {BABYLON.Engine}
  15160. */
  15161. Node.prototype.getEngine = function () {
  15162. return this._scene.getEngine();
  15163. };
  15164. /**
  15165. * Attach a behavior to the node
  15166. * @see http://doc.babylonjs.com/features/behaviour
  15167. * @param behavior defines the behavior to attach
  15168. * @returns the current Node
  15169. */
  15170. Node.prototype.addBehavior = function (behavior) {
  15171. var _this = this;
  15172. var index = this._behaviors.indexOf(behavior);
  15173. if (index !== -1) {
  15174. return this;
  15175. }
  15176. behavior.init();
  15177. if (this._scene.isLoading) {
  15178. // We defer the attach when the scene will be loaded
  15179. var observer = this._scene.onDataLoadedObservable.add(function () {
  15180. behavior.attach(_this);
  15181. setTimeout(function () {
  15182. // Need to use a timeout to avoid removing an observer while iterating the list of observers
  15183. _this._scene.onDataLoadedObservable.remove(observer);
  15184. }, 0);
  15185. });
  15186. }
  15187. else {
  15188. behavior.attach(this);
  15189. }
  15190. this._behaviors.push(behavior);
  15191. return this;
  15192. };
  15193. /**
  15194. * Remove an attached behavior
  15195. * @see http://doc.babylonjs.com/features/behaviour
  15196. * @param behavior defines the behavior to attach
  15197. * @returns the current Node
  15198. */
  15199. Node.prototype.removeBehavior = function (behavior) {
  15200. var index = this._behaviors.indexOf(behavior);
  15201. if (index === -1) {
  15202. return this;
  15203. }
  15204. this._behaviors[index].detach();
  15205. this._behaviors.splice(index, 1);
  15206. return this;
  15207. };
  15208. Object.defineProperty(Node.prototype, "behaviors", {
  15209. /**
  15210. * Gets the list of attached behaviors
  15211. * @see http://doc.babylonjs.com/features/behaviour
  15212. */
  15213. get: function () {
  15214. return this._behaviors;
  15215. },
  15216. enumerable: true,
  15217. configurable: true
  15218. });
  15219. /**
  15220. * Gets an attached behavior by name
  15221. * @param name defines the name of the behavior to look for
  15222. * @see http://doc.babylonjs.com/features/behaviour
  15223. * @returns null if behavior was not found else the requested behavior
  15224. */
  15225. Node.prototype.getBehaviorByName = function (name) {
  15226. for (var _i = 0, _a = this._behaviors; _i < _a.length; _i++) {
  15227. var behavior = _a[_i];
  15228. if (behavior.name === name) {
  15229. return behavior;
  15230. }
  15231. }
  15232. return null;
  15233. };
  15234. /**
  15235. * Returns the world matrix of the node
  15236. * @returns a matrix containing the node's world matrix
  15237. */
  15238. Node.prototype.getWorldMatrix = function () {
  15239. return BABYLON.Matrix.Identity();
  15240. };
  15241. // override it in derived class if you add new variables to the cache
  15242. // and call the parent class method
  15243. /** @ignore */
  15244. Node.prototype._initCache = function () {
  15245. this._cache = {};
  15246. this._cache.parent = undefined;
  15247. };
  15248. /** @ignore */
  15249. Node.prototype.updateCache = function (force) {
  15250. if (!force && this.isSynchronized())
  15251. return;
  15252. this._cache.parent = this.parent;
  15253. this._updateCache();
  15254. };
  15255. // override it in derived class if you add new variables to the cache
  15256. // and call the parent class method if !ignoreParentClass
  15257. /** @ignore */
  15258. Node.prototype._updateCache = function (ignoreParentClass) {
  15259. };
  15260. // override it in derived class if you add new variables to the cache
  15261. /** @ignore */
  15262. Node.prototype._isSynchronized = function () {
  15263. return true;
  15264. };
  15265. /** @ignore */
  15266. Node.prototype._markSyncedWithParent = function () {
  15267. if (this.parent) {
  15268. this._parentRenderId = this.parent._currentRenderId;
  15269. }
  15270. };
  15271. /** @ignore */
  15272. Node.prototype.isSynchronizedWithParent = function () {
  15273. if (!this.parent) {
  15274. return true;
  15275. }
  15276. if (this._parentRenderId !== this.parent._currentRenderId) {
  15277. return false;
  15278. }
  15279. return this.parent.isSynchronized();
  15280. };
  15281. /** @ignore */
  15282. Node.prototype.isSynchronized = function (updateCache) {
  15283. var check = this.hasNewParent();
  15284. check = check || !this.isSynchronizedWithParent();
  15285. check = check || !this._isSynchronized();
  15286. if (updateCache)
  15287. this.updateCache(true);
  15288. return !check;
  15289. };
  15290. /** @ignore */
  15291. Node.prototype.hasNewParent = function (update) {
  15292. if (this._cache.parent === this.parent)
  15293. return false;
  15294. if (update)
  15295. this._cache.parent = this.parent;
  15296. return true;
  15297. };
  15298. /**
  15299. * Is this node ready to be used/rendered
  15300. * @param completeCheck defines if a complete check (including materials and lights) has to be done (false by default)
  15301. * @return true if the node is ready
  15302. */
  15303. Node.prototype.isReady = function (completeCheck) {
  15304. if (completeCheck === void 0) { completeCheck = false; }
  15305. return this._isReady;
  15306. };
  15307. /**
  15308. * Is this node enabled?
  15309. * If the node has a parent, all ancestors will be checked and false will be returned if any are false (not enabled), otherwise will return true
  15310. * @param checkAncestors indicates if this method should check the ancestors. The default is to check the ancestors. If set to false, the method will return the value of this node without checking ancestors
  15311. * @return whether this node (and its parent) is enabled
  15312. * @see setEnabled
  15313. */
  15314. Node.prototype.isEnabled = function (checkAncestors) {
  15315. if (checkAncestors === void 0) { checkAncestors = true; }
  15316. if (checkAncestors === false) {
  15317. return this._isEnabled;
  15318. }
  15319. if (this._isEnabled === false) {
  15320. return false;
  15321. }
  15322. if (this.parent !== undefined && this.parent !== null) {
  15323. return this.parent.isEnabled(checkAncestors);
  15324. }
  15325. return true;
  15326. };
  15327. /**
  15328. * Set the enabled state of this node
  15329. * @param value defines the new enabled state
  15330. * @see isEnabled
  15331. */
  15332. Node.prototype.setEnabled = function (value) {
  15333. this._isEnabled = value;
  15334. };
  15335. /**
  15336. * Is this node a descendant of the given node?
  15337. * The function will iterate up the hierarchy until the ancestor was found or no more parents defined
  15338. * @param ancestor defines the parent node to inspect
  15339. * @see parent
  15340. * @returns a boolean indicating if this node is a descendant of the given node
  15341. */
  15342. Node.prototype.isDescendantOf = function (ancestor) {
  15343. if (this.parent) {
  15344. if (this.parent === ancestor) {
  15345. return true;
  15346. }
  15347. return this.parent.isDescendantOf(ancestor);
  15348. }
  15349. return false;
  15350. };
  15351. /** @ignore */
  15352. Node.prototype._getDescendants = function (results, directDescendantsOnly, predicate) {
  15353. if (directDescendantsOnly === void 0) { directDescendantsOnly = false; }
  15354. if (!this._children) {
  15355. return;
  15356. }
  15357. for (var index = 0; index < this._children.length; index++) {
  15358. var item = this._children[index];
  15359. if (!predicate || predicate(item)) {
  15360. results.push(item);
  15361. }
  15362. if (!directDescendantsOnly) {
  15363. item._getDescendants(results, false, predicate);
  15364. }
  15365. }
  15366. };
  15367. /**
  15368. * Will return all nodes that have this node as ascendant
  15369. * @param directDescendantsOnly defines if true only direct descendants of 'this' will be considered, if false direct and also indirect (children of children, an so on in a recursive manner) descendants of 'this' will be considered
  15370. * @param predicate defines an optional predicate that will be called on every evaluated child, the predicate must return true for a given child to be part of the result, otherwise it will be ignored
  15371. * @return all children nodes of all types
  15372. */
  15373. Node.prototype.getDescendants = function (directDescendantsOnly, predicate) {
  15374. var results = new Array();
  15375. this._getDescendants(results, directDescendantsOnly, predicate);
  15376. return results;
  15377. };
  15378. /**
  15379. * Get all child-meshes of this node
  15380. * @param directDescendantsOnly defines if true only direct descendants of 'this' will be considered, if false direct and also indirect (children of children, an so on in a recursive manner) descendants of 'this' will be considered
  15381. * @param predicate defines an optional predicate that will be called on every evaluated child, the predicate must return true for a given child to be part of the result, otherwise it will be ignored
  15382. * @returns an array of {BABYLON.AbstractMesh}
  15383. */
  15384. Node.prototype.getChildMeshes = function (directDescendantsOnly, predicate) {
  15385. var results = [];
  15386. this._getDescendants(results, directDescendantsOnly, function (node) {
  15387. return ((!predicate || predicate(node)) && (node instanceof BABYLON.AbstractMesh));
  15388. });
  15389. return results;
  15390. };
  15391. /**
  15392. * Get all child-transformNodes of this node
  15393. * @param directDescendantsOnly defines if true only direct descendants of 'this' will be considered, if false direct and also indirect (children of children, an so on in a recursive manner) descendants of 'this' will be considered
  15394. * @param predicate defines an optional predicate that will be called on every evaluated child, the predicate must return true for a given child to be part of the result, otherwise it will be ignored
  15395. * @returns an array of {BABYLON.TransformNode}
  15396. */
  15397. Node.prototype.getChildTransformNodes = function (directDescendantsOnly, predicate) {
  15398. var results = [];
  15399. this._getDescendants(results, directDescendantsOnly, function (node) {
  15400. return ((!predicate || predicate(node)) && (node instanceof BABYLON.TransformNode));
  15401. });
  15402. return results;
  15403. };
  15404. /**
  15405. * Get all direct children of this node
  15406. * @param predicate defines an optional predicate that will be called on every evaluated child, the predicate must return true for a given child to be part of the result, otherwise it will be ignored
  15407. * @returns an array of {BABYLON.Node}
  15408. */
  15409. Node.prototype.getChildren = function (predicate) {
  15410. return this.getDescendants(true, predicate);
  15411. };
  15412. /** @ignore */
  15413. Node.prototype._setReady = function (state) {
  15414. if (state === this._isReady) {
  15415. return;
  15416. }
  15417. if (!state) {
  15418. this._isReady = false;
  15419. return;
  15420. }
  15421. this._isReady = true;
  15422. if (this.onReady) {
  15423. this.onReady(this);
  15424. }
  15425. };
  15426. /**
  15427. * Get an animation by name
  15428. * @param name defines the name of the animation to look for
  15429. * @returns null if not found else the requested animation
  15430. */
  15431. Node.prototype.getAnimationByName = function (name) {
  15432. for (var i = 0; i < this.animations.length; i++) {
  15433. var animation = this.animations[i];
  15434. if (animation.name === name) {
  15435. return animation;
  15436. }
  15437. }
  15438. return null;
  15439. };
  15440. /**
  15441. * Creates an animation range for this node
  15442. * @param name defines the name of the range
  15443. * @param from defines the starting key
  15444. * @param to defines the end key
  15445. */
  15446. Node.prototype.createAnimationRange = function (name, from, to) {
  15447. // check name not already in use
  15448. if (!this._ranges[name]) {
  15449. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  15450. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  15451. if (this.animations[i]) {
  15452. this.animations[i].createRange(name, from, to);
  15453. }
  15454. }
  15455. }
  15456. };
  15457. /**
  15458. * Delete a specific animation range
  15459. * @param name defines the name of the range to delete
  15460. * @param deleteFrames defines if animation frames from the range must be deleted as well
  15461. */
  15462. Node.prototype.deleteAnimationRange = function (name, deleteFrames) {
  15463. if (deleteFrames === void 0) { deleteFrames = true; }
  15464. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  15465. if (this.animations[i]) {
  15466. this.animations[i].deleteRange(name, deleteFrames);
  15467. }
  15468. }
  15469. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  15470. };
  15471. /**
  15472. * Get an animation range by name
  15473. * @param name defines the name of the animation range to look for
  15474. * @returns null if not found else the requested animation range
  15475. */
  15476. Node.prototype.getAnimationRange = function (name) {
  15477. return this._ranges[name];
  15478. };
  15479. /**
  15480. * Will start the animation sequence
  15481. * @param name defines the range frames for animation sequence
  15482. * @param loop defines if the animation should loop (false by default)
  15483. * @param speedRatio defines the speed factor in which to run the animation (1 by default)
  15484. * @param onAnimationEnd defines a function to be executed when the animation ended (undefined by default)
  15485. * @returns the object created for this animation. If range does not exist, it will return null
  15486. */
  15487. Node.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  15488. var range = this.getAnimationRange(name);
  15489. if (!range) {
  15490. return null;
  15491. }
  15492. return this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  15493. };
  15494. /**
  15495. * Serialize animation ranges into a JSON compatible object
  15496. * @returns serialization object
  15497. */
  15498. Node.prototype.serializeAnimationRanges = function () {
  15499. var serializationRanges = [];
  15500. for (var name in this._ranges) {
  15501. var localRange = this._ranges[name];
  15502. if (!localRange) {
  15503. continue;
  15504. }
  15505. var range = {};
  15506. range.name = name;
  15507. range.from = localRange.from;
  15508. range.to = localRange.to;
  15509. serializationRanges.push(range);
  15510. }
  15511. return serializationRanges;
  15512. };
  15513. /**
  15514. * Computes the world matrix of the node
  15515. * @param force defines if the cache version should be invalidated forcing the world matrix to be created from scratch
  15516. * @returns the world matrix
  15517. */
  15518. Node.prototype.computeWorldMatrix = function (force) {
  15519. return BABYLON.Matrix.Identity();
  15520. };
  15521. /**
  15522. * Releases all associated resources
  15523. */
  15524. Node.prototype.dispose = function () {
  15525. this.parent = null;
  15526. // Callback
  15527. this.onDisposeObservable.notifyObservers(this);
  15528. this.onDisposeObservable.clear();
  15529. // Behaviors
  15530. for (var _i = 0, _a = this._behaviors; _i < _a.length; _i++) {
  15531. var behavior = _a[_i];
  15532. behavior.detach();
  15533. }
  15534. this._behaviors = [];
  15535. this._isDisposed = true;
  15536. };
  15537. /**
  15538. * Parse animation range data from a serialization object and store them into a given node
  15539. * @param node defines where to store the animation ranges
  15540. * @param parsedNode defines the serialization object to read data from
  15541. * @param scene defines the hosting scene
  15542. */
  15543. Node.ParseAnimationRanges = function (node, parsedNode, scene) {
  15544. if (parsedNode.ranges) {
  15545. for (var index = 0; index < parsedNode.ranges.length; index++) {
  15546. var data = parsedNode.ranges[index];
  15547. node.createAnimationRange(data.name, data.from, data.to);
  15548. }
  15549. }
  15550. };
  15551. __decorate([
  15552. BABYLON.serialize()
  15553. ], Node.prototype, "name", void 0);
  15554. __decorate([
  15555. BABYLON.serialize()
  15556. ], Node.prototype, "id", void 0);
  15557. __decorate([
  15558. BABYLON.serialize()
  15559. ], Node.prototype, "uniqueId", void 0);
  15560. __decorate([
  15561. BABYLON.serialize()
  15562. ], Node.prototype, "state", void 0);
  15563. __decorate([
  15564. BABYLON.serialize()
  15565. ], Node.prototype, "metadata", void 0);
  15566. return Node;
  15567. }());
  15568. BABYLON.Node = Node;
  15569. })(BABYLON || (BABYLON = {}));
  15570. //# sourceMappingURL=babylon.node.js.map
  15571. var BABYLON;
  15572. (function (BABYLON) {
  15573. var BoundingSphere = /** @class */ (function () {
  15574. function BoundingSphere(minimum, maximum) {
  15575. this.minimum = minimum;
  15576. this.maximum = maximum;
  15577. this._tempRadiusVector = BABYLON.Vector3.Zero();
  15578. var distance = BABYLON.Vector3.Distance(minimum, maximum);
  15579. this.center = BABYLON.Vector3.Lerp(minimum, maximum, 0.5);
  15580. this.radius = distance * 0.5;
  15581. this.centerWorld = BABYLON.Vector3.Zero();
  15582. this._update(BABYLON.Matrix.Identity());
  15583. }
  15584. // Methods
  15585. BoundingSphere.prototype._update = function (world) {
  15586. BABYLON.Vector3.TransformCoordinatesToRef(this.center, world, this.centerWorld);
  15587. BABYLON.Vector3.TransformNormalFromFloatsToRef(1.0, 1.0, 1.0, world, this._tempRadiusVector);
  15588. this.radiusWorld = Math.max(Math.abs(this._tempRadiusVector.x), Math.abs(this._tempRadiusVector.y), Math.abs(this._tempRadiusVector.z)) * this.radius;
  15589. };
  15590. BoundingSphere.prototype.isInFrustum = function (frustumPlanes) {
  15591. for (var i = 0; i < 6; i++) {
  15592. if (frustumPlanes[i].dotCoordinate(this.centerWorld) <= -this.radiusWorld)
  15593. return false;
  15594. }
  15595. return true;
  15596. };
  15597. BoundingSphere.prototype.intersectsPoint = function (point) {
  15598. var x = this.centerWorld.x - point.x;
  15599. var y = this.centerWorld.y - point.y;
  15600. var z = this.centerWorld.z - point.z;
  15601. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  15602. if (Math.abs(this.radiusWorld - distance) < BABYLON.Epsilon)
  15603. return false;
  15604. return true;
  15605. };
  15606. // Statics
  15607. BoundingSphere.Intersects = function (sphere0, sphere1) {
  15608. var x = sphere0.centerWorld.x - sphere1.centerWorld.x;
  15609. var y = sphere0.centerWorld.y - sphere1.centerWorld.y;
  15610. var z = sphere0.centerWorld.z - sphere1.centerWorld.z;
  15611. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  15612. if (sphere0.radiusWorld + sphere1.radiusWorld < distance)
  15613. return false;
  15614. return true;
  15615. };
  15616. return BoundingSphere;
  15617. }());
  15618. BABYLON.BoundingSphere = BoundingSphere;
  15619. })(BABYLON || (BABYLON = {}));
  15620. //# sourceMappingURL=babylon.boundingSphere.js.map
  15621. var BABYLON;
  15622. (function (BABYLON) {
  15623. var BoundingBox = /** @class */ (function () {
  15624. function BoundingBox(minimum, maximum) {
  15625. this.minimum = minimum;
  15626. this.maximum = maximum;
  15627. this.vectors = new Array();
  15628. this.vectorsWorld = new Array();
  15629. // Bounding vectors
  15630. this.vectors.push(this.minimum.clone());
  15631. this.vectors.push(this.maximum.clone());
  15632. this.vectors.push(this.minimum.clone());
  15633. this.vectors[2].x = this.maximum.x;
  15634. this.vectors.push(this.minimum.clone());
  15635. this.vectors[3].y = this.maximum.y;
  15636. this.vectors.push(this.minimum.clone());
  15637. this.vectors[4].z = this.maximum.z;
  15638. this.vectors.push(this.maximum.clone());
  15639. this.vectors[5].z = this.minimum.z;
  15640. this.vectors.push(this.maximum.clone());
  15641. this.vectors[6].x = this.minimum.x;
  15642. this.vectors.push(this.maximum.clone());
  15643. this.vectors[7].y = this.minimum.y;
  15644. // OBB
  15645. this.center = this.maximum.add(this.minimum).scale(0.5);
  15646. this.extendSize = this.maximum.subtract(this.minimum).scale(0.5);
  15647. this.directions = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  15648. // World
  15649. for (var index = 0; index < this.vectors.length; index++) {
  15650. this.vectorsWorld[index] = BABYLON.Vector3.Zero();
  15651. }
  15652. this.minimumWorld = BABYLON.Vector3.Zero();
  15653. this.maximumWorld = BABYLON.Vector3.Zero();
  15654. this.centerWorld = BABYLON.Vector3.Zero();
  15655. this.extendSizeWorld = BABYLON.Vector3.Zero();
  15656. this._update(BABYLON.Matrix.Identity());
  15657. }
  15658. // Methods
  15659. BoundingBox.prototype.getWorldMatrix = function () {
  15660. return this._worldMatrix;
  15661. };
  15662. BoundingBox.prototype.setWorldMatrix = function (matrix) {
  15663. this._worldMatrix.copyFrom(matrix);
  15664. return this;
  15665. };
  15666. BoundingBox.prototype._update = function (world) {
  15667. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this.minimumWorld);
  15668. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this.maximumWorld);
  15669. for (var index = 0; index < this.vectors.length; index++) {
  15670. var v = this.vectorsWorld[index];
  15671. BABYLON.Vector3.TransformCoordinatesToRef(this.vectors[index], world, v);
  15672. if (v.x < this.minimumWorld.x)
  15673. this.minimumWorld.x = v.x;
  15674. if (v.y < this.minimumWorld.y)
  15675. this.minimumWorld.y = v.y;
  15676. if (v.z < this.minimumWorld.z)
  15677. this.minimumWorld.z = v.z;
  15678. if (v.x > this.maximumWorld.x)
  15679. this.maximumWorld.x = v.x;
  15680. if (v.y > this.maximumWorld.y)
  15681. this.maximumWorld.y = v.y;
  15682. if (v.z > this.maximumWorld.z)
  15683. this.maximumWorld.z = v.z;
  15684. }
  15685. // Extend
  15686. this.maximumWorld.subtractToRef(this.minimumWorld, this.extendSizeWorld);
  15687. this.extendSizeWorld.scaleInPlace(0.5);
  15688. // OBB
  15689. this.maximumWorld.addToRef(this.minimumWorld, this.centerWorld);
  15690. this.centerWorld.scaleInPlace(0.5);
  15691. BABYLON.Vector3.FromFloatArrayToRef(world.m, 0, this.directions[0]);
  15692. BABYLON.Vector3.FromFloatArrayToRef(world.m, 4, this.directions[1]);
  15693. BABYLON.Vector3.FromFloatArrayToRef(world.m, 8, this.directions[2]);
  15694. this._worldMatrix = world;
  15695. };
  15696. BoundingBox.prototype.isInFrustum = function (frustumPlanes) {
  15697. return BoundingBox.IsInFrustum(this.vectorsWorld, frustumPlanes);
  15698. };
  15699. BoundingBox.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  15700. return BoundingBox.IsCompletelyInFrustum(this.vectorsWorld, frustumPlanes);
  15701. };
  15702. BoundingBox.prototype.intersectsPoint = function (point) {
  15703. var delta = -BABYLON.Epsilon;
  15704. if (this.maximumWorld.x - point.x < delta || delta > point.x - this.minimumWorld.x)
  15705. return false;
  15706. if (this.maximumWorld.y - point.y < delta || delta > point.y - this.minimumWorld.y)
  15707. return false;
  15708. if (this.maximumWorld.z - point.z < delta || delta > point.z - this.minimumWorld.z)
  15709. return false;
  15710. return true;
  15711. };
  15712. BoundingBox.prototype.intersectsSphere = function (sphere) {
  15713. return BoundingBox.IntersectsSphere(this.minimumWorld, this.maximumWorld, sphere.centerWorld, sphere.radiusWorld);
  15714. };
  15715. BoundingBox.prototype.intersectsMinMax = function (min, max) {
  15716. if (this.maximumWorld.x < min.x || this.minimumWorld.x > max.x)
  15717. return false;
  15718. if (this.maximumWorld.y < min.y || this.minimumWorld.y > max.y)
  15719. return false;
  15720. if (this.maximumWorld.z < min.z || this.minimumWorld.z > max.z)
  15721. return false;
  15722. return true;
  15723. };
  15724. // Statics
  15725. BoundingBox.Intersects = function (box0, box1) {
  15726. if (box0.maximumWorld.x < box1.minimumWorld.x || box0.minimumWorld.x > box1.maximumWorld.x)
  15727. return false;
  15728. if (box0.maximumWorld.y < box1.minimumWorld.y || box0.minimumWorld.y > box1.maximumWorld.y)
  15729. return false;
  15730. if (box0.maximumWorld.z < box1.minimumWorld.z || box0.minimumWorld.z > box1.maximumWorld.z)
  15731. return false;
  15732. return true;
  15733. };
  15734. BoundingBox.IntersectsSphere = function (minPoint, maxPoint, sphereCenter, sphereRadius) {
  15735. var vector = BABYLON.Vector3.Clamp(sphereCenter, minPoint, maxPoint);
  15736. var num = BABYLON.Vector3.DistanceSquared(sphereCenter, vector);
  15737. return (num <= (sphereRadius * sphereRadius));
  15738. };
  15739. BoundingBox.IsCompletelyInFrustum = function (boundingVectors, frustumPlanes) {
  15740. for (var p = 0; p < 6; p++) {
  15741. for (var i = 0; i < 8; i++) {
  15742. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  15743. return false;
  15744. }
  15745. }
  15746. }
  15747. return true;
  15748. };
  15749. BoundingBox.IsInFrustum = function (boundingVectors, frustumPlanes) {
  15750. for (var p = 0; p < 6; p++) {
  15751. var inCount = 8;
  15752. for (var i = 0; i < 8; i++) {
  15753. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  15754. --inCount;
  15755. }
  15756. else {
  15757. break;
  15758. }
  15759. }
  15760. if (inCount === 0)
  15761. return false;
  15762. }
  15763. return true;
  15764. };
  15765. return BoundingBox;
  15766. }());
  15767. BABYLON.BoundingBox = BoundingBox;
  15768. })(BABYLON || (BABYLON = {}));
  15769. //# sourceMappingURL=babylon.boundingBox.js.map
  15770. var BABYLON;
  15771. (function (BABYLON) {
  15772. var computeBoxExtents = function (axis, box) {
  15773. var p = BABYLON.Vector3.Dot(box.centerWorld, axis);
  15774. var r0 = Math.abs(BABYLON.Vector3.Dot(box.directions[0], axis)) * box.extendSize.x;
  15775. var r1 = Math.abs(BABYLON.Vector3.Dot(box.directions[1], axis)) * box.extendSize.y;
  15776. var r2 = Math.abs(BABYLON.Vector3.Dot(box.directions[2], axis)) * box.extendSize.z;
  15777. var r = r0 + r1 + r2;
  15778. return {
  15779. min: p - r,
  15780. max: p + r
  15781. };
  15782. };
  15783. var extentsOverlap = function (min0, max0, min1, max1) { return !(min0 > max1 || min1 > max0); };
  15784. var axisOverlap = function (axis, box0, box1) {
  15785. var result0 = computeBoxExtents(axis, box0);
  15786. var result1 = computeBoxExtents(axis, box1);
  15787. return extentsOverlap(result0.min, result0.max, result1.min, result1.max);
  15788. };
  15789. var BoundingInfo = /** @class */ (function () {
  15790. function BoundingInfo(minimum, maximum) {
  15791. this.minimum = minimum;
  15792. this.maximum = maximum;
  15793. this._isLocked = false;
  15794. this.boundingBox = new BABYLON.BoundingBox(minimum, maximum);
  15795. this.boundingSphere = new BABYLON.BoundingSphere(minimum, maximum);
  15796. }
  15797. Object.defineProperty(BoundingInfo.prototype, "isLocked", {
  15798. get: function () {
  15799. return this._isLocked;
  15800. },
  15801. set: function (value) {
  15802. this._isLocked = value;
  15803. },
  15804. enumerable: true,
  15805. configurable: true
  15806. });
  15807. // Methods
  15808. BoundingInfo.prototype.update = function (world) {
  15809. if (this._isLocked) {
  15810. return;
  15811. }
  15812. this.boundingBox._update(world);
  15813. this.boundingSphere._update(world);
  15814. };
  15815. /**
  15816. * Recreate the bounding info to be centered around a specific point given a specific extend.
  15817. * @param center New center of the bounding info
  15818. * @param extend New extend of the bounding info
  15819. */
  15820. BoundingInfo.prototype.centerOn = function (center, extend) {
  15821. this.minimum = center.subtract(extend);
  15822. this.maximum = center.add(extend);
  15823. this.boundingBox = new BABYLON.BoundingBox(this.minimum, this.maximum);
  15824. this.boundingSphere = new BABYLON.BoundingSphere(this.minimum, this.maximum);
  15825. return this;
  15826. };
  15827. BoundingInfo.prototype.isInFrustum = function (frustumPlanes) {
  15828. if (!this.boundingSphere.isInFrustum(frustumPlanes))
  15829. return false;
  15830. return this.boundingBox.isInFrustum(frustumPlanes);
  15831. };
  15832. Object.defineProperty(BoundingInfo.prototype, "diagonalLength", {
  15833. /**
  15834. * Gets the world distance between the min and max points of the bounding box
  15835. */
  15836. get: function () {
  15837. var boundingBox = this.boundingBox;
  15838. var size = boundingBox.maximumWorld.subtract(boundingBox.minimumWorld);
  15839. return size.length();
  15840. },
  15841. enumerable: true,
  15842. configurable: true
  15843. });
  15844. BoundingInfo.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  15845. return this.boundingBox.isCompletelyInFrustum(frustumPlanes);
  15846. };
  15847. BoundingInfo.prototype._checkCollision = function (collider) {
  15848. return collider._canDoCollision(this.boundingSphere.centerWorld, this.boundingSphere.radiusWorld, this.boundingBox.minimumWorld, this.boundingBox.maximumWorld);
  15849. };
  15850. BoundingInfo.prototype.intersectsPoint = function (point) {
  15851. if (!this.boundingSphere.centerWorld) {
  15852. return false;
  15853. }
  15854. if (!this.boundingSphere.intersectsPoint(point)) {
  15855. return false;
  15856. }
  15857. if (!this.boundingBox.intersectsPoint(point)) {
  15858. return false;
  15859. }
  15860. return true;
  15861. };
  15862. BoundingInfo.prototype.intersects = function (boundingInfo, precise) {
  15863. if (!this.boundingSphere.centerWorld || !boundingInfo.boundingSphere.centerWorld) {
  15864. return false;
  15865. }
  15866. if (!BABYLON.BoundingSphere.Intersects(this.boundingSphere, boundingInfo.boundingSphere)) {
  15867. return false;
  15868. }
  15869. if (!BABYLON.BoundingBox.Intersects(this.boundingBox, boundingInfo.boundingBox)) {
  15870. return false;
  15871. }
  15872. if (!precise) {
  15873. return true;
  15874. }
  15875. var box0 = this.boundingBox;
  15876. var box1 = boundingInfo.boundingBox;
  15877. if (!axisOverlap(box0.directions[0], box0, box1))
  15878. return false;
  15879. if (!axisOverlap(box0.directions[1], box0, box1))
  15880. return false;
  15881. if (!axisOverlap(box0.directions[2], box0, box1))
  15882. return false;
  15883. if (!axisOverlap(box1.directions[0], box0, box1))
  15884. return false;
  15885. if (!axisOverlap(box1.directions[1], box0, box1))
  15886. return false;
  15887. if (!axisOverlap(box1.directions[2], box0, box1))
  15888. return false;
  15889. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[0]), box0, box1))
  15890. return false;
  15891. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[1]), box0, box1))
  15892. return false;
  15893. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[2]), box0, box1))
  15894. return false;
  15895. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[0]), box0, box1))
  15896. return false;
  15897. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[1]), box0, box1))
  15898. return false;
  15899. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[2]), box0, box1))
  15900. return false;
  15901. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[0]), box0, box1))
  15902. return false;
  15903. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[1]), box0, box1))
  15904. return false;
  15905. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[2]), box0, box1))
  15906. return false;
  15907. return true;
  15908. };
  15909. return BoundingInfo;
  15910. }());
  15911. BABYLON.BoundingInfo = BoundingInfo;
  15912. })(BABYLON || (BABYLON = {}));
  15913. //# sourceMappingURL=babylon.boundingInfo.js.map
  15914. var BABYLON;
  15915. (function (BABYLON) {
  15916. var TransformNode = /** @class */ (function (_super) {
  15917. __extends(TransformNode, _super);
  15918. function TransformNode(name, scene, isPure) {
  15919. if (scene === void 0) { scene = null; }
  15920. if (isPure === void 0) { isPure = true; }
  15921. var _this = _super.call(this, name, scene) || this;
  15922. // Properties
  15923. _this._rotation = BABYLON.Vector3.Zero();
  15924. _this._scaling = BABYLON.Vector3.One();
  15925. _this._isDirty = false;
  15926. _this.billboardMode = BABYLON.AbstractMesh.BILLBOARDMODE_NONE;
  15927. _this.scalingDeterminant = 1;
  15928. _this.infiniteDistance = false;
  15929. _this.position = BABYLON.Vector3.Zero();
  15930. _this._localWorld = BABYLON.Matrix.Zero();
  15931. _this._worldMatrix = BABYLON.Matrix.Zero();
  15932. _this._worldMatrixDeterminant = 0;
  15933. _this._absolutePosition = BABYLON.Vector3.Zero();
  15934. _this._pivotMatrix = BABYLON.Matrix.Identity();
  15935. _this._postMultiplyPivotMatrix = false;
  15936. _this._isWorldMatrixFrozen = false;
  15937. /**
  15938. * An event triggered after the world matrix is updated
  15939. * @type {BABYLON.Observable}
  15940. */
  15941. _this.onAfterWorldMatrixUpdateObservable = new BABYLON.Observable();
  15942. _this._nonUniformScaling = false;
  15943. if (isPure) {
  15944. _this.getScene().addTransformNode(_this);
  15945. }
  15946. return _this;
  15947. }
  15948. Object.defineProperty(TransformNode.prototype, "rotation", {
  15949. /**
  15950. * Rotation property : a Vector3 depicting the rotation value in radians around each local axis X, Y, Z.
  15951. * If rotation quaternion is set, this Vector3 will (almost always) be the Zero vector!
  15952. * Default : (0.0, 0.0, 0.0)
  15953. */
  15954. get: function () {
  15955. return this._rotation;
  15956. },
  15957. set: function (newRotation) {
  15958. this._rotation = newRotation;
  15959. },
  15960. enumerable: true,
  15961. configurable: true
  15962. });
  15963. Object.defineProperty(TransformNode.prototype, "scaling", {
  15964. /**
  15965. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  15966. * Default : (1.0, 1.0, 1.0)
  15967. */
  15968. get: function () {
  15969. return this._scaling;
  15970. },
  15971. /**
  15972. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  15973. * Default : (1.0, 1.0, 1.0)
  15974. */
  15975. set: function (newScaling) {
  15976. this._scaling = newScaling;
  15977. },
  15978. enumerable: true,
  15979. configurable: true
  15980. });
  15981. Object.defineProperty(TransformNode.prototype, "rotationQuaternion", {
  15982. /**
  15983. * Rotation Quaternion property : this a Quaternion object depicting the mesh rotation by using a unit quaternion.
  15984. * It's null by default.
  15985. * If set, only the rotationQuaternion is then used to compute the mesh rotation and its property `.rotation\ is then ignored and set to (0.0, 0.0, 0.0)
  15986. */
  15987. get: function () {
  15988. return this._rotationQuaternion;
  15989. },
  15990. set: function (quaternion) {
  15991. this._rotationQuaternion = quaternion;
  15992. //reset the rotation vector.
  15993. if (quaternion && this.rotation.length()) {
  15994. this.rotation.copyFromFloats(0.0, 0.0, 0.0);
  15995. }
  15996. },
  15997. enumerable: true,
  15998. configurable: true
  15999. });
  16000. /**
  16001. * Returns the latest update of the World matrix
  16002. * Returns a Matrix.
  16003. */
  16004. TransformNode.prototype.getWorldMatrix = function () {
  16005. if (this._currentRenderId !== this.getScene().getRenderId()) {
  16006. this.computeWorldMatrix();
  16007. }
  16008. return this._worldMatrix;
  16009. };
  16010. /**
  16011. * Returns the latest update of the World matrix determinant.
  16012. */
  16013. TransformNode.prototype._getWorldMatrixDeterminant = function () {
  16014. return this._worldMatrixDeterminant;
  16015. };
  16016. Object.defineProperty(TransformNode.prototype, "worldMatrixFromCache", {
  16017. /**
  16018. * Returns directly the latest state of the mesh World matrix.
  16019. * A Matrix is returned.
  16020. */
  16021. get: function () {
  16022. return this._worldMatrix;
  16023. },
  16024. enumerable: true,
  16025. configurable: true
  16026. });
  16027. /**
  16028. * Copies the paramater passed Matrix into the mesh Pose matrix.
  16029. * Returns the AbstractMesh.
  16030. */
  16031. TransformNode.prototype.updatePoseMatrix = function (matrix) {
  16032. this._poseMatrix.copyFrom(matrix);
  16033. return this;
  16034. };
  16035. /**
  16036. * Returns the mesh Pose matrix.
  16037. * Returned object : Matrix
  16038. */
  16039. TransformNode.prototype.getPoseMatrix = function () {
  16040. return this._poseMatrix;
  16041. };
  16042. TransformNode.prototype._isSynchronized = function () {
  16043. if (this._isDirty) {
  16044. return false;
  16045. }
  16046. if (this.billboardMode !== this._cache.billboardMode || this.billboardMode !== BABYLON.AbstractMesh.BILLBOARDMODE_NONE)
  16047. return false;
  16048. if (this._cache.pivotMatrixUpdated) {
  16049. return false;
  16050. }
  16051. if (this.infiniteDistance) {
  16052. return false;
  16053. }
  16054. if (!this._cache.position.equals(this.position))
  16055. return false;
  16056. if (this.rotationQuaternion) {
  16057. if (!this._cache.rotationQuaternion.equals(this.rotationQuaternion))
  16058. return false;
  16059. }
  16060. if (!this._cache.rotation.equals(this.rotation))
  16061. return false;
  16062. if (!this._cache.scaling.equals(this.scaling))
  16063. return false;
  16064. return true;
  16065. };
  16066. TransformNode.prototype._initCache = function () {
  16067. _super.prototype._initCache.call(this);
  16068. this._cache.localMatrixUpdated = false;
  16069. this._cache.position = BABYLON.Vector3.Zero();
  16070. this._cache.scaling = BABYLON.Vector3.Zero();
  16071. this._cache.rotation = BABYLON.Vector3.Zero();
  16072. this._cache.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 0);
  16073. this._cache.billboardMode = -1;
  16074. };
  16075. TransformNode.prototype.markAsDirty = function (property) {
  16076. if (property === "rotation") {
  16077. this.rotationQuaternion = null;
  16078. }
  16079. this._currentRenderId = Number.MAX_VALUE;
  16080. this._isDirty = true;
  16081. return this;
  16082. };
  16083. Object.defineProperty(TransformNode.prototype, "absolutePosition", {
  16084. /**
  16085. * Returns the current mesh absolute position.
  16086. * Retuns a Vector3.
  16087. */
  16088. get: function () {
  16089. return this._absolutePosition;
  16090. },
  16091. enumerable: true,
  16092. configurable: true
  16093. });
  16094. /**
  16095. * Sets a new matrix to apply before all other transformation
  16096. * @param matrix defines the transform matrix
  16097. * @returns the current TransformNode
  16098. */
  16099. TransformNode.prototype.setPreTransformMatrix = function (matrix) {
  16100. return this.setPivotMatrix(matrix, false);
  16101. };
  16102. /**
  16103. * Sets a new pivot matrix to the current node
  16104. * @param matrix defines the new pivot matrix to use
  16105. * @param postMultiplyPivotMatrix defines if the pivot matrix must be cancelled in the world matrix. When this parameter is set to true (default), the inverse of the pivot matrix is also applied at the end to cancel the transformation effect
  16106. * @returns the current TransformNode
  16107. */
  16108. TransformNode.prototype.setPivotMatrix = function (matrix, postMultiplyPivotMatrix) {
  16109. if (postMultiplyPivotMatrix === void 0) { postMultiplyPivotMatrix = true; }
  16110. this._pivotMatrix = matrix.clone();
  16111. this._cache.pivotMatrixUpdated = true;
  16112. this._postMultiplyPivotMatrix = postMultiplyPivotMatrix;
  16113. if (this._postMultiplyPivotMatrix) {
  16114. if (!this._pivotMatrixInverse) {
  16115. this._pivotMatrixInverse = BABYLON.Matrix.Invert(this._pivotMatrix);
  16116. }
  16117. else {
  16118. this._pivotMatrix.invertToRef(this._pivotMatrixInverse);
  16119. }
  16120. }
  16121. return this;
  16122. };
  16123. /**
  16124. * Returns the mesh pivot matrix.
  16125. * Default : Identity.
  16126. * A Matrix is returned.
  16127. */
  16128. TransformNode.prototype.getPivotMatrix = function () {
  16129. return this._pivotMatrix;
  16130. };
  16131. /**
  16132. * Prevents the World matrix to be computed any longer.
  16133. * Returns the AbstractMesh.
  16134. */
  16135. TransformNode.prototype.freezeWorldMatrix = function () {
  16136. this._isWorldMatrixFrozen = false; // no guarantee world is not already frozen, switch off temporarily
  16137. this.computeWorldMatrix(true);
  16138. this._isWorldMatrixFrozen = true;
  16139. return this;
  16140. };
  16141. /**
  16142. * Allows back the World matrix computation.
  16143. * Returns the AbstractMesh.
  16144. */
  16145. TransformNode.prototype.unfreezeWorldMatrix = function () {
  16146. this._isWorldMatrixFrozen = false;
  16147. this.computeWorldMatrix(true);
  16148. return this;
  16149. };
  16150. Object.defineProperty(TransformNode.prototype, "isWorldMatrixFrozen", {
  16151. /**
  16152. * True if the World matrix has been frozen.
  16153. * Returns a boolean.
  16154. */
  16155. get: function () {
  16156. return this._isWorldMatrixFrozen;
  16157. },
  16158. enumerable: true,
  16159. configurable: true
  16160. });
  16161. /**
  16162. * Retuns the mesh absolute position in the World.
  16163. * Returns a Vector3.
  16164. */
  16165. TransformNode.prototype.getAbsolutePosition = function () {
  16166. this.computeWorldMatrix();
  16167. return this._absolutePosition;
  16168. };
  16169. /**
  16170. * Sets the mesh absolute position in the World from a Vector3 or an Array(3).
  16171. * Returns the AbstractMesh.
  16172. */
  16173. TransformNode.prototype.setAbsolutePosition = function (absolutePosition) {
  16174. if (!absolutePosition) {
  16175. return this;
  16176. }
  16177. var absolutePositionX;
  16178. var absolutePositionY;
  16179. var absolutePositionZ;
  16180. if (absolutePosition.x === undefined) {
  16181. if (arguments.length < 3) {
  16182. return this;
  16183. }
  16184. absolutePositionX = arguments[0];
  16185. absolutePositionY = arguments[1];
  16186. absolutePositionZ = arguments[2];
  16187. }
  16188. else {
  16189. absolutePositionX = absolutePosition.x;
  16190. absolutePositionY = absolutePosition.y;
  16191. absolutePositionZ = absolutePosition.z;
  16192. }
  16193. if (this.parent) {
  16194. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  16195. invertParentWorldMatrix.invert();
  16196. var worldPosition = new BABYLON.Vector3(absolutePositionX, absolutePositionY, absolutePositionZ);
  16197. this.position = BABYLON.Vector3.TransformCoordinates(worldPosition, invertParentWorldMatrix);
  16198. }
  16199. else {
  16200. this.position.x = absolutePositionX;
  16201. this.position.y = absolutePositionY;
  16202. this.position.z = absolutePositionZ;
  16203. }
  16204. return this;
  16205. };
  16206. /**
  16207. * Sets the mesh position in its local space.
  16208. * Returns the AbstractMesh.
  16209. */
  16210. TransformNode.prototype.setPositionWithLocalVector = function (vector3) {
  16211. this.computeWorldMatrix();
  16212. this.position = BABYLON.Vector3.TransformNormal(vector3, this._localWorld);
  16213. return this;
  16214. };
  16215. /**
  16216. * Returns the mesh position in the local space from the current World matrix values.
  16217. * Returns a new Vector3.
  16218. */
  16219. TransformNode.prototype.getPositionExpressedInLocalSpace = function () {
  16220. this.computeWorldMatrix();
  16221. var invLocalWorldMatrix = this._localWorld.clone();
  16222. invLocalWorldMatrix.invert();
  16223. return BABYLON.Vector3.TransformNormal(this.position, invLocalWorldMatrix);
  16224. };
  16225. /**
  16226. * Translates the mesh along the passed Vector3 in its local space.
  16227. * Returns the AbstractMesh.
  16228. */
  16229. TransformNode.prototype.locallyTranslate = function (vector3) {
  16230. this.computeWorldMatrix(true);
  16231. this.position = BABYLON.Vector3.TransformCoordinates(vector3, this._localWorld);
  16232. return this;
  16233. };
  16234. /**
  16235. * Orients a mesh towards a target point. Mesh must be drawn facing user.
  16236. * @param targetPoint the position (must be in same space as current mesh) to look at
  16237. * @param yawCor optional yaw (y-axis) correction in radians
  16238. * @param pitchCor optional pitch (x-axis) correction in radians
  16239. * @param rollCor optional roll (z-axis) correction in radians
  16240. * @param space the choosen space of the target
  16241. * @returns the TransformNode.
  16242. */
  16243. TransformNode.prototype.lookAt = function (targetPoint, yawCor, pitchCor, rollCor, space) {
  16244. if (yawCor === void 0) { yawCor = 0; }
  16245. if (pitchCor === void 0) { pitchCor = 0; }
  16246. if (rollCor === void 0) { rollCor = 0; }
  16247. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  16248. var dv = BABYLON.AbstractMesh._lookAtVectorCache;
  16249. var pos = space === BABYLON.Space.LOCAL ? this.position : this.getAbsolutePosition();
  16250. targetPoint.subtractToRef(pos, dv);
  16251. var yaw = -Math.atan2(dv.z, dv.x) - Math.PI / 2;
  16252. var len = Math.sqrt(dv.x * dv.x + dv.z * dv.z);
  16253. var pitch = Math.atan2(dv.y, len);
  16254. if (this.rotationQuaternion) {
  16255. BABYLON.Quaternion.RotationYawPitchRollToRef(yaw + yawCor, pitch + pitchCor, rollCor, this.rotationQuaternion);
  16256. }
  16257. else {
  16258. this.rotation.x = pitch + pitchCor;
  16259. this.rotation.y = yaw + yawCor;
  16260. this.rotation.z = rollCor;
  16261. }
  16262. return this;
  16263. };
  16264. /**
  16265. * Returns a new Vector3 what is the localAxis, expressed in the mesh local space, rotated like the mesh.
  16266. * This Vector3 is expressed in the World space.
  16267. */
  16268. TransformNode.prototype.getDirection = function (localAxis) {
  16269. var result = BABYLON.Vector3.Zero();
  16270. this.getDirectionToRef(localAxis, result);
  16271. return result;
  16272. };
  16273. /**
  16274. * Sets the Vector3 "result" as the rotated Vector3 "localAxis" in the same rotation than the mesh.
  16275. * localAxis is expressed in the mesh local space.
  16276. * result is computed in the Wordl space from the mesh World matrix.
  16277. * Returns the AbstractMesh.
  16278. */
  16279. TransformNode.prototype.getDirectionToRef = function (localAxis, result) {
  16280. BABYLON.Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result);
  16281. return this;
  16282. };
  16283. /**
  16284. * Sets a new pivot point to the current node
  16285. * @param point defines the new pivot point to use
  16286. * @param space defines if the point is in world or local space (local by default)
  16287. * @returns the current TransformNode
  16288. */
  16289. TransformNode.prototype.setPivotPoint = function (point, space) {
  16290. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  16291. if (this.getScene().getRenderId() == 0) {
  16292. this.computeWorldMatrix(true);
  16293. }
  16294. var wm = this.getWorldMatrix();
  16295. if (space == BABYLON.Space.WORLD) {
  16296. var tmat = BABYLON.Tmp.Matrix[0];
  16297. wm.invertToRef(tmat);
  16298. point = BABYLON.Vector3.TransformCoordinates(point, tmat);
  16299. }
  16300. return this.setPivotMatrix(BABYLON.Matrix.Translation(-point.x, -point.y, -point.z), true);
  16301. };
  16302. /**
  16303. * Returns a new Vector3 set with the mesh pivot point coordinates in the local space.
  16304. */
  16305. TransformNode.prototype.getPivotPoint = function () {
  16306. var point = BABYLON.Vector3.Zero();
  16307. this.getPivotPointToRef(point);
  16308. return point;
  16309. };
  16310. /**
  16311. * Sets the passed Vector3 "result" with the coordinates of the mesh pivot point in the local space.
  16312. * Returns the AbstractMesh.
  16313. */
  16314. TransformNode.prototype.getPivotPointToRef = function (result) {
  16315. result.x = -this._pivotMatrix.m[12];
  16316. result.y = -this._pivotMatrix.m[13];
  16317. result.z = -this._pivotMatrix.m[14];
  16318. return this;
  16319. };
  16320. /**
  16321. * Returns a new Vector3 set with the mesh pivot point World coordinates.
  16322. */
  16323. TransformNode.prototype.getAbsolutePivotPoint = function () {
  16324. var point = BABYLON.Vector3.Zero();
  16325. this.getAbsolutePivotPointToRef(point);
  16326. return point;
  16327. };
  16328. /**
  16329. * Sets the Vector3 "result" coordinates with the mesh pivot point World coordinates.
  16330. * Returns the AbstractMesh.
  16331. */
  16332. TransformNode.prototype.getAbsolutePivotPointToRef = function (result) {
  16333. result.x = this._pivotMatrix.m[12];
  16334. result.y = this._pivotMatrix.m[13];
  16335. result.z = this._pivotMatrix.m[14];
  16336. this.getPivotPointToRef(result);
  16337. BABYLON.Vector3.TransformCoordinatesToRef(result, this.getWorldMatrix(), result);
  16338. return this;
  16339. };
  16340. /**
  16341. * Defines the passed node as the parent of the current node.
  16342. * The node will remain exactly where it is and its position / rotation will be updated accordingly
  16343. * Returns the TransformNode.
  16344. */
  16345. TransformNode.prototype.setParent = function (node) {
  16346. if (node === null) {
  16347. var rotation = BABYLON.Tmp.Quaternion[0];
  16348. var position = BABYLON.Tmp.Vector3[0];
  16349. var scale = BABYLON.Tmp.Vector3[1];
  16350. if (this.parent && this.parent.computeWorldMatrix) {
  16351. this.parent.computeWorldMatrix(true);
  16352. }
  16353. this.computeWorldMatrix(true);
  16354. this.getWorldMatrix().decompose(scale, rotation, position);
  16355. if (this.rotationQuaternion) {
  16356. this.rotationQuaternion.copyFrom(rotation);
  16357. }
  16358. else {
  16359. rotation.toEulerAnglesToRef(this.rotation);
  16360. }
  16361. this.scaling.x = scale.x;
  16362. this.scaling.y = scale.y;
  16363. this.scaling.z = scale.z;
  16364. this.position.x = position.x;
  16365. this.position.y = position.y;
  16366. this.position.z = position.z;
  16367. }
  16368. else {
  16369. var rotation = BABYLON.Tmp.Quaternion[0];
  16370. var position = BABYLON.Tmp.Vector3[0];
  16371. var scale = BABYLON.Tmp.Vector3[1];
  16372. var diffMatrix = BABYLON.Tmp.Matrix[0];
  16373. var invParentMatrix = BABYLON.Tmp.Matrix[1];
  16374. this.computeWorldMatrix(true);
  16375. node.computeWorldMatrix(true);
  16376. node.getWorldMatrix().invertToRef(invParentMatrix);
  16377. this.getWorldMatrix().multiplyToRef(invParentMatrix, diffMatrix);
  16378. diffMatrix.decompose(scale, rotation, position);
  16379. if (this.rotationQuaternion) {
  16380. this.rotationQuaternion.copyFrom(rotation);
  16381. }
  16382. else {
  16383. rotation.toEulerAnglesToRef(this.rotation);
  16384. }
  16385. this.position.x = position.x;
  16386. this.position.y = position.y;
  16387. this.position.z = position.z;
  16388. this.scaling.x = scale.x;
  16389. this.scaling.y = scale.y;
  16390. this.scaling.z = scale.z;
  16391. }
  16392. this.parent = node;
  16393. return this;
  16394. };
  16395. Object.defineProperty(TransformNode.prototype, "nonUniformScaling", {
  16396. get: function () {
  16397. return this._nonUniformScaling;
  16398. },
  16399. enumerable: true,
  16400. configurable: true
  16401. });
  16402. TransformNode.prototype._updateNonUniformScalingState = function (value) {
  16403. if (this._nonUniformScaling === value) {
  16404. return false;
  16405. }
  16406. this._nonUniformScaling = true;
  16407. return true;
  16408. };
  16409. /**
  16410. * Attach the current TransformNode to another TransformNode associated with a bone
  16411. * @param bone Bone affecting the TransformNode
  16412. * @param affectedTransformNode TransformNode associated with the bone
  16413. */
  16414. TransformNode.prototype.attachToBone = function (bone, affectedTransformNode) {
  16415. this._transformToBoneReferal = affectedTransformNode;
  16416. this.parent = bone;
  16417. if (bone.getWorldMatrix().determinant() < 0) {
  16418. this.scalingDeterminant *= -1;
  16419. }
  16420. return this;
  16421. };
  16422. TransformNode.prototype.detachFromBone = function () {
  16423. if (!this.parent) {
  16424. return this;
  16425. }
  16426. if (this.parent.getWorldMatrix().determinant() < 0) {
  16427. this.scalingDeterminant *= -1;
  16428. }
  16429. this._transformToBoneReferal = null;
  16430. this.parent = null;
  16431. return this;
  16432. };
  16433. /**
  16434. * Rotates the mesh around the axis vector for the passed angle (amount) expressed in radians, in the given space.
  16435. * space (default LOCAL) can be either BABYLON.Space.LOCAL, either BABYLON.Space.WORLD.
  16436. * Note that the property `rotationQuaternion` is then automatically updated and the property `rotation` is set to (0,0,0) and no longer used.
  16437. * The passed axis is also normalized.
  16438. * Returns the AbstractMesh.
  16439. */
  16440. TransformNode.prototype.rotate = function (axis, amount, space) {
  16441. axis.normalize();
  16442. if (!this.rotationQuaternion) {
  16443. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  16444. this.rotation = BABYLON.Vector3.Zero();
  16445. }
  16446. var rotationQuaternion;
  16447. if (!space || space === BABYLON.Space.LOCAL) {
  16448. rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, BABYLON.AbstractMesh._rotationAxisCache);
  16449. this.rotationQuaternion.multiplyToRef(rotationQuaternion, this.rotationQuaternion);
  16450. }
  16451. else {
  16452. if (this.parent) {
  16453. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  16454. invertParentWorldMatrix.invert();
  16455. axis = BABYLON.Vector3.TransformNormal(axis, invertParentWorldMatrix);
  16456. }
  16457. rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, BABYLON.AbstractMesh._rotationAxisCache);
  16458. rotationQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  16459. }
  16460. return this;
  16461. };
  16462. /**
  16463. * Rotates the mesh around the axis vector for the passed angle (amount) expressed in radians, in world space.
  16464. * Note that the property `rotationQuaternion` is then automatically updated and the property `rotation` is set to (0,0,0) and no longer used.
  16465. * The passed axis is also normalized.
  16466. * Returns the AbstractMesh.
  16467. * Method is based on http://www.euclideanspace.com/maths/geometry/affine/aroundPoint/index.htm
  16468. */
  16469. TransformNode.prototype.rotateAround = function (point, axis, amount) {
  16470. axis.normalize();
  16471. if (!this.rotationQuaternion) {
  16472. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  16473. this.rotation.copyFromFloats(0, 0, 0);
  16474. }
  16475. point.subtractToRef(this.position, BABYLON.Tmp.Vector3[0]);
  16476. BABYLON.Matrix.TranslationToRef(BABYLON.Tmp.Vector3[0].x, BABYLON.Tmp.Vector3[0].y, BABYLON.Tmp.Vector3[0].z, BABYLON.Tmp.Matrix[0]);
  16477. BABYLON.Tmp.Matrix[0].invertToRef(BABYLON.Tmp.Matrix[2]);
  16478. BABYLON.Matrix.RotationAxisToRef(axis, amount, BABYLON.Tmp.Matrix[1]);
  16479. BABYLON.Tmp.Matrix[2].multiplyToRef(BABYLON.Tmp.Matrix[1], BABYLON.Tmp.Matrix[2]);
  16480. BABYLON.Tmp.Matrix[2].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[2]);
  16481. BABYLON.Tmp.Matrix[2].decompose(BABYLON.Tmp.Vector3[0], BABYLON.Tmp.Quaternion[0], BABYLON.Tmp.Vector3[1]);
  16482. this.position.addInPlace(BABYLON.Tmp.Vector3[1]);
  16483. BABYLON.Tmp.Quaternion[0].multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  16484. return this;
  16485. };
  16486. /**
  16487. * Translates the mesh along the axis vector for the passed distance in the given space.
  16488. * space (default LOCAL) can be either BABYLON.Space.LOCAL, either BABYLON.Space.WORLD.
  16489. * Returns the AbstractMesh.
  16490. */
  16491. TransformNode.prototype.translate = function (axis, distance, space) {
  16492. var displacementVector = axis.scale(distance);
  16493. if (!space || space === BABYLON.Space.LOCAL) {
  16494. var tempV3 = this.getPositionExpressedInLocalSpace().add(displacementVector);
  16495. this.setPositionWithLocalVector(tempV3);
  16496. }
  16497. else {
  16498. this.setAbsolutePosition(this.getAbsolutePosition().add(displacementVector));
  16499. }
  16500. return this;
  16501. };
  16502. /**
  16503. * Adds a rotation step to the mesh current rotation.
  16504. * x, y, z are Euler angles expressed in radians.
  16505. * This methods updates the current mesh rotation, either mesh.rotation, either mesh.rotationQuaternion if it's set.
  16506. * This means this rotation is made in the mesh local space only.
  16507. * It's useful to set a custom rotation order different from the BJS standard one YXZ.
  16508. * Example : this rotates the mesh first around its local X axis, then around its local Z axis, finally around its local Y axis.
  16509. * ```javascript
  16510. * mesh.addRotation(x1, 0, 0).addRotation(0, 0, z2).addRotation(0, 0, y3);
  16511. * ```
  16512. * Note that `addRotation()` accumulates the passed rotation values to the current ones and computes the .rotation or .rotationQuaternion updated values.
  16513. * Under the hood, only quaternions are used. So it's a little faster is you use .rotationQuaternion because it doesn't need to translate them back to Euler angles.
  16514. * Returns the AbstractMesh.
  16515. */
  16516. TransformNode.prototype.addRotation = function (x, y, z) {
  16517. var rotationQuaternion;
  16518. if (this.rotationQuaternion) {
  16519. rotationQuaternion = this.rotationQuaternion;
  16520. }
  16521. else {
  16522. rotationQuaternion = BABYLON.Tmp.Quaternion[1];
  16523. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, rotationQuaternion);
  16524. }
  16525. var accumulation = BABYLON.Tmp.Quaternion[0];
  16526. BABYLON.Quaternion.RotationYawPitchRollToRef(y, x, z, accumulation);
  16527. rotationQuaternion.multiplyInPlace(accumulation);
  16528. if (!this.rotationQuaternion) {
  16529. rotationQuaternion.toEulerAnglesToRef(this.rotation);
  16530. }
  16531. return this;
  16532. };
  16533. /**
  16534. * Computes the mesh World matrix and returns it.
  16535. * If the mesh world matrix is frozen, this computation does nothing more than returning the last frozen values.
  16536. * If the parameter `force` is let to `false` (default), the current cached World matrix is returned.
  16537. * If the parameter `force`is set to `true`, the actual computation is done.
  16538. * Returns the mesh World Matrix.
  16539. */
  16540. TransformNode.prototype.computeWorldMatrix = function (force) {
  16541. if (this._isWorldMatrixFrozen) {
  16542. return this._worldMatrix;
  16543. }
  16544. if (!force && this.isSynchronized(true)) {
  16545. return this._worldMatrix;
  16546. }
  16547. this._cache.position.copyFrom(this.position);
  16548. this._cache.scaling.copyFrom(this.scaling);
  16549. this._cache.pivotMatrixUpdated = false;
  16550. this._cache.billboardMode = this.billboardMode;
  16551. this._currentRenderId = this.getScene().getRenderId();
  16552. this._isDirty = false;
  16553. // Scaling
  16554. BABYLON.Matrix.ScalingToRef(this.scaling.x * this.scalingDeterminant, this.scaling.y * this.scalingDeterminant, this.scaling.z * this.scalingDeterminant, BABYLON.Tmp.Matrix[1]);
  16555. // Rotation
  16556. //rotate, if quaternion is set and rotation was used
  16557. if (this.rotationQuaternion) {
  16558. var len = this.rotation.length();
  16559. if (len) {
  16560. this.rotationQuaternion.multiplyInPlace(BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z));
  16561. this.rotation.copyFromFloats(0, 0, 0);
  16562. }
  16563. }
  16564. if (this.rotationQuaternion) {
  16565. this.rotationQuaternion.toRotationMatrix(BABYLON.Tmp.Matrix[0]);
  16566. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  16567. }
  16568. else {
  16569. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, BABYLON.Tmp.Matrix[0]);
  16570. this._cache.rotation.copyFrom(this.rotation);
  16571. }
  16572. // Translation
  16573. var camera = this.getScene().activeCamera;
  16574. if (this.infiniteDistance && !this.parent && camera) {
  16575. var cameraWorldMatrix = camera.getWorldMatrix();
  16576. var cameraGlobalPosition = new BABYLON.Vector3(cameraWorldMatrix.m[12], cameraWorldMatrix.m[13], cameraWorldMatrix.m[14]);
  16577. BABYLON.Matrix.TranslationToRef(this.position.x + cameraGlobalPosition.x, this.position.y + cameraGlobalPosition.y, this.position.z + cameraGlobalPosition.z, BABYLON.Tmp.Matrix[2]);
  16578. }
  16579. else {
  16580. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, BABYLON.Tmp.Matrix[2]);
  16581. }
  16582. // Composing transformations
  16583. this._pivotMatrix.multiplyToRef(BABYLON.Tmp.Matrix[1], BABYLON.Tmp.Matrix[4]);
  16584. BABYLON.Tmp.Matrix[4].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  16585. // Billboarding (testing PG:http://www.babylonjs-playground.com/#UJEIL#13)
  16586. if (this.billboardMode !== BABYLON.AbstractMesh.BILLBOARDMODE_NONE && camera) {
  16587. if ((this.billboardMode & BABYLON.AbstractMesh.BILLBOARDMODE_ALL) !== BABYLON.AbstractMesh.BILLBOARDMODE_ALL) {
  16588. // Need to decompose each rotation here
  16589. var currentPosition = BABYLON.Tmp.Vector3[3];
  16590. if (this.parent && this.parent.getWorldMatrix) {
  16591. if (this._transformToBoneReferal) {
  16592. this.parent.getWorldMatrix().multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  16593. BABYLON.Vector3.TransformCoordinatesToRef(this.position, BABYLON.Tmp.Matrix[6], currentPosition);
  16594. }
  16595. else {
  16596. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), currentPosition);
  16597. }
  16598. }
  16599. else {
  16600. currentPosition.copyFrom(this.position);
  16601. }
  16602. currentPosition.subtractInPlace(camera.globalPosition);
  16603. var finalEuler = BABYLON.Tmp.Vector3[4].copyFromFloats(0, 0, 0);
  16604. if ((this.billboardMode & BABYLON.AbstractMesh.BILLBOARDMODE_X) === BABYLON.AbstractMesh.BILLBOARDMODE_X) {
  16605. finalEuler.x = Math.atan2(-currentPosition.y, currentPosition.z);
  16606. }
  16607. if ((this.billboardMode & BABYLON.AbstractMesh.BILLBOARDMODE_Y) === BABYLON.AbstractMesh.BILLBOARDMODE_Y) {
  16608. finalEuler.y = Math.atan2(currentPosition.x, currentPosition.z);
  16609. }
  16610. if ((this.billboardMode & BABYLON.AbstractMesh.BILLBOARDMODE_Z) === BABYLON.AbstractMesh.BILLBOARDMODE_Z) {
  16611. finalEuler.z = Math.atan2(currentPosition.y, currentPosition.x);
  16612. }
  16613. BABYLON.Matrix.RotationYawPitchRollToRef(finalEuler.y, finalEuler.x, finalEuler.z, BABYLON.Tmp.Matrix[0]);
  16614. }
  16615. else {
  16616. BABYLON.Tmp.Matrix[1].copyFrom(camera.getViewMatrix());
  16617. BABYLON.Tmp.Matrix[1].setTranslationFromFloats(0, 0, 0);
  16618. BABYLON.Tmp.Matrix[1].invertToRef(BABYLON.Tmp.Matrix[0]);
  16619. }
  16620. BABYLON.Tmp.Matrix[1].copyFrom(BABYLON.Tmp.Matrix[5]);
  16621. BABYLON.Tmp.Matrix[1].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  16622. }
  16623. // Local world
  16624. BABYLON.Tmp.Matrix[5].multiplyToRef(BABYLON.Tmp.Matrix[2], this._localWorld);
  16625. // Parent
  16626. if (this.parent && this.parent.getWorldMatrix) {
  16627. if (this.billboardMode !== BABYLON.AbstractMesh.BILLBOARDMODE_NONE) {
  16628. if (this._transformToBoneReferal) {
  16629. this.parent.getWorldMatrix().multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  16630. BABYLON.Tmp.Matrix[5].copyFrom(BABYLON.Tmp.Matrix[6]);
  16631. }
  16632. else {
  16633. BABYLON.Tmp.Matrix[5].copyFrom(this.parent.getWorldMatrix());
  16634. }
  16635. this._localWorld.getTranslationToRef(BABYLON.Tmp.Vector3[5]);
  16636. BABYLON.Vector3.TransformCoordinatesToRef(BABYLON.Tmp.Vector3[5], BABYLON.Tmp.Matrix[5], BABYLON.Tmp.Vector3[5]);
  16637. this._worldMatrix.copyFrom(this._localWorld);
  16638. this._worldMatrix.setTranslation(BABYLON.Tmp.Vector3[5]);
  16639. }
  16640. else {
  16641. if (this._transformToBoneReferal) {
  16642. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  16643. BABYLON.Tmp.Matrix[6].multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), this._worldMatrix);
  16644. }
  16645. else {
  16646. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), this._worldMatrix);
  16647. }
  16648. }
  16649. this._markSyncedWithParent();
  16650. }
  16651. else {
  16652. this._worldMatrix.copyFrom(this._localWorld);
  16653. }
  16654. // Post multiply inverse of pivotMatrix
  16655. if (this._postMultiplyPivotMatrix) {
  16656. this._worldMatrix.multiplyToRef(this._pivotMatrixInverse, this._worldMatrix);
  16657. }
  16658. // Normal matrix
  16659. if (this.scaling.isNonUniform) {
  16660. this._updateNonUniformScalingState(true);
  16661. }
  16662. else if (this.parent && this.parent._nonUniformScaling) {
  16663. this._updateNonUniformScalingState(this.parent._nonUniformScaling);
  16664. }
  16665. else {
  16666. this._updateNonUniformScalingState(false);
  16667. }
  16668. this._afterComputeWorldMatrix();
  16669. // Absolute position
  16670. this._absolutePosition.copyFromFloats(this._worldMatrix.m[12], this._worldMatrix.m[13], this._worldMatrix.m[14]);
  16671. // Callbacks
  16672. this.onAfterWorldMatrixUpdateObservable.notifyObservers(this);
  16673. if (!this._poseMatrix) {
  16674. this._poseMatrix = BABYLON.Matrix.Invert(this._worldMatrix);
  16675. }
  16676. // Cache the determinant
  16677. this._worldMatrixDeterminant = this._worldMatrix.determinant();
  16678. return this._worldMatrix;
  16679. };
  16680. TransformNode.prototype._afterComputeWorldMatrix = function () {
  16681. };
  16682. /**
  16683. * If you'd like to be called back after the mesh position, rotation or scaling has been updated.
  16684. * @param func: callback function to add
  16685. *
  16686. * Returns the TransformNode.
  16687. */
  16688. TransformNode.prototype.registerAfterWorldMatrixUpdate = function (func) {
  16689. this.onAfterWorldMatrixUpdateObservable.add(func);
  16690. return this;
  16691. };
  16692. /**
  16693. * Removes a registered callback function.
  16694. * Returns the TransformNode.
  16695. */
  16696. TransformNode.prototype.unregisterAfterWorldMatrixUpdate = function (func) {
  16697. this.onAfterWorldMatrixUpdateObservable.removeCallback(func);
  16698. return this;
  16699. };
  16700. /**
  16701. * Clone the current transform node
  16702. * Returns the new transform node
  16703. * @param name Name of the new clone
  16704. * @param newParent New parent for the clone
  16705. * @param doNotCloneChildren Do not clone children hierarchy
  16706. */
  16707. TransformNode.prototype.clone = function (name, newParent, doNotCloneChildren) {
  16708. var _this = this;
  16709. var result = BABYLON.SerializationHelper.Clone(function () { return new TransformNode(name, _this.getScene()); }, this);
  16710. result.name = name;
  16711. result.id = name;
  16712. if (newParent) {
  16713. result.parent = newParent;
  16714. }
  16715. if (!doNotCloneChildren) {
  16716. // Children
  16717. var directDescendants = this.getDescendants(true);
  16718. for (var index = 0; index < directDescendants.length; index++) {
  16719. var child = directDescendants[index];
  16720. if (child.clone) {
  16721. child.clone(name + "." + child.name, result);
  16722. }
  16723. }
  16724. }
  16725. return result;
  16726. };
  16727. TransformNode.prototype.serialize = function (currentSerializationObject) {
  16728. var serializationObject = BABYLON.SerializationHelper.Serialize(this, currentSerializationObject);
  16729. serializationObject.type = this.getClassName();
  16730. // Parent
  16731. if (this.parent) {
  16732. serializationObject.parentId = this.parent.id;
  16733. }
  16734. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  16735. serializationObject.tags = BABYLON.Tags.GetTags(this);
  16736. }
  16737. serializationObject.localMatrix = this.getPivotMatrix().asArray();
  16738. serializationObject.isEnabled = this.isEnabled();
  16739. // Parent
  16740. if (this.parent) {
  16741. serializationObject.parentId = this.parent.id;
  16742. }
  16743. return serializationObject;
  16744. };
  16745. // Statics
  16746. /**
  16747. * Returns a new TransformNode object parsed from the source provided.
  16748. * The parameter `parsedMesh` is the source.
  16749. * The parameter `rootUrl` is a string, it's the root URL to prefix the `delayLoadingFile` property with
  16750. */
  16751. TransformNode.Parse = function (parsedTransformNode, scene, rootUrl) {
  16752. var transformNode = BABYLON.SerializationHelper.Parse(function () { return new TransformNode(parsedTransformNode.name, scene); }, parsedTransformNode, scene, rootUrl);
  16753. if (BABYLON.Tags) {
  16754. BABYLON.Tags.AddTagsTo(transformNode, parsedTransformNode.tags);
  16755. }
  16756. if (parsedTransformNode.localMatrix) {
  16757. transformNode.setPreTransformMatrix(BABYLON.Matrix.FromArray(parsedTransformNode.localMatrix));
  16758. }
  16759. else if (parsedTransformNode.pivotMatrix) {
  16760. transformNode.setPivotMatrix(BABYLON.Matrix.FromArray(parsedTransformNode.pivotMatrix));
  16761. }
  16762. transformNode.setEnabled(parsedTransformNode.isEnabled);
  16763. // Parent
  16764. if (parsedTransformNode.parentId) {
  16765. transformNode._waitingParentId = parsedTransformNode.parentId;
  16766. }
  16767. return transformNode;
  16768. };
  16769. /**
  16770. * Disposes the TransformNode.
  16771. * By default, all the children are also disposed unless the parameter `doNotRecurse` is set to `true`.
  16772. * Returns nothing.
  16773. */
  16774. TransformNode.prototype.dispose = function (doNotRecurse) {
  16775. // Animations
  16776. this.getScene().stopAnimation(this);
  16777. // Remove from scene
  16778. this.getScene().removeTransformNode(this);
  16779. if (!doNotRecurse) {
  16780. // Children
  16781. var objects = this.getDescendants(true);
  16782. for (var index = 0; index < objects.length; index++) {
  16783. objects[index].dispose();
  16784. }
  16785. }
  16786. else {
  16787. var childMeshes = this.getChildMeshes(true);
  16788. for (index = 0; index < childMeshes.length; index++) {
  16789. var child = childMeshes[index];
  16790. child.parent = null;
  16791. child.computeWorldMatrix(true);
  16792. }
  16793. }
  16794. this.onAfterWorldMatrixUpdateObservable.clear();
  16795. _super.prototype.dispose.call(this);
  16796. };
  16797. // Statics
  16798. TransformNode.BILLBOARDMODE_NONE = 0;
  16799. TransformNode.BILLBOARDMODE_X = 1;
  16800. TransformNode.BILLBOARDMODE_Y = 2;
  16801. TransformNode.BILLBOARDMODE_Z = 4;
  16802. TransformNode.BILLBOARDMODE_ALL = 7;
  16803. TransformNode._lookAtVectorCache = new BABYLON.Vector3(0, 0, 0);
  16804. TransformNode._rotationAxisCache = new BABYLON.Quaternion();
  16805. __decorate([
  16806. BABYLON.serializeAsVector3()
  16807. ], TransformNode.prototype, "_rotation", void 0);
  16808. __decorate([
  16809. BABYLON.serializeAsQuaternion()
  16810. ], TransformNode.prototype, "_rotationQuaternion", void 0);
  16811. __decorate([
  16812. BABYLON.serializeAsVector3()
  16813. ], TransformNode.prototype, "_scaling", void 0);
  16814. __decorate([
  16815. BABYLON.serialize()
  16816. ], TransformNode.prototype, "billboardMode", void 0);
  16817. __decorate([
  16818. BABYLON.serialize()
  16819. ], TransformNode.prototype, "scalingDeterminant", void 0);
  16820. __decorate([
  16821. BABYLON.serialize()
  16822. ], TransformNode.prototype, "infiniteDistance", void 0);
  16823. __decorate([
  16824. BABYLON.serializeAsVector3()
  16825. ], TransformNode.prototype, "position", void 0);
  16826. return TransformNode;
  16827. }(BABYLON.Node));
  16828. BABYLON.TransformNode = TransformNode;
  16829. })(BABYLON || (BABYLON = {}));
  16830. //# sourceMappingURL=babylon.transformNode.js.map
  16831. var BABYLON;
  16832. (function (BABYLON) {
  16833. var AbstractMesh = /** @class */ (function (_super) {
  16834. __extends(AbstractMesh, _super);
  16835. // Constructor
  16836. function AbstractMesh(name, scene) {
  16837. if (scene === void 0) { scene = null; }
  16838. var _this = _super.call(this, name, scene, false) || this;
  16839. _this._facetNb = 0; // facet number
  16840. _this._partitioningSubdivisions = 10; // number of subdivisions per axis in the partioning space
  16841. _this._partitioningBBoxRatio = 1.01; // the partioning array space is by default 1% bigger than the bounding box
  16842. _this._facetDataEnabled = false; // is the facet data feature enabled on this mesh ?
  16843. _this._facetParameters = {}; // keep a reference to the object parameters to avoid memory re-allocation
  16844. _this._bbSize = BABYLON.Vector3.Zero(); // bbox size approximated for facet data
  16845. _this._subDiv = {
  16846. max: 1,
  16847. X: 1,
  16848. Y: 1,
  16849. Z: 1
  16850. };
  16851. _this._facetDepthSort = false; // is the facet depth sort to be computed
  16852. _this._facetDepthSortEnabled = false; // is the facet depth sort initialized
  16853. // Events
  16854. /**
  16855. * An event triggered when this mesh collides with another one
  16856. * @type {BABYLON.Observable}
  16857. */
  16858. _this.onCollideObservable = new BABYLON.Observable();
  16859. /**
  16860. * An event triggered when the collision's position changes
  16861. * @type {BABYLON.Observable}
  16862. */
  16863. _this.onCollisionPositionChangeObservable = new BABYLON.Observable();
  16864. /**
  16865. * An event triggered when material is changed
  16866. * @type {BABYLON.Observable}
  16867. */
  16868. _this.onMaterialChangedObservable = new BABYLON.Observable();
  16869. // Properties
  16870. _this.definedFacingForward = true; // orientation for POV movement & rotation
  16871. /**
  16872. * This property determines the type of occlusion query algorithm to run in WebGl, you can use:
  16873. * AbstractMesh.OCCLUSION_ALGORITHM_TYPE_ACCURATE which is mapped to GL_ANY_SAMPLES_PASSED.
  16874. * or
  16875. * AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE (Default Value) which is mapped to GL_ANY_SAMPLES_PASSED_CONSERVATIVE which is a false positive algorithm that is faster than GL_ANY_SAMPLES_PASSED but less accurate.
  16876. * for more info check WebGl documentations
  16877. */
  16878. _this.occlusionQueryAlgorithmType = AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE;
  16879. /**
  16880. * This property is responsible for starting the occlusion query within the Mesh or not, this property is also used to determine what should happen when the occlusionRetryCount is reached. It has supports 3 values:
  16881. * OCCLUSION_TYPE_NONE (Default Value): this option means no occlusion query whith the Mesh.
  16882. * OCCLUSION_TYPE_OPTIMISTIC: this option is means use occlusion query and if occlusionRetryCount is reached and the query is broken show the mesh.
  16883. * OCCLUSION_TYPE_STRICT: this option is means use occlusion query and if occlusionRetryCount is reached and the query is broken restore the last state of the mesh occlusion if the mesh was visible then show the mesh if was hidden then hide don't show.
  16884. */
  16885. _this.occlusionType = AbstractMesh.OCCLUSION_TYPE_NONE;
  16886. /**
  16887. * This number indicates the number of allowed retries before stop the occlusion query, this is useful if the occlusion query is taking long time before to the query result is retireved, the query result indicates if the object is visible within the scene or not and based on that Babylon.Js engine decideds to show or hide the object.
  16888. * The default value is -1 which means don't break the query and wait till the result.
  16889. */
  16890. _this.occlusionRetryCount = -1;
  16891. _this._occlusionInternalRetryCounter = 0;
  16892. _this._isOccluded = false;
  16893. _this._isOcclusionQueryInProgress = false;
  16894. _this._visibility = 1.0;
  16895. _this.alphaIndex = Number.MAX_VALUE;
  16896. _this.isVisible = true;
  16897. _this.isPickable = true;
  16898. _this.showBoundingBox = false;
  16899. _this.showSubMeshesBoundingBox = false;
  16900. _this.isBlocker = false;
  16901. _this.enablePointerMoveEvents = false;
  16902. _this.renderingGroupId = 0;
  16903. _this._receiveShadows = false;
  16904. _this.renderOutline = false;
  16905. _this.outlineColor = BABYLON.Color3.Red();
  16906. _this.outlineWidth = 0.02;
  16907. _this.renderOverlay = false;
  16908. _this.overlayColor = BABYLON.Color3.Red();
  16909. _this.overlayAlpha = 0.5;
  16910. _this._hasVertexAlpha = false;
  16911. _this._useVertexColors = true;
  16912. _this._computeBonesUsingShaders = true;
  16913. _this._numBoneInfluencers = 4;
  16914. _this._applyFog = true;
  16915. _this.useOctreeForRenderingSelection = true;
  16916. _this.useOctreeForPicking = true;
  16917. _this.useOctreeForCollisions = true;
  16918. _this._layerMask = 0x0FFFFFFF;
  16919. /**
  16920. * True if the mesh must be rendered in any case.
  16921. */
  16922. _this.alwaysSelectAsActiveMesh = false;
  16923. /**
  16924. * This scene's action manager
  16925. * @type {BABYLON.ActionManager}
  16926. */
  16927. _this.actionManager = null;
  16928. // Physics
  16929. _this.physicsImpostor = null;
  16930. // Collisions
  16931. _this._checkCollisions = false;
  16932. _this._collisionMask = -1;
  16933. _this._collisionGroup = -1;
  16934. _this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  16935. _this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  16936. _this._oldPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  16937. _this._diffPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  16938. // Edges
  16939. _this.edgesWidth = 1;
  16940. _this.edgesColor = new BABYLON.Color4(1, 0, 0, 1);
  16941. // Cache
  16942. _this._collisionsTransformMatrix = BABYLON.Matrix.Zero();
  16943. _this._collisionsScalingMatrix = BABYLON.Matrix.Zero();
  16944. _this._renderId = 0;
  16945. _this._intersectionsInProgress = new Array();
  16946. _this._unIndexed = false;
  16947. _this._lightSources = new Array();
  16948. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  16949. if (collidedMesh === void 0) { collidedMesh = null; }
  16950. //TODO move this to the collision coordinator!
  16951. if (_this.getScene().workerCollisions)
  16952. newPosition.multiplyInPlace(_this._collider._radius);
  16953. newPosition.subtractToRef(_this._oldPositionForCollisions, _this._diffPositionForCollisions);
  16954. if (_this._diffPositionForCollisions.length() > BABYLON.Engine.CollisionsEpsilon) {
  16955. _this.position.addInPlace(_this._diffPositionForCollisions);
  16956. }
  16957. if (collidedMesh) {
  16958. _this.onCollideObservable.notifyObservers(collidedMesh);
  16959. }
  16960. _this.onCollisionPositionChangeObservable.notifyObservers(_this.position);
  16961. };
  16962. _this.getScene().addMesh(_this);
  16963. _this._resyncLightSources();
  16964. return _this;
  16965. }
  16966. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_NONE", {
  16967. get: function () {
  16968. return BABYLON.TransformNode.BILLBOARDMODE_NONE;
  16969. },
  16970. enumerable: true,
  16971. configurable: true
  16972. });
  16973. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_X", {
  16974. get: function () {
  16975. return BABYLON.TransformNode.BILLBOARDMODE_X;
  16976. },
  16977. enumerable: true,
  16978. configurable: true
  16979. });
  16980. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Y", {
  16981. get: function () {
  16982. return BABYLON.TransformNode.BILLBOARDMODE_Y;
  16983. },
  16984. enumerable: true,
  16985. configurable: true
  16986. });
  16987. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Z", {
  16988. get: function () {
  16989. return BABYLON.TransformNode.BILLBOARDMODE_Z;
  16990. },
  16991. enumerable: true,
  16992. configurable: true
  16993. });
  16994. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_ALL", {
  16995. get: function () {
  16996. return BABYLON.TransformNode.BILLBOARDMODE_ALL;
  16997. },
  16998. enumerable: true,
  16999. configurable: true
  17000. });
  17001. Object.defineProperty(AbstractMesh.prototype, "facetNb", {
  17002. /**
  17003. * Read-only : the number of facets in the mesh
  17004. */
  17005. get: function () {
  17006. return this._facetNb;
  17007. },
  17008. enumerable: true,
  17009. configurable: true
  17010. });
  17011. Object.defineProperty(AbstractMesh.prototype, "partitioningSubdivisions", {
  17012. /**
  17013. * The number (integer) of subdivisions per axis in the partioning space
  17014. */
  17015. get: function () {
  17016. return this._partitioningSubdivisions;
  17017. },
  17018. set: function (nb) {
  17019. this._partitioningSubdivisions = nb;
  17020. },
  17021. enumerable: true,
  17022. configurable: true
  17023. });
  17024. Object.defineProperty(AbstractMesh.prototype, "partitioningBBoxRatio", {
  17025. /**
  17026. * The ratio (float) to apply to the bouding box size to set to the partioning space.
  17027. * Ex : 1.01 (default) the partioning space is 1% bigger than the bounding box.
  17028. */
  17029. get: function () {
  17030. return this._partitioningBBoxRatio;
  17031. },
  17032. set: function (ratio) {
  17033. this._partitioningBBoxRatio = ratio;
  17034. },
  17035. enumerable: true,
  17036. configurable: true
  17037. });
  17038. Object.defineProperty(AbstractMesh.prototype, "mustDepthSortFacets", {
  17039. /**
  17040. * Boolean : must the facet be depth sorted on next call to `updateFacetData()` ?
  17041. * Works only for updatable meshes.
  17042. * Doesn't work with multi-materials.
  17043. */
  17044. get: function () {
  17045. return this._facetDepthSort;
  17046. },
  17047. set: function (sort) {
  17048. this._facetDepthSort = sort;
  17049. },
  17050. enumerable: true,
  17051. configurable: true
  17052. });
  17053. Object.defineProperty(AbstractMesh.prototype, "facetDepthSortFrom", {
  17054. /**
  17055. * The location (Vector3) where the facet depth sort must be computed from.
  17056. * By default, the active camera position.
  17057. * Used only when facet depth sort is enabled.
  17058. */
  17059. get: function () {
  17060. return this._facetDepthSortFrom;
  17061. },
  17062. set: function (location) {
  17063. this._facetDepthSortFrom = location;
  17064. },
  17065. enumerable: true,
  17066. configurable: true
  17067. });
  17068. Object.defineProperty(AbstractMesh.prototype, "isFacetDataEnabled", {
  17069. /**
  17070. * Read-only boolean : is the feature facetData enabled ?
  17071. */
  17072. get: function () {
  17073. return this._facetDataEnabled;
  17074. },
  17075. enumerable: true,
  17076. configurable: true
  17077. });
  17078. AbstractMesh.prototype._updateNonUniformScalingState = function (value) {
  17079. if (!_super.prototype._updateNonUniformScalingState.call(this, value)) {
  17080. return false;
  17081. }
  17082. this._markSubMeshesAsMiscDirty();
  17083. return true;
  17084. };
  17085. Object.defineProperty(AbstractMesh.prototype, "onCollide", {
  17086. set: function (callback) {
  17087. if (this._onCollideObserver) {
  17088. this.onCollideObservable.remove(this._onCollideObserver);
  17089. }
  17090. this._onCollideObserver = this.onCollideObservable.add(callback);
  17091. },
  17092. enumerable: true,
  17093. configurable: true
  17094. });
  17095. Object.defineProperty(AbstractMesh.prototype, "onCollisionPositionChange", {
  17096. set: function (callback) {
  17097. if (this._onCollisionPositionChangeObserver) {
  17098. this.onCollisionPositionChangeObservable.remove(this._onCollisionPositionChangeObserver);
  17099. }
  17100. this._onCollisionPositionChangeObserver = this.onCollisionPositionChangeObservable.add(callback);
  17101. },
  17102. enumerable: true,
  17103. configurable: true
  17104. });
  17105. Object.defineProperty(AbstractMesh.prototype, "isOccluded", {
  17106. /**
  17107. * Property isOccluded : Gets or sets whether the mesh is occluded or not, it is used also to set the intial state of the mesh to be occluded or not.
  17108. */
  17109. get: function () {
  17110. return this._isOccluded;
  17111. },
  17112. set: function (value) {
  17113. this._isOccluded = value;
  17114. },
  17115. enumerable: true,
  17116. configurable: true
  17117. });
  17118. Object.defineProperty(AbstractMesh.prototype, "isOcclusionQueryInProgress", {
  17119. /**
  17120. * Flag to check the progress status of the query
  17121. */
  17122. get: function () {
  17123. return this._isOcclusionQueryInProgress;
  17124. },
  17125. enumerable: true,
  17126. configurable: true
  17127. });
  17128. Object.defineProperty(AbstractMesh.prototype, "visibility", {
  17129. /**
  17130. * Gets or sets mesh visibility between 0 and 1 (defult is 1)
  17131. */
  17132. get: function () {
  17133. return this._visibility;
  17134. },
  17135. /**
  17136. * Gets or sets mesh visibility between 0 and 1 (defult is 1)
  17137. */
  17138. set: function (value) {
  17139. if (this._visibility === value) {
  17140. return;
  17141. }
  17142. this._visibility = value;
  17143. this._markSubMeshesAsMiscDirty();
  17144. },
  17145. enumerable: true,
  17146. configurable: true
  17147. });
  17148. Object.defineProperty(AbstractMesh.prototype, "material", {
  17149. get: function () {
  17150. return this._material;
  17151. },
  17152. set: function (value) {
  17153. if (this._material === value) {
  17154. return;
  17155. }
  17156. this._material = value;
  17157. if (this.onMaterialChangedObservable.hasObservers) {
  17158. this.onMaterialChangedObservable.notifyObservers(this);
  17159. }
  17160. if (!this.subMeshes) {
  17161. return;
  17162. }
  17163. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  17164. var subMesh = _a[_i];
  17165. subMesh.setEffect(null);
  17166. }
  17167. },
  17168. enumerable: true,
  17169. configurable: true
  17170. });
  17171. Object.defineProperty(AbstractMesh.prototype, "receiveShadows", {
  17172. get: function () {
  17173. return this._receiveShadows;
  17174. },
  17175. set: function (value) {
  17176. if (this._receiveShadows === value) {
  17177. return;
  17178. }
  17179. this._receiveShadows = value;
  17180. this._markSubMeshesAsLightDirty();
  17181. },
  17182. enumerable: true,
  17183. configurable: true
  17184. });
  17185. Object.defineProperty(AbstractMesh.prototype, "hasVertexAlpha", {
  17186. get: function () {
  17187. return this._hasVertexAlpha;
  17188. },
  17189. set: function (value) {
  17190. if (this._hasVertexAlpha === value) {
  17191. return;
  17192. }
  17193. this._hasVertexAlpha = value;
  17194. this._markSubMeshesAsAttributesDirty();
  17195. this._markSubMeshesAsMiscDirty();
  17196. },
  17197. enumerable: true,
  17198. configurable: true
  17199. });
  17200. Object.defineProperty(AbstractMesh.prototype, "useVertexColors", {
  17201. get: function () {
  17202. return this._useVertexColors;
  17203. },
  17204. set: function (value) {
  17205. if (this._useVertexColors === value) {
  17206. return;
  17207. }
  17208. this._useVertexColors = value;
  17209. this._markSubMeshesAsAttributesDirty();
  17210. },
  17211. enumerable: true,
  17212. configurable: true
  17213. });
  17214. Object.defineProperty(AbstractMesh.prototype, "computeBonesUsingShaders", {
  17215. get: function () {
  17216. return this._computeBonesUsingShaders;
  17217. },
  17218. set: function (value) {
  17219. if (this._computeBonesUsingShaders === value) {
  17220. return;
  17221. }
  17222. this._computeBonesUsingShaders = value;
  17223. this._markSubMeshesAsAttributesDirty();
  17224. },
  17225. enumerable: true,
  17226. configurable: true
  17227. });
  17228. Object.defineProperty(AbstractMesh.prototype, "numBoneInfluencers", {
  17229. get: function () {
  17230. return this._numBoneInfluencers;
  17231. },
  17232. set: function (value) {
  17233. if (this._numBoneInfluencers === value) {
  17234. return;
  17235. }
  17236. this._numBoneInfluencers = value;
  17237. this._markSubMeshesAsAttributesDirty();
  17238. },
  17239. enumerable: true,
  17240. configurable: true
  17241. });
  17242. Object.defineProperty(AbstractMesh.prototype, "applyFog", {
  17243. get: function () {
  17244. return this._applyFog;
  17245. },
  17246. set: function (value) {
  17247. if (this._applyFog === value) {
  17248. return;
  17249. }
  17250. this._applyFog = value;
  17251. this._markSubMeshesAsMiscDirty();
  17252. },
  17253. enumerable: true,
  17254. configurable: true
  17255. });
  17256. Object.defineProperty(AbstractMesh.prototype, "layerMask", {
  17257. get: function () {
  17258. return this._layerMask;
  17259. },
  17260. set: function (value) {
  17261. if (value === this._layerMask) {
  17262. return;
  17263. }
  17264. this._layerMask = value;
  17265. this._resyncLightSources();
  17266. },
  17267. enumerable: true,
  17268. configurable: true
  17269. });
  17270. Object.defineProperty(AbstractMesh.prototype, "collisionMask", {
  17271. get: function () {
  17272. return this._collisionMask;
  17273. },
  17274. set: function (mask) {
  17275. this._collisionMask = !isNaN(mask) ? mask : -1;
  17276. },
  17277. enumerable: true,
  17278. configurable: true
  17279. });
  17280. Object.defineProperty(AbstractMesh.prototype, "collisionGroup", {
  17281. get: function () {
  17282. return this._collisionGroup;
  17283. },
  17284. set: function (mask) {
  17285. this._collisionGroup = !isNaN(mask) ? mask : -1;
  17286. },
  17287. enumerable: true,
  17288. configurable: true
  17289. });
  17290. Object.defineProperty(AbstractMesh.prototype, "_positions", {
  17291. get: function () {
  17292. return null;
  17293. },
  17294. enumerable: true,
  17295. configurable: true
  17296. });
  17297. Object.defineProperty(AbstractMesh.prototype, "skeleton", {
  17298. get: function () {
  17299. return this._skeleton;
  17300. },
  17301. set: function (value) {
  17302. if (this._skeleton && this._skeleton.needInitialSkinMatrix) {
  17303. this._skeleton._unregisterMeshWithPoseMatrix(this);
  17304. }
  17305. if (value && value.needInitialSkinMatrix) {
  17306. value._registerMeshWithPoseMatrix(this);
  17307. }
  17308. this._skeleton = value;
  17309. if (!this._skeleton) {
  17310. this._bonesTransformMatrices = null;
  17311. }
  17312. this._markSubMeshesAsAttributesDirty();
  17313. },
  17314. enumerable: true,
  17315. configurable: true
  17316. });
  17317. /**
  17318. * Returns the string "AbstractMesh"
  17319. */
  17320. AbstractMesh.prototype.getClassName = function () {
  17321. return "AbstractMesh";
  17322. };
  17323. /**
  17324. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  17325. */
  17326. AbstractMesh.prototype.toString = function (fullDetails) {
  17327. var ret = "Name: " + this.name + ", isInstance: " + (this instanceof BABYLON.InstancedMesh ? "YES" : "NO");
  17328. ret += ", # of submeshes: " + (this.subMeshes ? this.subMeshes.length : 0);
  17329. if (this._skeleton) {
  17330. ret += ", skeleton: " + this._skeleton.name;
  17331. }
  17332. if (fullDetails) {
  17333. ret += ", billboard mode: " + (["NONE", "X", "Y", null, "Z", null, null, "ALL"])[this.billboardMode];
  17334. ret += ", freeze wrld mat: " + (this._isWorldMatrixFrozen || this._waitingFreezeWorldMatrix ? "YES" : "NO");
  17335. }
  17336. return ret;
  17337. };
  17338. AbstractMesh.prototype._rebuild = function () {
  17339. if (this._occlusionQuery) {
  17340. this._occlusionQuery = null;
  17341. }
  17342. if (this._edgesRenderer) {
  17343. this._edgesRenderer._rebuild();
  17344. }
  17345. if (!this.subMeshes) {
  17346. return;
  17347. }
  17348. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  17349. var subMesh = _a[_i];
  17350. subMesh._rebuild();
  17351. }
  17352. };
  17353. AbstractMesh.prototype._resyncLightSources = function () {
  17354. this._lightSources.length = 0;
  17355. for (var _i = 0, _a = this.getScene().lights; _i < _a.length; _i++) {
  17356. var light = _a[_i];
  17357. if (!light.isEnabled()) {
  17358. continue;
  17359. }
  17360. if (light.canAffectMesh(this)) {
  17361. this._lightSources.push(light);
  17362. }
  17363. }
  17364. this._markSubMeshesAsLightDirty();
  17365. };
  17366. AbstractMesh.prototype._resyncLighSource = function (light) {
  17367. var isIn = light.isEnabled() && light.canAffectMesh(this);
  17368. var index = this._lightSources.indexOf(light);
  17369. if (index === -1) {
  17370. if (!isIn) {
  17371. return;
  17372. }
  17373. this._lightSources.push(light);
  17374. }
  17375. else {
  17376. if (isIn) {
  17377. return;
  17378. }
  17379. this._lightSources.splice(index, 1);
  17380. }
  17381. this._markSubMeshesAsLightDirty();
  17382. };
  17383. AbstractMesh.prototype._removeLightSource = function (light) {
  17384. var index = this._lightSources.indexOf(light);
  17385. if (index === -1) {
  17386. return;
  17387. }
  17388. this._lightSources.splice(index, 1);
  17389. this._markSubMeshesAsLightDirty();
  17390. };
  17391. AbstractMesh.prototype._markSubMeshesAsDirty = function (func) {
  17392. if (!this.subMeshes) {
  17393. return;
  17394. }
  17395. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  17396. var subMesh = _a[_i];
  17397. if (subMesh._materialDefines) {
  17398. func(subMesh._materialDefines);
  17399. }
  17400. }
  17401. };
  17402. AbstractMesh.prototype._markSubMeshesAsLightDirty = function () {
  17403. this._markSubMeshesAsDirty(function (defines) { return defines.markAsLightDirty(); });
  17404. };
  17405. AbstractMesh.prototype._markSubMeshesAsAttributesDirty = function () {
  17406. this._markSubMeshesAsDirty(function (defines) { return defines.markAsAttributesDirty(); });
  17407. };
  17408. AbstractMesh.prototype._markSubMeshesAsMiscDirty = function () {
  17409. if (!this.subMeshes) {
  17410. return;
  17411. }
  17412. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  17413. var subMesh = _a[_i];
  17414. var material = subMesh.getMaterial();
  17415. if (material) {
  17416. material.markAsDirty(BABYLON.Material.MiscDirtyFlag);
  17417. }
  17418. }
  17419. };
  17420. Object.defineProperty(AbstractMesh.prototype, "scaling", {
  17421. /**
  17422. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  17423. * Default : (1.0, 1.0, 1.0)
  17424. */
  17425. get: function () {
  17426. return this._scaling;
  17427. },
  17428. /**
  17429. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  17430. * Default : (1.0, 1.0, 1.0)
  17431. */
  17432. set: function (newScaling) {
  17433. this._scaling = newScaling;
  17434. if (this.physicsImpostor) {
  17435. this.physicsImpostor.forceUpdate();
  17436. }
  17437. },
  17438. enumerable: true,
  17439. configurable: true
  17440. });
  17441. // Methods
  17442. /**
  17443. * Disables the mesh edger rendering mode.
  17444. * Returns the AbstractMesh.
  17445. */
  17446. AbstractMesh.prototype.disableEdgesRendering = function () {
  17447. if (this._edgesRenderer) {
  17448. this._edgesRenderer.dispose();
  17449. this._edgesRenderer = null;
  17450. }
  17451. return this;
  17452. };
  17453. /**
  17454. * Enables the edge rendering mode on the mesh.
  17455. * This mode makes the mesh edges visible.
  17456. * Returns the AbstractMesh.
  17457. */
  17458. AbstractMesh.prototype.enableEdgesRendering = function (epsilon, checkVerticesInsteadOfIndices) {
  17459. if (epsilon === void 0) { epsilon = 0.95; }
  17460. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  17461. this.disableEdgesRendering();
  17462. this._edgesRenderer = new BABYLON.EdgesRenderer(this, epsilon, checkVerticesInsteadOfIndices);
  17463. return this;
  17464. };
  17465. Object.defineProperty(AbstractMesh.prototype, "isBlocked", {
  17466. /**
  17467. * Returns true if the mesh is blocked. Used by the class Mesh.
  17468. * Returns the boolean `false` by default.
  17469. */
  17470. get: function () {
  17471. return false;
  17472. },
  17473. enumerable: true,
  17474. configurable: true
  17475. });
  17476. /**
  17477. * Returns the mesh itself by default, used by the class Mesh.
  17478. * Returned type : AbstractMesh
  17479. */
  17480. AbstractMesh.prototype.getLOD = function (camera) {
  17481. return this;
  17482. };
  17483. /**
  17484. * Returns 0 by default, used by the class Mesh.
  17485. * Returns an integer.
  17486. */
  17487. AbstractMesh.prototype.getTotalVertices = function () {
  17488. return 0;
  17489. };
  17490. /**
  17491. * Returns null by default, used by the class Mesh.
  17492. * Returned type : integer array
  17493. */
  17494. AbstractMesh.prototype.getIndices = function () {
  17495. return null;
  17496. };
  17497. /**
  17498. * Returns the array of the requested vertex data kind. Used by the class Mesh. Returns null here.
  17499. * Returned type : float array or Float32Array
  17500. */
  17501. AbstractMesh.prototype.getVerticesData = function (kind) {
  17502. return null;
  17503. };
  17504. /**
  17505. * Sets the vertex data of the mesh geometry for the requested `kind`.
  17506. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  17507. * The `data` are either a numeric array either a Float32Array.
  17508. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  17509. * The parameter `stride` is an optional positive integer, it is usually automatically deducted from the `kind` (3 for positions or normals, 2 for UV, etc).
  17510. * Note that a new underlying VertexBuffer object is created each call.
  17511. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  17512. *
  17513. * Possible `kind` values :
  17514. * - BABYLON.VertexBuffer.PositionKind
  17515. * - BABYLON.VertexBuffer.UVKind
  17516. * - BABYLON.VertexBuffer.UV2Kind
  17517. * - BABYLON.VertexBuffer.UV3Kind
  17518. * - BABYLON.VertexBuffer.UV4Kind
  17519. * - BABYLON.VertexBuffer.UV5Kind
  17520. * - BABYLON.VertexBuffer.UV6Kind
  17521. * - BABYLON.VertexBuffer.ColorKind
  17522. * - BABYLON.VertexBuffer.MatricesIndicesKind
  17523. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  17524. * - BABYLON.VertexBuffer.MatricesWeightsKind
  17525. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  17526. *
  17527. * Returns the Mesh.
  17528. */
  17529. AbstractMesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  17530. return this;
  17531. };
  17532. /**
  17533. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  17534. * If the mesh has no geometry, it is simply returned as it is.
  17535. * The `data` are either a numeric array either a Float32Array.
  17536. * No new underlying VertexBuffer object is created.
  17537. * If the `kind` is the `PositionKind` and if `updateExtends` is true, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  17538. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  17539. *
  17540. * Possible `kind` values :
  17541. * - BABYLON.VertexBuffer.PositionKind
  17542. * - BABYLON.VertexBuffer.UVKind
  17543. * - BABYLON.VertexBuffer.UV2Kind
  17544. * - BABYLON.VertexBuffer.UV3Kind
  17545. * - BABYLON.VertexBuffer.UV4Kind
  17546. * - BABYLON.VertexBuffer.UV5Kind
  17547. * - BABYLON.VertexBuffer.UV6Kind
  17548. * - BABYLON.VertexBuffer.ColorKind
  17549. * - BABYLON.VertexBuffer.MatricesIndicesKind
  17550. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  17551. * - BABYLON.VertexBuffer.MatricesWeightsKind
  17552. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  17553. *
  17554. * Returns the Mesh.
  17555. */
  17556. AbstractMesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  17557. return this;
  17558. };
  17559. /**
  17560. * Sets the mesh indices.
  17561. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array).
  17562. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  17563. * This method creates a new index buffer each call.
  17564. * Returns the Mesh.
  17565. */
  17566. AbstractMesh.prototype.setIndices = function (indices, totalVertices) {
  17567. return this;
  17568. };
  17569. /** Returns false by default, used by the class Mesh.
  17570. * Returns a boolean
  17571. */
  17572. AbstractMesh.prototype.isVerticesDataPresent = function (kind) {
  17573. return false;
  17574. };
  17575. /**
  17576. * Returns the mesh BoundingInfo object or creates a new one and returns it if undefined.
  17577. * Returns a BoundingInfo
  17578. */
  17579. AbstractMesh.prototype.getBoundingInfo = function () {
  17580. if (this._masterMesh) {
  17581. return this._masterMesh.getBoundingInfo();
  17582. }
  17583. if (!this._boundingInfo) {
  17584. // this._boundingInfo is being created here
  17585. this._updateBoundingInfo();
  17586. }
  17587. // cannot be null.
  17588. return this._boundingInfo;
  17589. };
  17590. /**
  17591. * Uniformly scales the mesh to fit inside of a unit cube (1 X 1 X 1 units).
  17592. * @param includeDescendants Take the hierarchy's bounding box instead of the mesh's bounding box.
  17593. */
  17594. AbstractMesh.prototype.normalizeToUnitCube = function (includeDescendants) {
  17595. if (includeDescendants === void 0) { includeDescendants = true; }
  17596. var boundingVectors = this.getHierarchyBoundingVectors(includeDescendants);
  17597. var sizeVec = boundingVectors.max.subtract(boundingVectors.min);
  17598. var maxDimension = Math.max(sizeVec.x, sizeVec.y, sizeVec.z);
  17599. if (maxDimension === 0) {
  17600. return this;
  17601. }
  17602. var scale = 1 / maxDimension;
  17603. this.scaling.scaleInPlace(scale);
  17604. return this;
  17605. };
  17606. /**
  17607. * Sets a mesh new object BoundingInfo.
  17608. * Returns the AbstractMesh.
  17609. */
  17610. AbstractMesh.prototype.setBoundingInfo = function (boundingInfo) {
  17611. this._boundingInfo = boundingInfo;
  17612. return this;
  17613. };
  17614. Object.defineProperty(AbstractMesh.prototype, "useBones", {
  17615. get: function () {
  17616. return (this.skeleton && this.getScene().skeletonsEnabled && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind));
  17617. },
  17618. enumerable: true,
  17619. configurable: true
  17620. });
  17621. AbstractMesh.prototype._preActivate = function () {
  17622. };
  17623. AbstractMesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  17624. };
  17625. AbstractMesh.prototype._activate = function (renderId) {
  17626. this._renderId = renderId;
  17627. };
  17628. /**
  17629. * Returns the latest update of the World matrix
  17630. * Returns a Matrix.
  17631. */
  17632. AbstractMesh.prototype.getWorldMatrix = function () {
  17633. if (this._masterMesh) {
  17634. return this._masterMesh.getWorldMatrix();
  17635. }
  17636. return _super.prototype.getWorldMatrix.call(this);
  17637. };
  17638. /**
  17639. * Returns the latest update of the World matrix determinant.
  17640. */
  17641. AbstractMesh.prototype._getWorldMatrixDeterminant = function () {
  17642. if (this._masterMesh) {
  17643. return this._masterMesh._getWorldMatrixDeterminant();
  17644. }
  17645. return _super.prototype._getWorldMatrixDeterminant.call(this);
  17646. };
  17647. // ================================== Point of View Movement =================================
  17648. /**
  17649. * Perform relative position change from the point of view of behind the front of the mesh.
  17650. * This is performed taking into account the meshes current rotation, so you do not have to care.
  17651. * Supports definition of mesh facing forward or backward.
  17652. * @param {number} amountRight
  17653. * @param {number} amountUp
  17654. * @param {number} amountForward
  17655. *
  17656. * Returns the AbstractMesh.
  17657. */
  17658. AbstractMesh.prototype.movePOV = function (amountRight, amountUp, amountForward) {
  17659. this.position.addInPlace(this.calcMovePOV(amountRight, amountUp, amountForward));
  17660. return this;
  17661. };
  17662. /**
  17663. * Calculate relative position change from the point of view of behind the front of the mesh.
  17664. * This is performed taking into account the meshes current rotation, so you do not have to care.
  17665. * Supports definition of mesh facing forward or backward.
  17666. * @param {number} amountRight
  17667. * @param {number} amountUp
  17668. * @param {number} amountForward
  17669. *
  17670. * Returns a new Vector3.
  17671. */
  17672. AbstractMesh.prototype.calcMovePOV = function (amountRight, amountUp, amountForward) {
  17673. var rotMatrix = new BABYLON.Matrix();
  17674. var rotQuaternion = (this.rotationQuaternion) ? this.rotationQuaternion : BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  17675. rotQuaternion.toRotationMatrix(rotMatrix);
  17676. var translationDelta = BABYLON.Vector3.Zero();
  17677. var defForwardMult = this.definedFacingForward ? -1 : 1;
  17678. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(amountRight * defForwardMult, amountUp, amountForward * defForwardMult, rotMatrix, translationDelta);
  17679. return translationDelta;
  17680. };
  17681. // ================================== Point of View Rotation =================================
  17682. /**
  17683. * Perform relative rotation change from the point of view of behind the front of the mesh.
  17684. * Supports definition of mesh facing forward or backward.
  17685. * @param {number} flipBack
  17686. * @param {number} twirlClockwise
  17687. * @param {number} tiltRight
  17688. *
  17689. * Returns the AbstractMesh.
  17690. */
  17691. AbstractMesh.prototype.rotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  17692. this.rotation.addInPlace(this.calcRotatePOV(flipBack, twirlClockwise, tiltRight));
  17693. return this;
  17694. };
  17695. /**
  17696. * Calculate relative rotation change from the point of view of behind the front of the mesh.
  17697. * Supports definition of mesh facing forward or backward.
  17698. * @param {number} flipBack
  17699. * @param {number} twirlClockwise
  17700. * @param {number} tiltRight
  17701. *
  17702. * Returns a new Vector3.
  17703. */
  17704. AbstractMesh.prototype.calcRotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  17705. var defForwardMult = this.definedFacingForward ? 1 : -1;
  17706. return new BABYLON.Vector3(flipBack * defForwardMult, twirlClockwise, tiltRight * defForwardMult);
  17707. };
  17708. /**
  17709. * Return the minimum and maximum world vectors of the entire hierarchy under current mesh
  17710. * @param includeDescendants Include bounding info from descendants as well (true by default).
  17711. */
  17712. AbstractMesh.prototype.getHierarchyBoundingVectors = function (includeDescendants) {
  17713. if (includeDescendants === void 0) { includeDescendants = true; }
  17714. this.computeWorldMatrix(true);
  17715. var min;
  17716. var max;
  17717. var boundingInfo = this.getBoundingInfo();
  17718. if (!this.subMeshes) {
  17719. min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  17720. max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  17721. }
  17722. else {
  17723. min = boundingInfo.boundingBox.minimumWorld;
  17724. max = boundingInfo.boundingBox.maximumWorld;
  17725. }
  17726. if (includeDescendants) {
  17727. var descendants = this.getDescendants(false);
  17728. for (var _i = 0, descendants_1 = descendants; _i < descendants_1.length; _i++) {
  17729. var descendant = descendants_1[_i];
  17730. var childMesh = descendant;
  17731. childMesh.computeWorldMatrix(true);
  17732. //make sure we have the needed params to get mix and max
  17733. if (!childMesh.getBoundingInfo || childMesh.getTotalVertices() === 0) {
  17734. continue;
  17735. }
  17736. var childBoundingInfo = childMesh.getBoundingInfo();
  17737. var boundingBox = childBoundingInfo.boundingBox;
  17738. var minBox = boundingBox.minimumWorld;
  17739. var maxBox = boundingBox.maximumWorld;
  17740. BABYLON.Tools.CheckExtends(minBox, min, max);
  17741. BABYLON.Tools.CheckExtends(maxBox, min, max);
  17742. }
  17743. }
  17744. return {
  17745. min: min,
  17746. max: max
  17747. };
  17748. };
  17749. /**
  17750. * Updates the mesh BoundingInfo object and all its children BoundingInfo objects also.
  17751. * Returns the AbstractMesh.
  17752. */
  17753. AbstractMesh.prototype._updateBoundingInfo = function () {
  17754. this._boundingInfo = this._boundingInfo || new BABYLON.BoundingInfo(this.absolutePosition, this.absolutePosition);
  17755. this._boundingInfo.update(this.worldMatrixFromCache);
  17756. this._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  17757. return this;
  17758. };
  17759. /**
  17760. * Update a mesh's children BoundingInfo objects only.
  17761. * Returns the AbstractMesh.
  17762. */
  17763. AbstractMesh.prototype._updateSubMeshesBoundingInfo = function (matrix) {
  17764. if (!this.subMeshes) {
  17765. return this;
  17766. }
  17767. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  17768. var subMesh = this.subMeshes[subIndex];
  17769. if (!subMesh.IsGlobal) {
  17770. subMesh.updateBoundingInfo(matrix);
  17771. }
  17772. }
  17773. return this;
  17774. };
  17775. AbstractMesh.prototype._afterComputeWorldMatrix = function () {
  17776. // Bounding info
  17777. this._updateBoundingInfo();
  17778. };
  17779. /**
  17780. * Returns `true` if the mesh is within the frustum defined by the passed array of planes.
  17781. * A mesh is in the frustum if its bounding box intersects the frustum.
  17782. * Boolean returned.
  17783. */
  17784. AbstractMesh.prototype.isInFrustum = function (frustumPlanes) {
  17785. return this._boundingInfo !== null && this._boundingInfo.isInFrustum(frustumPlanes);
  17786. };
  17787. /**
  17788. * Returns `true` if the mesh is completely in the frustum defined be the passed array of planes.
  17789. * A mesh is completely in the frustum if its bounding box it completely inside the frustum.
  17790. * Boolean returned.
  17791. */
  17792. AbstractMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  17793. return this._boundingInfo !== null && this._boundingInfo.isCompletelyInFrustum(frustumPlanes);
  17794. ;
  17795. };
  17796. /**
  17797. * True if the mesh intersects another mesh or a SolidParticle object.
  17798. * Unless the parameter `precise` is set to `true` the intersection is computed according to Axis Aligned Bounding Boxes (AABB), else according to OBB (Oriented BBoxes)
  17799. * includeDescendants can be set to true to test if the mesh defined in parameters intersects with the current mesh or any child meshes
  17800. * Returns a boolean.
  17801. */
  17802. AbstractMesh.prototype.intersectsMesh = function (mesh, precise, includeDescendants) {
  17803. if (precise === void 0) { precise = false; }
  17804. if (!this._boundingInfo || !mesh._boundingInfo) {
  17805. return false;
  17806. }
  17807. if (this._boundingInfo.intersects(mesh._boundingInfo, precise)) {
  17808. return true;
  17809. }
  17810. if (includeDescendants) {
  17811. for (var _i = 0, _a = this.getChildMeshes(); _i < _a.length; _i++) {
  17812. var child = _a[_i];
  17813. if (child.intersectsMesh(mesh, precise, true)) {
  17814. return true;
  17815. }
  17816. }
  17817. }
  17818. return false;
  17819. };
  17820. /**
  17821. * Returns true if the passed point (Vector3) is inside the mesh bounding box.
  17822. * Returns a boolean.
  17823. */
  17824. AbstractMesh.prototype.intersectsPoint = function (point) {
  17825. if (!this._boundingInfo) {
  17826. return false;
  17827. }
  17828. return this._boundingInfo.intersectsPoint(point);
  17829. };
  17830. AbstractMesh.prototype.getPhysicsImpostor = function () {
  17831. return this.physicsImpostor;
  17832. };
  17833. AbstractMesh.prototype.getPositionInCameraSpace = function (camera) {
  17834. if (camera === void 0) { camera = null; }
  17835. if (!camera) {
  17836. camera = this.getScene().activeCamera;
  17837. }
  17838. return BABYLON.Vector3.TransformCoordinates(this.absolutePosition, camera.getViewMatrix());
  17839. };
  17840. /**
  17841. * Returns the distance from the mesh to the active camera.
  17842. * Returns a float.
  17843. */
  17844. AbstractMesh.prototype.getDistanceToCamera = function (camera) {
  17845. if (camera === void 0) { camera = null; }
  17846. if (!camera) {
  17847. camera = this.getScene().activeCamera;
  17848. }
  17849. return this.absolutePosition.subtract(camera.position).length();
  17850. };
  17851. AbstractMesh.prototype.applyImpulse = function (force, contactPoint) {
  17852. if (!this.physicsImpostor) {
  17853. return this;
  17854. }
  17855. this.physicsImpostor.applyImpulse(force, contactPoint);
  17856. return this;
  17857. };
  17858. AbstractMesh.prototype.setPhysicsLinkWith = function (otherMesh, pivot1, pivot2, options) {
  17859. if (!this.physicsImpostor || !otherMesh.physicsImpostor) {
  17860. return this;
  17861. }
  17862. this.physicsImpostor.createJoint(otherMesh.physicsImpostor, BABYLON.PhysicsJoint.HingeJoint, {
  17863. mainPivot: pivot1,
  17864. connectedPivot: pivot2,
  17865. nativeParams: options
  17866. });
  17867. return this;
  17868. };
  17869. Object.defineProperty(AbstractMesh.prototype, "checkCollisions", {
  17870. // Collisions
  17871. /**
  17872. * Property checkCollisions : Boolean, whether the camera should check the collisions against the mesh.
  17873. * Default `false`.
  17874. */
  17875. get: function () {
  17876. return this._checkCollisions;
  17877. },
  17878. set: function (collisionEnabled) {
  17879. this._checkCollisions = collisionEnabled;
  17880. if (this.getScene().workerCollisions) {
  17881. this.getScene().collisionCoordinator.onMeshUpdated(this);
  17882. }
  17883. },
  17884. enumerable: true,
  17885. configurable: true
  17886. });
  17887. Object.defineProperty(AbstractMesh.prototype, "collider", {
  17888. /**
  17889. * Gets Collider object used to compute collisions (not physics)
  17890. */
  17891. get: function () {
  17892. return this._collider;
  17893. },
  17894. enumerable: true,
  17895. configurable: true
  17896. });
  17897. AbstractMesh.prototype.moveWithCollisions = function (displacement) {
  17898. var globalPosition = this.getAbsolutePosition();
  17899. globalPosition.addToRef(this.ellipsoidOffset, this._oldPositionForCollisions);
  17900. if (!this._collider) {
  17901. this._collider = new BABYLON.Collider();
  17902. }
  17903. this._collider._radius = this.ellipsoid;
  17904. this.getScene().collisionCoordinator.getNewPosition(this._oldPositionForCollisions, displacement, this._collider, 3, this, this._onCollisionPositionChange, this.uniqueId);
  17905. return this;
  17906. };
  17907. // Submeshes octree
  17908. /**
  17909. * This function will create an octree to help to select the right submeshes for rendering, picking and collision computations.
  17910. * Please note that you must have a decent number of submeshes to get performance improvements when using an octree.
  17911. * Returns an Octree of submeshes.
  17912. */
  17913. AbstractMesh.prototype.createOrUpdateSubmeshesOctree = function (maxCapacity, maxDepth) {
  17914. if (maxCapacity === void 0) { maxCapacity = 64; }
  17915. if (maxDepth === void 0) { maxDepth = 2; }
  17916. if (!this._submeshesOctree) {
  17917. this._submeshesOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForSubMeshes, maxCapacity, maxDepth);
  17918. }
  17919. this.computeWorldMatrix(true);
  17920. var boundingInfo = this.getBoundingInfo();
  17921. // Update octree
  17922. var bbox = boundingInfo.boundingBox;
  17923. this._submeshesOctree.update(bbox.minimumWorld, bbox.maximumWorld, this.subMeshes);
  17924. return this._submeshesOctree;
  17925. };
  17926. // Collisions
  17927. AbstractMesh.prototype._collideForSubMesh = function (subMesh, transformMatrix, collider) {
  17928. this._generatePointsArray();
  17929. if (!this._positions) {
  17930. return this;
  17931. }
  17932. // Transformation
  17933. if (!subMesh._lastColliderWorldVertices || !subMesh._lastColliderTransformMatrix.equals(transformMatrix)) {
  17934. subMesh._lastColliderTransformMatrix = transformMatrix.clone();
  17935. subMesh._lastColliderWorldVertices = [];
  17936. subMesh._trianglePlanes = [];
  17937. var start = subMesh.verticesStart;
  17938. var end = (subMesh.verticesStart + subMesh.verticesCount);
  17939. for (var i = start; i < end; i++) {
  17940. subMesh._lastColliderWorldVertices.push(BABYLON.Vector3.TransformCoordinates(this._positions[i], transformMatrix));
  17941. }
  17942. }
  17943. // Collide
  17944. collider._collide(subMesh._trianglePlanes, subMesh._lastColliderWorldVertices, this.getIndices(), subMesh.indexStart, subMesh.indexStart + subMesh.indexCount, subMesh.verticesStart, !!subMesh.getMaterial());
  17945. if (collider.collisionFound) {
  17946. collider.collidedMesh = this;
  17947. }
  17948. return this;
  17949. };
  17950. AbstractMesh.prototype._processCollisionsForSubMeshes = function (collider, transformMatrix) {
  17951. var subMeshes;
  17952. var len;
  17953. // Octrees
  17954. if (this._submeshesOctree && this.useOctreeForCollisions) {
  17955. var radius = collider._velocityWorldLength + Math.max(collider._radius.x, collider._radius.y, collider._radius.z);
  17956. var intersections = this._submeshesOctree.intersects(collider._basePointWorld, radius);
  17957. len = intersections.length;
  17958. subMeshes = intersections.data;
  17959. }
  17960. else {
  17961. subMeshes = this.subMeshes;
  17962. len = subMeshes.length;
  17963. }
  17964. for (var index = 0; index < len; index++) {
  17965. var subMesh = subMeshes[index];
  17966. // Bounding test
  17967. if (len > 1 && !subMesh._checkCollision(collider))
  17968. continue;
  17969. this._collideForSubMesh(subMesh, transformMatrix, collider);
  17970. }
  17971. return this;
  17972. };
  17973. AbstractMesh.prototype._checkCollision = function (collider) {
  17974. // Bounding box test
  17975. if (!this._boundingInfo || !this._boundingInfo._checkCollision(collider))
  17976. return this;
  17977. // Transformation matrix
  17978. BABYLON.Matrix.ScalingToRef(1.0 / collider._radius.x, 1.0 / collider._radius.y, 1.0 / collider._radius.z, this._collisionsScalingMatrix);
  17979. this.worldMatrixFromCache.multiplyToRef(this._collisionsScalingMatrix, this._collisionsTransformMatrix);
  17980. this._processCollisionsForSubMeshes(collider, this._collisionsTransformMatrix);
  17981. return this;
  17982. };
  17983. // Picking
  17984. AbstractMesh.prototype._generatePointsArray = function () {
  17985. return false;
  17986. };
  17987. /**
  17988. * Checks if the passed Ray intersects with the mesh.
  17989. * Returns an object PickingInfo.
  17990. */
  17991. AbstractMesh.prototype.intersects = function (ray, fastCheck) {
  17992. var pickingInfo = new BABYLON.PickingInfo();
  17993. if (!this.subMeshes || !this._boundingInfo || !ray.intersectsSphere(this._boundingInfo.boundingSphere) || !ray.intersectsBox(this._boundingInfo.boundingBox)) {
  17994. return pickingInfo;
  17995. }
  17996. if (!this._generatePointsArray()) {
  17997. return pickingInfo;
  17998. }
  17999. var intersectInfo = null;
  18000. // Octrees
  18001. var subMeshes;
  18002. var len;
  18003. if (this._submeshesOctree && this.useOctreeForPicking) {
  18004. var worldRay = BABYLON.Ray.Transform(ray, this.getWorldMatrix());
  18005. var intersections = this._submeshesOctree.intersectsRay(worldRay);
  18006. len = intersections.length;
  18007. subMeshes = intersections.data;
  18008. }
  18009. else {
  18010. subMeshes = this.subMeshes;
  18011. len = subMeshes.length;
  18012. }
  18013. for (var index = 0; index < len; index++) {
  18014. var subMesh = subMeshes[index];
  18015. // Bounding test
  18016. if (len > 1 && !subMesh.canIntersects(ray))
  18017. continue;
  18018. var currentIntersectInfo = subMesh.intersects(ray, this._positions, this.getIndices(), fastCheck);
  18019. if (currentIntersectInfo) {
  18020. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  18021. intersectInfo = currentIntersectInfo;
  18022. intersectInfo.subMeshId = index;
  18023. if (fastCheck) {
  18024. break;
  18025. }
  18026. }
  18027. }
  18028. }
  18029. if (intersectInfo) {
  18030. // Get picked point
  18031. var world = this.getWorldMatrix();
  18032. var worldOrigin = BABYLON.Vector3.TransformCoordinates(ray.origin, world);
  18033. var direction = ray.direction.clone();
  18034. direction = direction.scale(intersectInfo.distance);
  18035. var worldDirection = BABYLON.Vector3.TransformNormal(direction, world);
  18036. var pickedPoint = worldOrigin.add(worldDirection);
  18037. // Return result
  18038. pickingInfo.hit = true;
  18039. pickingInfo.distance = BABYLON.Vector3.Distance(worldOrigin, pickedPoint);
  18040. pickingInfo.pickedPoint = pickedPoint;
  18041. pickingInfo.pickedMesh = this;
  18042. pickingInfo.bu = intersectInfo.bu || 0;
  18043. pickingInfo.bv = intersectInfo.bv || 0;
  18044. pickingInfo.faceId = intersectInfo.faceId;
  18045. pickingInfo.subMeshId = intersectInfo.subMeshId;
  18046. return pickingInfo;
  18047. }
  18048. return pickingInfo;
  18049. };
  18050. /**
  18051. * Clones the mesh, used by the class Mesh.
  18052. * Just returns `null` for an AbstractMesh.
  18053. */
  18054. AbstractMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  18055. return null;
  18056. };
  18057. /**
  18058. * Disposes all the mesh submeshes.
  18059. * Returns the AbstractMesh.
  18060. */
  18061. AbstractMesh.prototype.releaseSubMeshes = function () {
  18062. if (this.subMeshes) {
  18063. while (this.subMeshes.length) {
  18064. this.subMeshes[0].dispose();
  18065. }
  18066. }
  18067. else {
  18068. this.subMeshes = new Array();
  18069. }
  18070. return this;
  18071. };
  18072. /**
  18073. * Disposes the AbstractMesh.
  18074. * By default, all the mesh children are also disposed unless the parameter `doNotRecurse` is set to `true`.
  18075. * Returns nothing.
  18076. */
  18077. AbstractMesh.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  18078. var _this = this;
  18079. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  18080. var index;
  18081. // Action manager
  18082. if (this.actionManager !== undefined && this.actionManager !== null) {
  18083. this.actionManager.dispose();
  18084. this.actionManager = null;
  18085. }
  18086. // Skeleton
  18087. this.skeleton = null;
  18088. // Physics
  18089. if (this.physicsImpostor) {
  18090. this.physicsImpostor.dispose();
  18091. }
  18092. // Intersections in progress
  18093. for (index = 0; index < this._intersectionsInProgress.length; index++) {
  18094. var other = this._intersectionsInProgress[index];
  18095. var pos = other._intersectionsInProgress.indexOf(this);
  18096. other._intersectionsInProgress.splice(pos, 1);
  18097. }
  18098. this._intersectionsInProgress = [];
  18099. // Lights
  18100. var lights = this.getScene().lights;
  18101. lights.forEach(function (light) {
  18102. var meshIndex = light.includedOnlyMeshes.indexOf(_this);
  18103. if (meshIndex !== -1) {
  18104. light.includedOnlyMeshes.splice(meshIndex, 1);
  18105. }
  18106. meshIndex = light.excludedMeshes.indexOf(_this);
  18107. if (meshIndex !== -1) {
  18108. light.excludedMeshes.splice(meshIndex, 1);
  18109. }
  18110. // Shadow generators
  18111. var generator = light.getShadowGenerator();
  18112. if (generator) {
  18113. var shadowMap = generator.getShadowMap();
  18114. if (shadowMap && shadowMap.renderList) {
  18115. meshIndex = shadowMap.renderList.indexOf(_this);
  18116. if (meshIndex !== -1) {
  18117. shadowMap.renderList.splice(meshIndex, 1);
  18118. }
  18119. }
  18120. }
  18121. });
  18122. // Edges
  18123. if (this._edgesRenderer) {
  18124. this._edgesRenderer.dispose();
  18125. this._edgesRenderer = null;
  18126. }
  18127. // SubMeshes
  18128. if (this.getClassName() !== "InstancedMesh") {
  18129. this.releaseSubMeshes();
  18130. }
  18131. // Octree
  18132. var sceneOctree = this.getScene().selectionOctree;
  18133. if (sceneOctree !== undefined && sceneOctree !== null) {
  18134. var index = sceneOctree.dynamicContent.indexOf(this);
  18135. if (index !== -1) {
  18136. sceneOctree.dynamicContent.splice(index, 1);
  18137. }
  18138. }
  18139. // Query
  18140. var engine = this.getScene().getEngine();
  18141. if (this._occlusionQuery) {
  18142. this._isOcclusionQueryInProgress = false;
  18143. engine.deleteQuery(this._occlusionQuery);
  18144. this._occlusionQuery = null;
  18145. }
  18146. // Engine
  18147. engine.wipeCaches();
  18148. // Remove from scene
  18149. this.getScene().removeMesh(this);
  18150. if (disposeMaterialAndTextures) {
  18151. if (this.material) {
  18152. this.material.dispose(false, true);
  18153. }
  18154. }
  18155. if (!doNotRecurse) {
  18156. // Particles
  18157. for (index = 0; index < this.getScene().particleSystems.length; index++) {
  18158. if (this.getScene().particleSystems[index].emitter === this) {
  18159. this.getScene().particleSystems[index].dispose();
  18160. index--;
  18161. }
  18162. }
  18163. }
  18164. // facet data
  18165. if (this._facetDataEnabled) {
  18166. this.disableFacetData();
  18167. }
  18168. this.onAfterWorldMatrixUpdateObservable.clear();
  18169. this.onCollideObservable.clear();
  18170. this.onCollisionPositionChangeObservable.clear();
  18171. _super.prototype.dispose.call(this, doNotRecurse);
  18172. };
  18173. /**
  18174. * Adds the passed mesh as a child to the current mesh.
  18175. * Returns the AbstractMesh.
  18176. */
  18177. AbstractMesh.prototype.addChild = function (mesh) {
  18178. mesh.setParent(this);
  18179. return this;
  18180. };
  18181. /**
  18182. * Removes the passed mesh from the current mesh children list.
  18183. * Returns the AbstractMesh.
  18184. */
  18185. AbstractMesh.prototype.removeChild = function (mesh) {
  18186. mesh.setParent(null);
  18187. return this;
  18188. };
  18189. // Facet data
  18190. /**
  18191. * Initialize the facet data arrays : facetNormals, facetPositions and facetPartitioning.
  18192. * Returns the AbstractMesh.
  18193. */
  18194. AbstractMesh.prototype._initFacetData = function () {
  18195. if (!this._facetNormals) {
  18196. this._facetNormals = new Array();
  18197. }
  18198. if (!this._facetPositions) {
  18199. this._facetPositions = new Array();
  18200. }
  18201. if (!this._facetPartitioning) {
  18202. this._facetPartitioning = new Array();
  18203. }
  18204. this._facetNb = (this.getIndices().length / 3) | 0;
  18205. this._partitioningSubdivisions = (this._partitioningSubdivisions) ? this._partitioningSubdivisions : 10; // default nb of partitioning subdivisions = 10
  18206. this._partitioningBBoxRatio = (this._partitioningBBoxRatio) ? this._partitioningBBoxRatio : 1.01; // default ratio 1.01 = the partitioning is 1% bigger than the bounding box
  18207. for (var f = 0; f < this._facetNb; f++) {
  18208. this._facetNormals[f] = BABYLON.Vector3.Zero();
  18209. this._facetPositions[f] = BABYLON.Vector3.Zero();
  18210. }
  18211. this._facetDataEnabled = true;
  18212. return this;
  18213. };
  18214. /**
  18215. * Updates the mesh facetData arrays and the internal partitioning when the mesh is morphed or updated.
  18216. * This method can be called within the render loop.
  18217. * You don't need to call this method by yourself in the render loop when you update/morph a mesh with the methods CreateXXX() as they automatically manage this computation.
  18218. * Returns the AbstractMesh.
  18219. */
  18220. AbstractMesh.prototype.updateFacetData = function () {
  18221. if (!this._facetDataEnabled) {
  18222. this._initFacetData();
  18223. }
  18224. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  18225. var indices = this.getIndices();
  18226. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  18227. var bInfo = this.getBoundingInfo();
  18228. if (this._facetDepthSort && !this._facetDepthSortEnabled) {
  18229. // init arrays, matrix and sort function on first call
  18230. this._facetDepthSortEnabled = true;
  18231. if (indices instanceof Uint16Array) {
  18232. this._depthSortedIndices = new Uint16Array(indices);
  18233. }
  18234. else if (indices instanceof Uint32Array) {
  18235. this._depthSortedIndices = new Uint32Array(indices);
  18236. }
  18237. else {
  18238. var needs32bits = false;
  18239. for (var i = 0; i < indices.length; i++) {
  18240. if (indices[i] > 65535) {
  18241. needs32bits = true;
  18242. break;
  18243. }
  18244. }
  18245. if (needs32bits) {
  18246. this._depthSortedIndices = new Uint32Array(indices);
  18247. }
  18248. else {
  18249. this._depthSortedIndices = new Uint16Array(indices);
  18250. }
  18251. }
  18252. this._facetDepthSortFunction = function (f1, f2) {
  18253. return (f2.sqDistance - f1.sqDistance);
  18254. };
  18255. if (!this._facetDepthSortFrom) {
  18256. var camera = this.getScene().activeCamera;
  18257. this._facetDepthSortFrom = (camera) ? camera.position : BABYLON.Vector3.Zero();
  18258. }
  18259. this._depthSortedFacets = [];
  18260. for (var f = 0; f < this._facetNb; f++) {
  18261. var depthSortedFacet = { ind: f * 3, sqDistance: 0.0 };
  18262. this._depthSortedFacets.push(depthSortedFacet);
  18263. }
  18264. this._invertedMatrix = BABYLON.Matrix.Identity();
  18265. this._facetDepthSortOrigin = BABYLON.Vector3.Zero();
  18266. }
  18267. this._bbSize.x = (bInfo.maximum.x - bInfo.minimum.x > BABYLON.Epsilon) ? bInfo.maximum.x - bInfo.minimum.x : BABYLON.Epsilon;
  18268. this._bbSize.y = (bInfo.maximum.y - bInfo.minimum.y > BABYLON.Epsilon) ? bInfo.maximum.y - bInfo.minimum.y : BABYLON.Epsilon;
  18269. this._bbSize.z = (bInfo.maximum.z - bInfo.minimum.z > BABYLON.Epsilon) ? bInfo.maximum.z - bInfo.minimum.z : BABYLON.Epsilon;
  18270. var bbSizeMax = (this._bbSize.x > this._bbSize.y) ? this._bbSize.x : this._bbSize.y;
  18271. bbSizeMax = (bbSizeMax > this._bbSize.z) ? bbSizeMax : this._bbSize.z;
  18272. this._subDiv.max = this._partitioningSubdivisions;
  18273. this._subDiv.X = Math.floor(this._subDiv.max * this._bbSize.x / bbSizeMax); // adjust the number of subdivisions per axis
  18274. this._subDiv.Y = Math.floor(this._subDiv.max * this._bbSize.y / bbSizeMax); // according to each bbox size per axis
  18275. this._subDiv.Z = Math.floor(this._subDiv.max * this._bbSize.z / bbSizeMax);
  18276. this._subDiv.X = this._subDiv.X < 1 ? 1 : this._subDiv.X; // at least one subdivision
  18277. this._subDiv.Y = this._subDiv.Y < 1 ? 1 : this._subDiv.Y;
  18278. this._subDiv.Z = this._subDiv.Z < 1 ? 1 : this._subDiv.Z;
  18279. // set the parameters for ComputeNormals()
  18280. this._facetParameters.facetNormals = this.getFacetLocalNormals();
  18281. this._facetParameters.facetPositions = this.getFacetLocalPositions();
  18282. this._facetParameters.facetPartitioning = this.getFacetLocalPartitioning();
  18283. this._facetParameters.bInfo = bInfo;
  18284. this._facetParameters.bbSize = this._bbSize;
  18285. this._facetParameters.subDiv = this._subDiv;
  18286. this._facetParameters.ratio = this.partitioningBBoxRatio;
  18287. this._facetParameters.depthSort = this._facetDepthSort;
  18288. if (this._facetDepthSort && this._facetDepthSortEnabled) {
  18289. this.computeWorldMatrix(true);
  18290. this._worldMatrix.invertToRef(this._invertedMatrix);
  18291. BABYLON.Vector3.TransformCoordinatesToRef(this._facetDepthSortFrom, this._invertedMatrix, this._facetDepthSortOrigin);
  18292. this._facetParameters.distanceTo = this._facetDepthSortOrigin;
  18293. }
  18294. this._facetParameters.depthSortedFacets = this._depthSortedFacets;
  18295. BABYLON.VertexData.ComputeNormals(positions, indices, normals, this._facetParameters);
  18296. if (this._facetDepthSort && this._facetDepthSortEnabled) {
  18297. this._depthSortedFacets.sort(this._facetDepthSortFunction);
  18298. var l = (this._depthSortedIndices.length / 3) | 0;
  18299. for (var f = 0; f < l; f++) {
  18300. var sind = this._depthSortedFacets[f].ind;
  18301. this._depthSortedIndices[f * 3] = indices[sind];
  18302. this._depthSortedIndices[f * 3 + 1] = indices[sind + 1];
  18303. this._depthSortedIndices[f * 3 + 2] = indices[sind + 2];
  18304. }
  18305. this.updateIndices(this._depthSortedIndices);
  18306. }
  18307. return this;
  18308. };
  18309. /**
  18310. * Returns the facetLocalNormals array.
  18311. * The normals are expressed in the mesh local space.
  18312. */
  18313. AbstractMesh.prototype.getFacetLocalNormals = function () {
  18314. if (!this._facetNormals) {
  18315. this.updateFacetData();
  18316. }
  18317. return this._facetNormals;
  18318. };
  18319. /**
  18320. * Returns the facetLocalPositions array.
  18321. * The facet positions are expressed in the mesh local space.
  18322. */
  18323. AbstractMesh.prototype.getFacetLocalPositions = function () {
  18324. if (!this._facetPositions) {
  18325. this.updateFacetData();
  18326. }
  18327. return this._facetPositions;
  18328. };
  18329. /**
  18330. * Returns the facetLocalPartioning array.
  18331. */
  18332. AbstractMesh.prototype.getFacetLocalPartitioning = function () {
  18333. if (!this._facetPartitioning) {
  18334. this.updateFacetData();
  18335. }
  18336. return this._facetPartitioning;
  18337. };
  18338. /**
  18339. * Returns the i-th facet position in the world system.
  18340. * This method allocates a new Vector3 per call.
  18341. */
  18342. AbstractMesh.prototype.getFacetPosition = function (i) {
  18343. var pos = BABYLON.Vector3.Zero();
  18344. this.getFacetPositionToRef(i, pos);
  18345. return pos;
  18346. };
  18347. /**
  18348. * Sets the reference Vector3 with the i-th facet position in the world system.
  18349. * Returns the AbstractMesh.
  18350. */
  18351. AbstractMesh.prototype.getFacetPositionToRef = function (i, ref) {
  18352. var localPos = (this.getFacetLocalPositions())[i];
  18353. var world = this.getWorldMatrix();
  18354. BABYLON.Vector3.TransformCoordinatesToRef(localPos, world, ref);
  18355. return this;
  18356. };
  18357. /**
  18358. * Returns the i-th facet normal in the world system.
  18359. * This method allocates a new Vector3 per call.
  18360. */
  18361. AbstractMesh.prototype.getFacetNormal = function (i) {
  18362. var norm = BABYLON.Vector3.Zero();
  18363. this.getFacetNormalToRef(i, norm);
  18364. return norm;
  18365. };
  18366. /**
  18367. * Sets the reference Vector3 with the i-th facet normal in the world system.
  18368. * Returns the AbstractMesh.
  18369. */
  18370. AbstractMesh.prototype.getFacetNormalToRef = function (i, ref) {
  18371. var localNorm = (this.getFacetLocalNormals())[i];
  18372. BABYLON.Vector3.TransformNormalToRef(localNorm, this.getWorldMatrix(), ref);
  18373. return this;
  18374. };
  18375. /**
  18376. * Returns the facets (in an array) in the same partitioning block than the one the passed coordinates are located (expressed in the mesh local system).
  18377. */
  18378. AbstractMesh.prototype.getFacetsAtLocalCoordinates = function (x, y, z) {
  18379. var bInfo = this.getBoundingInfo();
  18380. var ox = Math.floor((x - bInfo.minimum.x * this._partitioningBBoxRatio) * this._subDiv.X * this._partitioningBBoxRatio / this._bbSize.x);
  18381. var oy = Math.floor((y - bInfo.minimum.y * this._partitioningBBoxRatio) * this._subDiv.Y * this._partitioningBBoxRatio / this._bbSize.y);
  18382. var oz = Math.floor((z - bInfo.minimum.z * this._partitioningBBoxRatio) * this._subDiv.Z * this._partitioningBBoxRatio / this._bbSize.z);
  18383. if (ox < 0 || ox > this._subDiv.max || oy < 0 || oy > this._subDiv.max || oz < 0 || oz > this._subDiv.max) {
  18384. return null;
  18385. }
  18386. return this._facetPartitioning[ox + this._subDiv.max * oy + this._subDiv.max * this._subDiv.max * oz];
  18387. };
  18388. /**
  18389. * Returns the closest mesh facet index at (x,y,z) World coordinates, null if not found.
  18390. * If the parameter projected (vector3) is passed, it is set as the (x,y,z) World projection on the facet.
  18391. * If checkFace is true (default false), only the facet "facing" to (x,y,z) or only the ones "turning their backs", according to the parameter "facing" are returned.
  18392. * If facing and checkFace are true, only the facet "facing" to (x, y, z) are returned : positive dot (x, y, z) * facet position.
  18393. * If facing si false and checkFace is true, only the facet "turning their backs" to (x, y, z) are returned : negative dot (x, y, z) * facet position.
  18394. */
  18395. AbstractMesh.prototype.getClosestFacetAtCoordinates = function (x, y, z, projected, checkFace, facing) {
  18396. if (checkFace === void 0) { checkFace = false; }
  18397. if (facing === void 0) { facing = true; }
  18398. var world = this.getWorldMatrix();
  18399. var invMat = BABYLON.Tmp.Matrix[5];
  18400. world.invertToRef(invMat);
  18401. var invVect = BABYLON.Tmp.Vector3[8];
  18402. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, invMat, invVect); // transform (x,y,z) to coordinates in the mesh local space
  18403. var closest = this.getClosestFacetAtLocalCoordinates(invVect.x, invVect.y, invVect.z, projected, checkFace, facing);
  18404. if (projected) {
  18405. // tranform the local computed projected vector to world coordinates
  18406. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(projected.x, projected.y, projected.z, world, projected);
  18407. }
  18408. return closest;
  18409. };
  18410. /**
  18411. * Returns the closest mesh facet index at (x,y,z) local coordinates, null if not found.
  18412. * If the parameter projected (vector3) is passed, it is set as the (x,y,z) local projection on the facet.
  18413. * If checkFace is true (default false), only the facet "facing" to (x,y,z) or only the ones "turning their backs", according to the parameter "facing" are returned.
  18414. * If facing and checkFace are true, only the facet "facing" to (x, y, z) are returned : positive dot (x, y, z) * facet position.
  18415. * If facing si false and checkFace is true, only the facet "turning their backs" to (x, y, z) are returned : negative dot (x, y, z) * facet position.
  18416. */
  18417. AbstractMesh.prototype.getClosestFacetAtLocalCoordinates = function (x, y, z, projected, checkFace, facing) {
  18418. if (checkFace === void 0) { checkFace = false; }
  18419. if (facing === void 0) { facing = true; }
  18420. var closest = null;
  18421. var tmpx = 0.0;
  18422. var tmpy = 0.0;
  18423. var tmpz = 0.0;
  18424. var d = 0.0; // tmp dot facet normal * facet position
  18425. var t0 = 0.0;
  18426. var projx = 0.0;
  18427. var projy = 0.0;
  18428. var projz = 0.0;
  18429. // Get all the facets in the same partitioning block than (x, y, z)
  18430. var facetPositions = this.getFacetLocalPositions();
  18431. var facetNormals = this.getFacetLocalNormals();
  18432. var facetsInBlock = this.getFacetsAtLocalCoordinates(x, y, z);
  18433. if (!facetsInBlock) {
  18434. return null;
  18435. }
  18436. // Get the closest facet to (x, y, z)
  18437. var shortest = Number.MAX_VALUE; // init distance vars
  18438. var tmpDistance = shortest;
  18439. var fib; // current facet in the block
  18440. var norm; // current facet normal
  18441. var p0; // current facet barycenter position
  18442. // loop on all the facets in the current partitioning block
  18443. for (var idx = 0; idx < facetsInBlock.length; idx++) {
  18444. fib = facetsInBlock[idx];
  18445. norm = facetNormals[fib];
  18446. p0 = facetPositions[fib];
  18447. d = (x - p0.x) * norm.x + (y - p0.y) * norm.y + (z - p0.z) * norm.z;
  18448. if (!checkFace || (checkFace && facing && d >= 0.0) || (checkFace && !facing && d <= 0.0)) {
  18449. // compute (x,y,z) projection on the facet = (projx, projy, projz)
  18450. d = norm.x * p0.x + norm.y * p0.y + norm.z * p0.z;
  18451. t0 = -(norm.x * x + norm.y * y + norm.z * z - d) / (norm.x * norm.x + norm.y * norm.y + norm.z * norm.z);
  18452. projx = x + norm.x * t0;
  18453. projy = y + norm.y * t0;
  18454. projz = z + norm.z * t0;
  18455. tmpx = projx - x;
  18456. tmpy = projy - y;
  18457. tmpz = projz - z;
  18458. tmpDistance = tmpx * tmpx + tmpy * tmpy + tmpz * tmpz; // compute length between (x, y, z) and its projection on the facet
  18459. if (tmpDistance < shortest) {
  18460. shortest = tmpDistance;
  18461. closest = fib;
  18462. if (projected) {
  18463. projected.x = projx;
  18464. projected.y = projy;
  18465. projected.z = projz;
  18466. }
  18467. }
  18468. }
  18469. }
  18470. return closest;
  18471. };
  18472. /**
  18473. * Returns the object "parameter" set with all the expected parameters for facetData computation by ComputeNormals()
  18474. */
  18475. AbstractMesh.prototype.getFacetDataParameters = function () {
  18476. return this._facetParameters;
  18477. };
  18478. /**
  18479. * Disables the feature FacetData and frees the related memory.
  18480. * Returns the AbstractMesh.
  18481. */
  18482. AbstractMesh.prototype.disableFacetData = function () {
  18483. if (this._facetDataEnabled) {
  18484. this._facetDataEnabled = false;
  18485. this._facetPositions = new Array();
  18486. this._facetNormals = new Array();
  18487. this._facetPartitioning = new Array();
  18488. this._facetParameters = null;
  18489. this._depthSortedIndices = new Uint32Array(0);
  18490. }
  18491. return this;
  18492. };
  18493. /**
  18494. * Updates the AbstractMesh indices array. Actually, used by the Mesh object.
  18495. * Returns the mesh.
  18496. */
  18497. AbstractMesh.prototype.updateIndices = function (indices) {
  18498. return this;
  18499. };
  18500. /**
  18501. * The mesh Geometry. Actually used by the Mesh object.
  18502. * Returns a blank geometry object.
  18503. */
  18504. /**
  18505. * Creates new normals data for the mesh.
  18506. * @param updatable.
  18507. */
  18508. AbstractMesh.prototype.createNormals = function (updatable) {
  18509. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  18510. var indices = this.getIndices();
  18511. var normals;
  18512. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  18513. normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  18514. }
  18515. else {
  18516. normals = [];
  18517. }
  18518. BABYLON.VertexData.ComputeNormals(positions, indices, normals, { useRightHandedSystem: this.getScene().useRightHandedSystem });
  18519. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  18520. };
  18521. /**
  18522. * Align the mesh with a normal.
  18523. * Returns the mesh.
  18524. */
  18525. AbstractMesh.prototype.alignWithNormal = function (normal, upDirection) {
  18526. if (!upDirection) {
  18527. upDirection = BABYLON.Axis.Y;
  18528. }
  18529. var axisX = BABYLON.Tmp.Vector3[0];
  18530. var axisZ = BABYLON.Tmp.Vector3[1];
  18531. BABYLON.Vector3.CrossToRef(upDirection, normal, axisZ);
  18532. BABYLON.Vector3.CrossToRef(normal, axisZ, axisX);
  18533. if (this.rotationQuaternion) {
  18534. BABYLON.Quaternion.RotationQuaternionFromAxisToRef(axisX, normal, axisZ, this.rotationQuaternion);
  18535. }
  18536. else {
  18537. BABYLON.Vector3.RotationFromAxisToRef(axisX, normal, axisZ, this.rotation);
  18538. }
  18539. return this;
  18540. };
  18541. AbstractMesh.prototype.checkOcclusionQuery = function () {
  18542. var engine = this.getEngine();
  18543. if (engine.webGLVersion < 2 || this.occlusionType === AbstractMesh.OCCLUSION_TYPE_NONE) {
  18544. this._isOccluded = false;
  18545. return;
  18546. }
  18547. if (this.isOcclusionQueryInProgress && this._occlusionQuery) {
  18548. var isOcclusionQueryAvailable = engine.isQueryResultAvailable(this._occlusionQuery);
  18549. if (isOcclusionQueryAvailable) {
  18550. var occlusionQueryResult = engine.getQueryResult(this._occlusionQuery);
  18551. this._isOcclusionQueryInProgress = false;
  18552. this._occlusionInternalRetryCounter = 0;
  18553. this._isOccluded = occlusionQueryResult === 1 ? false : true;
  18554. }
  18555. else {
  18556. this._occlusionInternalRetryCounter++;
  18557. if (this.occlusionRetryCount !== -1 && this._occlusionInternalRetryCounter > this.occlusionRetryCount) {
  18558. this._isOcclusionQueryInProgress = false;
  18559. this._occlusionInternalRetryCounter = 0;
  18560. // if optimistic set isOccluded to false regardless of the status of isOccluded. (Render in the current render loop)
  18561. // if strict continue the last state of the object.
  18562. this._isOccluded = this.occlusionType === AbstractMesh.OCCLUSION_TYPE_OPTIMISTIC ? false : this._isOccluded;
  18563. }
  18564. else {
  18565. return;
  18566. }
  18567. }
  18568. }
  18569. var scene = this.getScene();
  18570. var occlusionBoundingBoxRenderer = scene.getBoundingBoxRenderer();
  18571. if (!this._occlusionQuery) {
  18572. this._occlusionQuery = engine.createQuery();
  18573. }
  18574. engine.beginOcclusionQuery(this.occlusionQueryAlgorithmType, this._occlusionQuery);
  18575. occlusionBoundingBoxRenderer.renderOcclusionBoundingBox(this);
  18576. engine.endOcclusionQuery(this.occlusionQueryAlgorithmType);
  18577. this._isOcclusionQueryInProgress = true;
  18578. };
  18579. AbstractMesh.OCCLUSION_TYPE_NONE = 0;
  18580. AbstractMesh.OCCLUSION_TYPE_OPTIMISTIC = 1;
  18581. AbstractMesh.OCCLUSION_TYPE_STRICT = 2;
  18582. AbstractMesh.OCCLUSION_ALGORITHM_TYPE_ACCURATE = 0;
  18583. AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE = 1;
  18584. return AbstractMesh;
  18585. }(BABYLON.TransformNode));
  18586. BABYLON.AbstractMesh = AbstractMesh;
  18587. })(BABYLON || (BABYLON = {}));
  18588. //# sourceMappingURL=babylon.abstractMesh.js.map
  18589. var BABYLON;
  18590. (function (BABYLON) {
  18591. /**
  18592. * Base class of all the lights in Babylon. It groups all the generic information about lights.
  18593. * Lights are used, as you would expect, to affect how meshes are seen, in terms of both illumination and colour.
  18594. * All meshes allow light to pass through them unless shadow generation is activated. The default number of lights allowed is four but this can be increased.
  18595. */
  18596. var Light = /** @class */ (function (_super) {
  18597. __extends(Light, _super);
  18598. /**
  18599. * Creates a Light object in the scene.
  18600. * Documentation : http://doc.babylonjs.com/tutorials/lights
  18601. * @param name The firendly name of the light
  18602. * @param scene The scene the light belongs too
  18603. */
  18604. function Light(name, scene) {
  18605. var _this = _super.call(this, name, scene) || this;
  18606. /**
  18607. * Diffuse gives the basic color to an object.
  18608. */
  18609. _this.diffuse = new BABYLON.Color3(1.0, 1.0, 1.0);
  18610. /**
  18611. * Specular produces a highlight color on an object.
  18612. * Note: This is note affecting PBR materials.
  18613. */
  18614. _this.specular = new BABYLON.Color3(1.0, 1.0, 1.0);
  18615. /**
  18616. * Strength of the light.
  18617. * Note: By default it is define in the framework own unit.
  18618. * Note: In PBR materials the intensityMode can be use to chose what unit the intensity is defined in.
  18619. */
  18620. _this.intensity = 1.0;
  18621. /**
  18622. * Defines how far from the source the light is impacting in scene units.
  18623. * Note: Unused in PBR material as the distance light falloff is defined following the inverse squared falloff.
  18624. */
  18625. _this.range = Number.MAX_VALUE;
  18626. /**
  18627. * Cached photometric scale default to 1.0 as the automatic intensity mode defaults to 1.0 for every type
  18628. * of light.
  18629. */
  18630. _this._photometricScale = 1.0;
  18631. _this._intensityMode = Light.INTENSITYMODE_AUTOMATIC;
  18632. _this._radius = 0.00001;
  18633. /**
  18634. * Defines the rendering priority of the lights. It can help in case of fallback or number of lights
  18635. * exceeding the number allowed of the materials.
  18636. */
  18637. _this.renderPriority = 0;
  18638. /**
  18639. * Defines wether or not the shadows are enabled for this light. This can help turning off/on shadow without detaching
  18640. * the current shadow generator.
  18641. */
  18642. _this.shadowEnabled = true;
  18643. _this._excludeWithLayerMask = 0;
  18644. _this._includeOnlyWithLayerMask = 0;
  18645. _this._lightmapMode = 0;
  18646. /**
  18647. * @ignore Internal use only.
  18648. */
  18649. _this._excludedMeshesIds = new Array();
  18650. /**
  18651. * @ignore Internal use only.
  18652. */
  18653. _this._includedOnlyMeshesIds = new Array();
  18654. _this.getScene().addLight(_this);
  18655. _this._uniformBuffer = new BABYLON.UniformBuffer(_this.getScene().getEngine());
  18656. _this._buildUniformLayout();
  18657. _this.includedOnlyMeshes = new Array();
  18658. _this.excludedMeshes = new Array();
  18659. _this._resyncMeshes();
  18660. return _this;
  18661. }
  18662. Object.defineProperty(Light, "LIGHTMAP_DEFAULT", {
  18663. /**
  18664. * If every light affecting the material is in this lightmapMode,
  18665. * material.lightmapTexture adds or multiplies
  18666. * (depends on material.useLightmapAsShadowmap)
  18667. * after every other light calculations.
  18668. */
  18669. get: function () {
  18670. return Light._LIGHTMAP_DEFAULT;
  18671. },
  18672. enumerable: true,
  18673. configurable: true
  18674. });
  18675. Object.defineProperty(Light, "LIGHTMAP_SPECULAR", {
  18676. /**
  18677. * material.lightmapTexture as only diffuse lighting from this light
  18678. * adds only specular lighting from this light
  18679. * adds dynamic shadows
  18680. */
  18681. get: function () {
  18682. return Light._LIGHTMAP_SPECULAR;
  18683. },
  18684. enumerable: true,
  18685. configurable: true
  18686. });
  18687. Object.defineProperty(Light, "LIGHTMAP_SHADOWSONLY", {
  18688. /**
  18689. * material.lightmapTexture as only lighting
  18690. * no light calculation from this light
  18691. * only adds dynamic shadows from this light
  18692. */
  18693. get: function () {
  18694. return Light._LIGHTMAP_SHADOWSONLY;
  18695. },
  18696. enumerable: true,
  18697. configurable: true
  18698. });
  18699. Object.defineProperty(Light, "INTENSITYMODE_AUTOMATIC", {
  18700. /**
  18701. * Each light type uses the default quantity according to its type:
  18702. * point/spot lights use luminous intensity
  18703. * directional lights use illuminance
  18704. */
  18705. get: function () {
  18706. return Light._INTENSITYMODE_AUTOMATIC;
  18707. },
  18708. enumerable: true,
  18709. configurable: true
  18710. });
  18711. Object.defineProperty(Light, "INTENSITYMODE_LUMINOUSPOWER", {
  18712. /**
  18713. * lumen (lm)
  18714. */
  18715. get: function () {
  18716. return Light._INTENSITYMODE_LUMINOUSPOWER;
  18717. },
  18718. enumerable: true,
  18719. configurable: true
  18720. });
  18721. Object.defineProperty(Light, "INTENSITYMODE_LUMINOUSINTENSITY", {
  18722. /**
  18723. * candela (lm/sr)
  18724. */
  18725. get: function () {
  18726. return Light._INTENSITYMODE_LUMINOUSINTENSITY;
  18727. },
  18728. enumerable: true,
  18729. configurable: true
  18730. });
  18731. Object.defineProperty(Light, "INTENSITYMODE_ILLUMINANCE", {
  18732. /**
  18733. * lux (lm/m^2)
  18734. */
  18735. get: function () {
  18736. return Light._INTENSITYMODE_ILLUMINANCE;
  18737. },
  18738. enumerable: true,
  18739. configurable: true
  18740. });
  18741. Object.defineProperty(Light, "INTENSITYMODE_LUMINANCE", {
  18742. /**
  18743. * nit (cd/m^2)
  18744. */
  18745. get: function () {
  18746. return Light._INTENSITYMODE_LUMINANCE;
  18747. },
  18748. enumerable: true,
  18749. configurable: true
  18750. });
  18751. Object.defineProperty(Light, "LIGHTTYPEID_POINTLIGHT", {
  18752. /**
  18753. * Light type const id of the point light.
  18754. */
  18755. get: function () {
  18756. return Light._LIGHTTYPEID_POINTLIGHT;
  18757. },
  18758. enumerable: true,
  18759. configurable: true
  18760. });
  18761. Object.defineProperty(Light, "LIGHTTYPEID_DIRECTIONALLIGHT", {
  18762. /**
  18763. * Light type const id of the directional light.
  18764. */
  18765. get: function () {
  18766. return Light._LIGHTTYPEID_DIRECTIONALLIGHT;
  18767. },
  18768. enumerable: true,
  18769. configurable: true
  18770. });
  18771. Object.defineProperty(Light, "LIGHTTYPEID_SPOTLIGHT", {
  18772. /**
  18773. * Light type const id of the spot light.
  18774. */
  18775. get: function () {
  18776. return Light._LIGHTTYPEID_SPOTLIGHT;
  18777. },
  18778. enumerable: true,
  18779. configurable: true
  18780. });
  18781. Object.defineProperty(Light, "LIGHTTYPEID_HEMISPHERICLIGHT", {
  18782. /**
  18783. * Light type const id of the hemispheric light.
  18784. */
  18785. get: function () {
  18786. return Light._LIGHTTYPEID_HEMISPHERICLIGHT;
  18787. },
  18788. enumerable: true,
  18789. configurable: true
  18790. });
  18791. Object.defineProperty(Light.prototype, "intensityMode", {
  18792. /**
  18793. * Gets the photometric scale used to interpret the intensity.
  18794. * This is only relevant with PBR Materials where the light intensity can be defined in a physical way.
  18795. */
  18796. get: function () {
  18797. return this._intensityMode;
  18798. },
  18799. /**
  18800. * Sets the photometric scale used to interpret the intensity.
  18801. * This is only relevant with PBR Materials where the light intensity can be defined in a physical way.
  18802. */
  18803. set: function (value) {
  18804. this._intensityMode = value;
  18805. this._computePhotometricScale();
  18806. },
  18807. enumerable: true,
  18808. configurable: true
  18809. });
  18810. ;
  18811. ;
  18812. Object.defineProperty(Light.prototype, "radius", {
  18813. /**
  18814. * Gets the light radius used by PBR Materials to simulate soft area lights.
  18815. */
  18816. get: function () {
  18817. return this._radius;
  18818. },
  18819. /**
  18820. * sets the light radius used by PBR Materials to simulate soft area lights.
  18821. */
  18822. set: function (value) {
  18823. this._radius = value;
  18824. this._computePhotometricScale();
  18825. },
  18826. enumerable: true,
  18827. configurable: true
  18828. });
  18829. ;
  18830. ;
  18831. Object.defineProperty(Light.prototype, "includedOnlyMeshes", {
  18832. /**
  18833. * Gets the only meshes impacted by this light.
  18834. */
  18835. get: function () {
  18836. return this._includedOnlyMeshes;
  18837. },
  18838. /**
  18839. * Sets the only meshes impacted by this light.
  18840. */
  18841. set: function (value) {
  18842. this._includedOnlyMeshes = value;
  18843. this._hookArrayForIncludedOnly(value);
  18844. },
  18845. enumerable: true,
  18846. configurable: true
  18847. });
  18848. Object.defineProperty(Light.prototype, "excludedMeshes", {
  18849. /**
  18850. * Gets the meshes not impacted by this light.
  18851. */
  18852. get: function () {
  18853. return this._excludedMeshes;
  18854. },
  18855. /**
  18856. * Sets the meshes not impacted by this light.
  18857. */
  18858. set: function (value) {
  18859. this._excludedMeshes = value;
  18860. this._hookArrayForExcluded(value);
  18861. },
  18862. enumerable: true,
  18863. configurable: true
  18864. });
  18865. Object.defineProperty(Light.prototype, "excludeWithLayerMask", {
  18866. /**
  18867. * Gets the layer id use to find what meshes are not impacted by the light.
  18868. * Inactive if 0
  18869. */
  18870. get: function () {
  18871. return this._excludeWithLayerMask;
  18872. },
  18873. /**
  18874. * Sets the layer id use to find what meshes are not impacted by the light.
  18875. * Inactive if 0
  18876. */
  18877. set: function (value) {
  18878. this._excludeWithLayerMask = value;
  18879. this._resyncMeshes();
  18880. },
  18881. enumerable: true,
  18882. configurable: true
  18883. });
  18884. Object.defineProperty(Light.prototype, "includeOnlyWithLayerMask", {
  18885. /**
  18886. * Gets the layer id use to find what meshes are impacted by the light.
  18887. * Inactive if 0
  18888. */
  18889. get: function () {
  18890. return this._includeOnlyWithLayerMask;
  18891. },
  18892. /**
  18893. * Sets the layer id use to find what meshes are impacted by the light.
  18894. * Inactive if 0
  18895. */
  18896. set: function (value) {
  18897. this._includeOnlyWithLayerMask = value;
  18898. this._resyncMeshes();
  18899. },
  18900. enumerable: true,
  18901. configurable: true
  18902. });
  18903. Object.defineProperty(Light.prototype, "lightmapMode", {
  18904. /**
  18905. * Gets the lightmap mode of this light (should be one of the constants defined by Light.LIGHTMAP_x)
  18906. */
  18907. get: function () {
  18908. return this._lightmapMode;
  18909. },
  18910. /**
  18911. * Sets the lightmap mode of this light (should be one of the constants defined by Light.LIGHTMAP_x)
  18912. */
  18913. set: function (value) {
  18914. if (this._lightmapMode === value) {
  18915. return;
  18916. }
  18917. this._lightmapMode = value;
  18918. this._markMeshesAsLightDirty();
  18919. },
  18920. enumerable: true,
  18921. configurable: true
  18922. });
  18923. /**
  18924. * Returns the string "Light".
  18925. * @returns the class name
  18926. */
  18927. Light.prototype.getClassName = function () {
  18928. return "Light";
  18929. };
  18930. /**
  18931. * Converts the light information to a readable string for debug purpose.
  18932. * @param fullDetails Supports for multiple levels of logging within scene loading
  18933. * @returns the human readable light info
  18934. */
  18935. Light.prototype.toString = function (fullDetails) {
  18936. var ret = "Name: " + this.name;
  18937. ret += ", type: " + (["Point", "Directional", "Spot", "Hemispheric"])[this.getTypeID()];
  18938. if (this.animations) {
  18939. for (var i = 0; i < this.animations.length; i++) {
  18940. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  18941. }
  18942. }
  18943. if (fullDetails) {
  18944. }
  18945. return ret;
  18946. };
  18947. /**
  18948. * Set the enabled state of this node.
  18949. * @param value - the new enabled state
  18950. * @see isEnabled
  18951. */
  18952. Light.prototype.setEnabled = function (value) {
  18953. _super.prototype.setEnabled.call(this, value);
  18954. this._resyncMeshes();
  18955. };
  18956. /**
  18957. * Returns the Light associated shadow generator if any.
  18958. * @return the associated shadow generator.
  18959. */
  18960. Light.prototype.getShadowGenerator = function () {
  18961. return this._shadowGenerator;
  18962. };
  18963. /**
  18964. * Returns a Vector3, the absolute light position in the World.
  18965. * @returns the world space position of the light
  18966. */
  18967. Light.prototype.getAbsolutePosition = function () {
  18968. return BABYLON.Vector3.Zero();
  18969. };
  18970. /**
  18971. * Specifies if the light will affect the passed mesh.
  18972. * @param mesh The mesh to test against the light
  18973. * @return true the mesh is affected otherwise, false.
  18974. */
  18975. Light.prototype.canAffectMesh = function (mesh) {
  18976. if (!mesh) {
  18977. return true;
  18978. }
  18979. if (this.includedOnlyMeshes && this.includedOnlyMeshes.length > 0 && this.includedOnlyMeshes.indexOf(mesh) === -1) {
  18980. return false;
  18981. }
  18982. if (this.excludedMeshes && this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  18983. return false;
  18984. }
  18985. if (this.includeOnlyWithLayerMask !== 0 && (this.includeOnlyWithLayerMask & mesh.layerMask) === 0) {
  18986. return false;
  18987. }
  18988. if (this.excludeWithLayerMask !== 0 && this.excludeWithLayerMask & mesh.layerMask) {
  18989. return false;
  18990. }
  18991. return true;
  18992. };
  18993. /**
  18994. * Computes and Returns the light World matrix.
  18995. * @returns the world matrix
  18996. */
  18997. Light.prototype.getWorldMatrix = function () {
  18998. this._currentRenderId = this.getScene().getRenderId();
  18999. var worldMatrix = this._getWorldMatrix();
  19000. if (this.parent && this.parent.getWorldMatrix) {
  19001. if (!this._parentedWorldMatrix) {
  19002. this._parentedWorldMatrix = BABYLON.Matrix.Identity();
  19003. }
  19004. worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._parentedWorldMatrix);
  19005. this._markSyncedWithParent();
  19006. return this._parentedWorldMatrix;
  19007. }
  19008. return worldMatrix;
  19009. };
  19010. /**
  19011. * Sort function to order lights for rendering.
  19012. * @param a First Light object to compare to second.
  19013. * @param b Second Light object to compare first.
  19014. * @return -1 to reduce's a's index relative to be, 0 for no change, 1 to increase a's index relative to b.
  19015. */
  19016. Light.CompareLightsPriority = function (a, b) {
  19017. //shadow-casting lights have priority over non-shadow-casting lights
  19018. //the renderPrioirty is a secondary sort criterion
  19019. if (a.shadowEnabled !== b.shadowEnabled) {
  19020. return (b.shadowEnabled ? 1 : 0) - (a.shadowEnabled ? 1 : 0);
  19021. }
  19022. return b.renderPriority - a.renderPriority;
  19023. };
  19024. /**
  19025. * Disposes the light.
  19026. */
  19027. Light.prototype.dispose = function () {
  19028. if (this._shadowGenerator) {
  19029. this._shadowGenerator.dispose();
  19030. this._shadowGenerator = null;
  19031. }
  19032. // Animations
  19033. this.getScene().stopAnimation(this);
  19034. // Remove from meshes
  19035. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  19036. var mesh = _a[_i];
  19037. mesh._removeLightSource(this);
  19038. }
  19039. this._uniformBuffer.dispose();
  19040. // Remove from scene
  19041. this.getScene().removeLight(this);
  19042. _super.prototype.dispose.call(this);
  19043. };
  19044. /**
  19045. * Returns the light type ID (integer).
  19046. * @returns The light Type id as a constant defines in Light.LIGHTTYPEID_x
  19047. */
  19048. Light.prototype.getTypeID = function () {
  19049. return 0;
  19050. };
  19051. /**
  19052. * Returns the intensity scaled by the Photometric Scale according to the light type and intensity mode.
  19053. * @returns the scaled intensity in intensity mode unit
  19054. */
  19055. Light.prototype.getScaledIntensity = function () {
  19056. return this._photometricScale * this.intensity;
  19057. };
  19058. /**
  19059. * Returns a new Light object, named "name", from the current one.
  19060. * @param name The name of the cloned light
  19061. * @returns the new created light
  19062. */
  19063. Light.prototype.clone = function (name) {
  19064. var constructor = Light.GetConstructorFromName(this.getTypeID(), name, this.getScene());
  19065. if (!constructor) {
  19066. return null;
  19067. }
  19068. return BABYLON.SerializationHelper.Clone(constructor, this);
  19069. };
  19070. /**
  19071. * Serializes the current light into a Serialization object.
  19072. * @returns the serialized object.
  19073. */
  19074. Light.prototype.serialize = function () {
  19075. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  19076. // Type
  19077. serializationObject.type = this.getTypeID();
  19078. // Parent
  19079. if (this.parent) {
  19080. serializationObject.parentId = this.parent.id;
  19081. }
  19082. // Inclusion / exclusions
  19083. if (this.excludedMeshes.length > 0) {
  19084. serializationObject.excludedMeshesIds = [];
  19085. this.excludedMeshes.forEach(function (mesh) {
  19086. serializationObject.excludedMeshesIds.push(mesh.id);
  19087. });
  19088. }
  19089. if (this.includedOnlyMeshes.length > 0) {
  19090. serializationObject.includedOnlyMeshesIds = [];
  19091. this.includedOnlyMeshes.forEach(function (mesh) {
  19092. serializationObject.includedOnlyMeshesIds.push(mesh.id);
  19093. });
  19094. }
  19095. // Animations
  19096. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  19097. serializationObject.ranges = this.serializeAnimationRanges();
  19098. return serializationObject;
  19099. };
  19100. /**
  19101. * Creates a new typed light from the passed type (integer) : point light = 0, directional light = 1, spot light = 2, hemispheric light = 3.
  19102. * This new light is named "name" and added to the passed scene.
  19103. * @param type Type according to the types available in Light.LIGHTTYPEID_x
  19104. * @param name The friendly name of the light
  19105. * @param scene The scene the new light will belong to
  19106. * @returns the constructor function
  19107. */
  19108. Light.GetConstructorFromName = function (type, name, scene) {
  19109. switch (type) {
  19110. case 0:
  19111. return function () { return new BABYLON.PointLight(name, BABYLON.Vector3.Zero(), scene); };
  19112. case 1:
  19113. return function () { return new BABYLON.DirectionalLight(name, BABYLON.Vector3.Zero(), scene); };
  19114. case 2:
  19115. return function () { return new BABYLON.SpotLight(name, BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), 0, 0, scene); };
  19116. case 3:
  19117. return function () { return new BABYLON.HemisphericLight(name, BABYLON.Vector3.Zero(), scene); };
  19118. }
  19119. return null;
  19120. };
  19121. /**
  19122. * Parses the passed "parsedLight" and returns a new instanced Light from this parsing.
  19123. * @param parsedLight The JSON representation of the light
  19124. * @param scene The scene to create the parsed light in
  19125. * @returns the created light after parsing
  19126. */
  19127. Light.Parse = function (parsedLight, scene) {
  19128. var constructor = Light.GetConstructorFromName(parsedLight.type, parsedLight.name, scene);
  19129. if (!constructor) {
  19130. return null;
  19131. }
  19132. var light = BABYLON.SerializationHelper.Parse(constructor, parsedLight, scene);
  19133. // Inclusion / exclusions
  19134. if (parsedLight.excludedMeshesIds) {
  19135. light._excludedMeshesIds = parsedLight.excludedMeshesIds;
  19136. }
  19137. if (parsedLight.includedOnlyMeshesIds) {
  19138. light._includedOnlyMeshesIds = parsedLight.includedOnlyMeshesIds;
  19139. }
  19140. // Parent
  19141. if (parsedLight.parentId) {
  19142. light._waitingParentId = parsedLight.parentId;
  19143. }
  19144. // Animations
  19145. if (parsedLight.animations) {
  19146. for (var animationIndex = 0; animationIndex < parsedLight.animations.length; animationIndex++) {
  19147. var parsedAnimation = parsedLight.animations[animationIndex];
  19148. light.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  19149. }
  19150. BABYLON.Node.ParseAnimationRanges(light, parsedLight, scene);
  19151. }
  19152. if (parsedLight.autoAnimate) {
  19153. scene.beginAnimation(light, parsedLight.autoAnimateFrom, parsedLight.autoAnimateTo, parsedLight.autoAnimateLoop, parsedLight.autoAnimateSpeed || 1.0);
  19154. }
  19155. return light;
  19156. };
  19157. Light.prototype._hookArrayForExcluded = function (array) {
  19158. var _this = this;
  19159. var oldPush = array.push;
  19160. array.push = function () {
  19161. var items = [];
  19162. for (var _i = 0; _i < arguments.length; _i++) {
  19163. items[_i] = arguments[_i];
  19164. }
  19165. var result = oldPush.apply(array, items);
  19166. for (var _a = 0, items_1 = items; _a < items_1.length; _a++) {
  19167. var item = items_1[_a];
  19168. item._resyncLighSource(_this);
  19169. }
  19170. return result;
  19171. };
  19172. var oldSplice = array.splice;
  19173. array.splice = function (index, deleteCount) {
  19174. var deleted = oldSplice.apply(array, [index, deleteCount]);
  19175. for (var _i = 0, deleted_1 = deleted; _i < deleted_1.length; _i++) {
  19176. var item = deleted_1[_i];
  19177. item._resyncLighSource(_this);
  19178. }
  19179. return deleted;
  19180. };
  19181. for (var _i = 0, array_1 = array; _i < array_1.length; _i++) {
  19182. var item = array_1[_i];
  19183. item._resyncLighSource(this);
  19184. }
  19185. };
  19186. Light.prototype._hookArrayForIncludedOnly = function (array) {
  19187. var _this = this;
  19188. var oldPush = array.push;
  19189. array.push = function () {
  19190. var items = [];
  19191. for (var _i = 0; _i < arguments.length; _i++) {
  19192. items[_i] = arguments[_i];
  19193. }
  19194. var result = oldPush.apply(array, items);
  19195. _this._resyncMeshes();
  19196. return result;
  19197. };
  19198. var oldSplice = array.splice;
  19199. array.splice = function (index, deleteCount) {
  19200. var deleted = oldSplice.apply(array, [index, deleteCount]);
  19201. _this._resyncMeshes();
  19202. return deleted;
  19203. };
  19204. this._resyncMeshes();
  19205. };
  19206. Light.prototype._resyncMeshes = function () {
  19207. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  19208. var mesh = _a[_i];
  19209. mesh._resyncLighSource(this);
  19210. }
  19211. };
  19212. /**
  19213. * Forces the meshes to update their light related information in their rendering used effects
  19214. * @ignore Internal Use Only
  19215. */
  19216. Light.prototype._markMeshesAsLightDirty = function () {
  19217. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  19218. var mesh = _a[_i];
  19219. if (mesh._lightSources.indexOf(this) !== -1) {
  19220. mesh._markSubMeshesAsLightDirty();
  19221. }
  19222. }
  19223. };
  19224. /**
  19225. * Recomputes the cached photometric scale if needed.
  19226. */
  19227. Light.prototype._computePhotometricScale = function () {
  19228. this._photometricScale = this._getPhotometricScale();
  19229. this.getScene().resetCachedMaterial();
  19230. };
  19231. /**
  19232. * Returns the Photometric Scale according to the light type and intensity mode.
  19233. */
  19234. Light.prototype._getPhotometricScale = function () {
  19235. var photometricScale = 0.0;
  19236. var lightTypeID = this.getTypeID();
  19237. //get photometric mode
  19238. var photometricMode = this.intensityMode;
  19239. if (photometricMode === Light.INTENSITYMODE_AUTOMATIC) {
  19240. if (lightTypeID === Light.LIGHTTYPEID_DIRECTIONALLIGHT) {
  19241. photometricMode = Light.INTENSITYMODE_ILLUMINANCE;
  19242. }
  19243. else {
  19244. photometricMode = Light.INTENSITYMODE_LUMINOUSINTENSITY;
  19245. }
  19246. }
  19247. //compute photometric scale
  19248. switch (lightTypeID) {
  19249. case Light.LIGHTTYPEID_POINTLIGHT:
  19250. case Light.LIGHTTYPEID_SPOTLIGHT:
  19251. switch (photometricMode) {
  19252. case Light.INTENSITYMODE_LUMINOUSPOWER:
  19253. photometricScale = 1.0 / (4.0 * Math.PI);
  19254. break;
  19255. case Light.INTENSITYMODE_LUMINOUSINTENSITY:
  19256. photometricScale = 1.0;
  19257. break;
  19258. case Light.INTENSITYMODE_LUMINANCE:
  19259. photometricScale = this.radius * this.radius;
  19260. break;
  19261. }
  19262. break;
  19263. case Light.LIGHTTYPEID_DIRECTIONALLIGHT:
  19264. switch (photometricMode) {
  19265. case Light.INTENSITYMODE_ILLUMINANCE:
  19266. photometricScale = 1.0;
  19267. break;
  19268. case Light.INTENSITYMODE_LUMINANCE:
  19269. // When radius (and therefore solid angle) is non-zero a directional lights brightness can be specified via central (peak) luminance.
  19270. // For a directional light the 'radius' defines the angular radius (in radians) rather than world-space radius (e.g. in metres).
  19271. var apexAngleRadians = this.radius;
  19272. // Impose a minimum light angular size to avoid the light becoming an infinitely small angular light source (i.e. a dirac delta function).
  19273. apexAngleRadians = Math.max(apexAngleRadians, 0.001);
  19274. var solidAngle = 2.0 * Math.PI * (1.0 - Math.cos(apexAngleRadians));
  19275. photometricScale = solidAngle;
  19276. break;
  19277. }
  19278. break;
  19279. case Light.LIGHTTYPEID_HEMISPHERICLIGHT:
  19280. // No fall off in hemisperic light.
  19281. photometricScale = 1.0;
  19282. break;
  19283. }
  19284. return photometricScale;
  19285. };
  19286. /**
  19287. * Reorder the light in the scene according to their defined priority.
  19288. * @ignore Internal Use Only
  19289. */
  19290. Light.prototype._reorderLightsInScene = function () {
  19291. var scene = this.getScene();
  19292. if (this._renderPriority != 0) {
  19293. scene.requireLightSorting = true;
  19294. }
  19295. this.getScene().sortLightsByPriority();
  19296. };
  19297. //lightmapMode Consts
  19298. Light._LIGHTMAP_DEFAULT = 0;
  19299. Light._LIGHTMAP_SPECULAR = 1;
  19300. Light._LIGHTMAP_SHADOWSONLY = 2;
  19301. // Intensity Mode Consts
  19302. Light._INTENSITYMODE_AUTOMATIC = 0;
  19303. Light._INTENSITYMODE_LUMINOUSPOWER = 1;
  19304. Light._INTENSITYMODE_LUMINOUSINTENSITY = 2;
  19305. Light._INTENSITYMODE_ILLUMINANCE = 3;
  19306. Light._INTENSITYMODE_LUMINANCE = 4;
  19307. // Light types ids const.
  19308. Light._LIGHTTYPEID_POINTLIGHT = 0;
  19309. Light._LIGHTTYPEID_DIRECTIONALLIGHT = 1;
  19310. Light._LIGHTTYPEID_SPOTLIGHT = 2;
  19311. Light._LIGHTTYPEID_HEMISPHERICLIGHT = 3;
  19312. __decorate([
  19313. BABYLON.serializeAsColor3()
  19314. ], Light.prototype, "diffuse", void 0);
  19315. __decorate([
  19316. BABYLON.serializeAsColor3()
  19317. ], Light.prototype, "specular", void 0);
  19318. __decorate([
  19319. BABYLON.serialize()
  19320. ], Light.prototype, "intensity", void 0);
  19321. __decorate([
  19322. BABYLON.serialize()
  19323. ], Light.prototype, "range", void 0);
  19324. __decorate([
  19325. BABYLON.serialize()
  19326. ], Light.prototype, "intensityMode", null);
  19327. __decorate([
  19328. BABYLON.serialize()
  19329. ], Light.prototype, "radius", null);
  19330. __decorate([
  19331. BABYLON.serialize()
  19332. ], Light.prototype, "_renderPriority", void 0);
  19333. __decorate([
  19334. BABYLON.expandToProperty("_reorderLightsInScene")
  19335. ], Light.prototype, "renderPriority", void 0);
  19336. __decorate([
  19337. BABYLON.serialize()
  19338. ], Light.prototype, "shadowEnabled", void 0);
  19339. __decorate([
  19340. BABYLON.serialize("excludeWithLayerMask")
  19341. ], Light.prototype, "_excludeWithLayerMask", void 0);
  19342. __decorate([
  19343. BABYLON.serialize("includeOnlyWithLayerMask")
  19344. ], Light.prototype, "_includeOnlyWithLayerMask", void 0);
  19345. __decorate([
  19346. BABYLON.serialize("lightmapMode")
  19347. ], Light.prototype, "_lightmapMode", void 0);
  19348. return Light;
  19349. }(BABYLON.Node));
  19350. BABYLON.Light = Light;
  19351. })(BABYLON || (BABYLON = {}));
  19352. //# sourceMappingURL=babylon.light.js.map
  19353. var BABYLON;
  19354. (function (BABYLON) {
  19355. var Camera = /** @class */ (function (_super) {
  19356. __extends(Camera, _super);
  19357. function Camera(name, position, scene) {
  19358. var _this = _super.call(this, name, scene) || this;
  19359. /**
  19360. * The vector the camera should consider as up.
  19361. * (default is Vector3(0, 1, 0) aka Vector3.Up())
  19362. */
  19363. _this.upVector = BABYLON.Vector3.Up();
  19364. _this.orthoLeft = null;
  19365. _this.orthoRight = null;
  19366. _this.orthoBottom = null;
  19367. _this.orthoTop = null;
  19368. /**
  19369. * FOV is set in Radians. (default is 0.8)
  19370. */
  19371. _this.fov = 0.8;
  19372. _this.minZ = 1;
  19373. _this.maxZ = 10000.0;
  19374. _this.inertia = 0.9;
  19375. _this.mode = Camera.PERSPECTIVE_CAMERA;
  19376. _this.isIntermediate = false;
  19377. _this.viewport = new BABYLON.Viewport(0, 0, 1.0, 1.0);
  19378. /**
  19379. * Restricts the camera to viewing objects with the same layerMask.
  19380. * A camera with a layerMask of 1 will render mesh.layerMask & camera.layerMask!== 0
  19381. */
  19382. _this.layerMask = 0x0FFFFFFF;
  19383. /**
  19384. * fovMode sets the camera frustum bounds to the viewport bounds. (default is FOVMODE_VERTICAL_FIXED)
  19385. */
  19386. _this.fovMode = Camera.FOVMODE_VERTICAL_FIXED;
  19387. // Camera rig members
  19388. _this.cameraRigMode = Camera.RIG_MODE_NONE;
  19389. _this._rigCameras = new Array();
  19390. _this._webvrViewMatrix = BABYLON.Matrix.Identity();
  19391. _this._skipRendering = false;
  19392. _this.customRenderTargets = new Array();
  19393. // Observables
  19394. _this.onViewMatrixChangedObservable = new BABYLON.Observable();
  19395. _this.onProjectionMatrixChangedObservable = new BABYLON.Observable();
  19396. _this.onAfterCheckInputsObservable = new BABYLON.Observable();
  19397. _this.onRestoreStateObservable = new BABYLON.Observable();
  19398. // Cache
  19399. _this._computedViewMatrix = BABYLON.Matrix.Identity();
  19400. _this._projectionMatrix = new BABYLON.Matrix();
  19401. _this._doNotComputeProjectionMatrix = false;
  19402. _this._postProcesses = new Array();
  19403. _this._transformMatrix = BABYLON.Matrix.Zero();
  19404. _this._activeMeshes = new BABYLON.SmartArray(256);
  19405. _this._globalPosition = BABYLON.Vector3.Zero();
  19406. _this._refreshFrustumPlanes = true;
  19407. _this.getScene().addCamera(_this);
  19408. if (!_this.getScene().activeCamera) {
  19409. _this.getScene().activeCamera = _this;
  19410. }
  19411. _this.position = position;
  19412. return _this;
  19413. }
  19414. Object.defineProperty(Camera, "PERSPECTIVE_CAMERA", {
  19415. get: function () {
  19416. return Camera._PERSPECTIVE_CAMERA;
  19417. },
  19418. enumerable: true,
  19419. configurable: true
  19420. });
  19421. Object.defineProperty(Camera, "ORTHOGRAPHIC_CAMERA", {
  19422. get: function () {
  19423. return Camera._ORTHOGRAPHIC_CAMERA;
  19424. },
  19425. enumerable: true,
  19426. configurable: true
  19427. });
  19428. Object.defineProperty(Camera, "FOVMODE_VERTICAL_FIXED", {
  19429. /**
  19430. * This is the default FOV mode for perspective cameras.
  19431. * This setting aligns the upper and lower bounds of the viewport to the upper and lower bounds of the camera frustum.
  19432. *
  19433. */
  19434. get: function () {
  19435. return Camera._FOVMODE_VERTICAL_FIXED;
  19436. },
  19437. enumerable: true,
  19438. configurable: true
  19439. });
  19440. Object.defineProperty(Camera, "FOVMODE_HORIZONTAL_FIXED", {
  19441. /**
  19442. * This setting aligns the left and right bounds of the viewport to the left and right bounds of the camera frustum.
  19443. *
  19444. */
  19445. get: function () {
  19446. return Camera._FOVMODE_HORIZONTAL_FIXED;
  19447. },
  19448. enumerable: true,
  19449. configurable: true
  19450. });
  19451. Object.defineProperty(Camera, "RIG_MODE_NONE", {
  19452. get: function () {
  19453. return Camera._RIG_MODE_NONE;
  19454. },
  19455. enumerable: true,
  19456. configurable: true
  19457. });
  19458. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_ANAGLYPH", {
  19459. get: function () {
  19460. return Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH;
  19461. },
  19462. enumerable: true,
  19463. configurable: true
  19464. });
  19465. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL", {
  19466. get: function () {
  19467. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL;
  19468. },
  19469. enumerable: true,
  19470. configurable: true
  19471. });
  19472. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED", {
  19473. get: function () {
  19474. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  19475. },
  19476. enumerable: true,
  19477. configurable: true
  19478. });
  19479. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_OVERUNDER", {
  19480. get: function () {
  19481. return Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER;
  19482. },
  19483. enumerable: true,
  19484. configurable: true
  19485. });
  19486. Object.defineProperty(Camera, "RIG_MODE_VR", {
  19487. get: function () {
  19488. return Camera._RIG_MODE_VR;
  19489. },
  19490. enumerable: true,
  19491. configurable: true
  19492. });
  19493. Object.defineProperty(Camera, "RIG_MODE_WEBVR", {
  19494. get: function () {
  19495. return Camera._RIG_MODE_WEBVR;
  19496. },
  19497. enumerable: true,
  19498. configurable: true
  19499. });
  19500. /**
  19501. * Store current camera state (fov, position, etc..)
  19502. */
  19503. Camera.prototype.storeState = function () {
  19504. this._stateStored = true;
  19505. this._storedFov = this.fov;
  19506. return this;
  19507. };
  19508. /**
  19509. * Restores the camera state values if it has been stored. You must call storeState() first
  19510. */
  19511. Camera.prototype._restoreStateValues = function () {
  19512. if (!this._stateStored) {
  19513. return false;
  19514. }
  19515. this.fov = this._storedFov;
  19516. return true;
  19517. };
  19518. /**
  19519. * Restored camera state. You must call storeState() first
  19520. */
  19521. Camera.prototype.restoreState = function () {
  19522. if (this._restoreStateValues()) {
  19523. this.onRestoreStateObservable.notifyObservers(this);
  19524. return true;
  19525. }
  19526. return false;
  19527. };
  19528. Camera.prototype.getClassName = function () {
  19529. return "Camera";
  19530. };
  19531. /**
  19532. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  19533. */
  19534. Camera.prototype.toString = function (fullDetails) {
  19535. var ret = "Name: " + this.name;
  19536. ret += ", type: " + this.getClassName();
  19537. if (this.animations) {
  19538. for (var i = 0; i < this.animations.length; i++) {
  19539. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  19540. }
  19541. }
  19542. if (fullDetails) {
  19543. }
  19544. return ret;
  19545. };
  19546. Object.defineProperty(Camera.prototype, "globalPosition", {
  19547. get: function () {
  19548. return this._globalPosition;
  19549. },
  19550. enumerable: true,
  19551. configurable: true
  19552. });
  19553. Camera.prototype.getActiveMeshes = function () {
  19554. return this._activeMeshes;
  19555. };
  19556. Camera.prototype.isActiveMesh = function (mesh) {
  19557. return (this._activeMeshes.indexOf(mesh) !== -1);
  19558. };
  19559. //Cache
  19560. Camera.prototype._initCache = function () {
  19561. _super.prototype._initCache.call(this);
  19562. this._cache.position = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  19563. this._cache.upVector = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  19564. this._cache.mode = undefined;
  19565. this._cache.minZ = undefined;
  19566. this._cache.maxZ = undefined;
  19567. this._cache.fov = undefined;
  19568. this._cache.fovMode = undefined;
  19569. this._cache.aspectRatio = undefined;
  19570. this._cache.orthoLeft = undefined;
  19571. this._cache.orthoRight = undefined;
  19572. this._cache.orthoBottom = undefined;
  19573. this._cache.orthoTop = undefined;
  19574. this._cache.renderWidth = undefined;
  19575. this._cache.renderHeight = undefined;
  19576. };
  19577. Camera.prototype._updateCache = function (ignoreParentClass) {
  19578. if (!ignoreParentClass) {
  19579. _super.prototype._updateCache.call(this);
  19580. }
  19581. this._cache.position.copyFrom(this.position);
  19582. this._cache.upVector.copyFrom(this.upVector);
  19583. };
  19584. // Synchronized
  19585. Camera.prototype._isSynchronized = function () {
  19586. return this._isSynchronizedViewMatrix() && this._isSynchronizedProjectionMatrix();
  19587. };
  19588. Camera.prototype._isSynchronizedViewMatrix = function () {
  19589. if (!_super.prototype._isSynchronized.call(this))
  19590. return false;
  19591. return this._cache.position.equals(this.position)
  19592. && this._cache.upVector.equals(this.upVector)
  19593. && this.isSynchronizedWithParent();
  19594. };
  19595. Camera.prototype._isSynchronizedProjectionMatrix = function () {
  19596. var check = this._cache.mode === this.mode
  19597. && this._cache.minZ === this.minZ
  19598. && this._cache.maxZ === this.maxZ;
  19599. if (!check) {
  19600. return false;
  19601. }
  19602. var engine = this.getEngine();
  19603. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  19604. check = this._cache.fov === this.fov
  19605. && this._cache.fovMode === this.fovMode
  19606. && this._cache.aspectRatio === engine.getAspectRatio(this);
  19607. }
  19608. else {
  19609. check = this._cache.orthoLeft === this.orthoLeft
  19610. && this._cache.orthoRight === this.orthoRight
  19611. && this._cache.orthoBottom === this.orthoBottom
  19612. && this._cache.orthoTop === this.orthoTop
  19613. && this._cache.renderWidth === engine.getRenderWidth()
  19614. && this._cache.renderHeight === engine.getRenderHeight();
  19615. }
  19616. return check;
  19617. };
  19618. // Controls
  19619. Camera.prototype.attachControl = function (element, noPreventDefault) {
  19620. };
  19621. Camera.prototype.detachControl = function (element) {
  19622. };
  19623. Camera.prototype.update = function () {
  19624. this._checkInputs();
  19625. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  19626. this._updateRigCameras();
  19627. }
  19628. };
  19629. Camera.prototype._checkInputs = function () {
  19630. this.onAfterCheckInputsObservable.notifyObservers(this);
  19631. };
  19632. Object.defineProperty(Camera.prototype, "rigCameras", {
  19633. get: function () {
  19634. return this._rigCameras;
  19635. },
  19636. enumerable: true,
  19637. configurable: true
  19638. });
  19639. Object.defineProperty(Camera.prototype, "rigPostProcess", {
  19640. get: function () {
  19641. return this._rigPostProcess;
  19642. },
  19643. enumerable: true,
  19644. configurable: true
  19645. });
  19646. Camera.prototype._cascadePostProcessesToRigCams = function () {
  19647. // invalidate framebuffer
  19648. if (this._postProcesses.length > 0) {
  19649. this._postProcesses[0].markTextureDirty();
  19650. }
  19651. // glue the rigPostProcess to the end of the user postprocesses & assign to each sub-camera
  19652. for (var i = 0, len = this._rigCameras.length; i < len; i++) {
  19653. var cam = this._rigCameras[i];
  19654. var rigPostProcess = cam._rigPostProcess;
  19655. // for VR rig, there does not have to be a post process
  19656. if (rigPostProcess) {
  19657. var isPass = rigPostProcess instanceof BABYLON.PassPostProcess;
  19658. if (isPass) {
  19659. // any rig which has a PassPostProcess for rig[0], cannot be isIntermediate when there are also user postProcesses
  19660. cam.isIntermediate = this._postProcesses.length === 0;
  19661. }
  19662. cam._postProcesses = this._postProcesses.slice(0).concat(rigPostProcess);
  19663. rigPostProcess.markTextureDirty();
  19664. }
  19665. else {
  19666. cam._postProcesses = this._postProcesses.slice(0);
  19667. }
  19668. }
  19669. };
  19670. Camera.prototype.attachPostProcess = function (postProcess, insertAt) {
  19671. if (insertAt === void 0) { insertAt = null; }
  19672. if (!postProcess.isReusable() && this._postProcesses.indexOf(postProcess) > -1) {
  19673. BABYLON.Tools.Error("You're trying to reuse a post process not defined as reusable.");
  19674. return 0;
  19675. }
  19676. if (insertAt == null || insertAt < 0) {
  19677. this._postProcesses.push(postProcess);
  19678. }
  19679. else {
  19680. this._postProcesses.splice(insertAt, 0, postProcess);
  19681. }
  19682. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  19683. return this._postProcesses.indexOf(postProcess);
  19684. };
  19685. Camera.prototype.detachPostProcess = function (postProcess) {
  19686. var idx = this._postProcesses.indexOf(postProcess);
  19687. if (idx !== -1) {
  19688. this._postProcesses.splice(idx, 1);
  19689. }
  19690. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  19691. };
  19692. Camera.prototype.getWorldMatrix = function () {
  19693. if (!this._worldMatrix) {
  19694. this._worldMatrix = BABYLON.Matrix.Identity();
  19695. }
  19696. var viewMatrix = this.getViewMatrix();
  19697. viewMatrix.invertToRef(this._worldMatrix);
  19698. return this._worldMatrix;
  19699. };
  19700. Camera.prototype._getViewMatrix = function () {
  19701. return BABYLON.Matrix.Identity();
  19702. };
  19703. Camera.prototype.getViewMatrix = function (force) {
  19704. if (!force && this._isSynchronizedViewMatrix()) {
  19705. return this._computedViewMatrix;
  19706. }
  19707. this.updateCache();
  19708. this._computedViewMatrix = this._getViewMatrix();
  19709. this._currentRenderId = this.getScene().getRenderId();
  19710. this._refreshFrustumPlanes = true;
  19711. if (!this.parent || !this.parent.getWorldMatrix) {
  19712. this._globalPosition.copyFrom(this.position);
  19713. }
  19714. else {
  19715. if (!this._worldMatrix) {
  19716. this._worldMatrix = BABYLON.Matrix.Identity();
  19717. }
  19718. this._computedViewMatrix.invertToRef(this._worldMatrix);
  19719. this._worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._computedViewMatrix);
  19720. this._globalPosition.copyFromFloats(this._computedViewMatrix.m[12], this._computedViewMatrix.m[13], this._computedViewMatrix.m[14]);
  19721. this._computedViewMatrix.invert();
  19722. this._markSyncedWithParent();
  19723. }
  19724. if (this._cameraRigParams && this._cameraRigParams.vrPreViewMatrix) {
  19725. this._computedViewMatrix.multiplyToRef(this._cameraRigParams.vrPreViewMatrix, this._computedViewMatrix);
  19726. }
  19727. this.onViewMatrixChangedObservable.notifyObservers(this);
  19728. return this._computedViewMatrix;
  19729. };
  19730. Camera.prototype.freezeProjectionMatrix = function (projection) {
  19731. this._doNotComputeProjectionMatrix = true;
  19732. if (projection !== undefined) {
  19733. this._projectionMatrix = projection;
  19734. }
  19735. };
  19736. ;
  19737. Camera.prototype.unfreezeProjectionMatrix = function () {
  19738. this._doNotComputeProjectionMatrix = false;
  19739. };
  19740. ;
  19741. Camera.prototype.getProjectionMatrix = function (force) {
  19742. if (this._doNotComputeProjectionMatrix || (!force && this._isSynchronizedProjectionMatrix())) {
  19743. return this._projectionMatrix;
  19744. }
  19745. // Cache
  19746. this._cache.mode = this.mode;
  19747. this._cache.minZ = this.minZ;
  19748. this._cache.maxZ = this.maxZ;
  19749. // Matrix
  19750. this._refreshFrustumPlanes = true;
  19751. var engine = this.getEngine();
  19752. var scene = this.getScene();
  19753. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  19754. this._cache.fov = this.fov;
  19755. this._cache.fovMode = this.fovMode;
  19756. this._cache.aspectRatio = engine.getAspectRatio(this);
  19757. if (this.minZ <= 0) {
  19758. this.minZ = 0.1;
  19759. }
  19760. if (scene.useRightHandedSystem) {
  19761. BABYLON.Matrix.PerspectiveFovRHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  19762. }
  19763. else {
  19764. BABYLON.Matrix.PerspectiveFovLHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  19765. }
  19766. }
  19767. else {
  19768. var halfWidth = engine.getRenderWidth() / 2.0;
  19769. var halfHeight = engine.getRenderHeight() / 2.0;
  19770. if (scene.useRightHandedSystem) {
  19771. BABYLON.Matrix.OrthoOffCenterRHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  19772. }
  19773. else {
  19774. BABYLON.Matrix.OrthoOffCenterLHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  19775. }
  19776. this._cache.orthoLeft = this.orthoLeft;
  19777. this._cache.orthoRight = this.orthoRight;
  19778. this._cache.orthoBottom = this.orthoBottom;
  19779. this._cache.orthoTop = this.orthoTop;
  19780. this._cache.renderWidth = engine.getRenderWidth();
  19781. this._cache.renderHeight = engine.getRenderHeight();
  19782. }
  19783. this.onProjectionMatrixChangedObservable.notifyObservers(this);
  19784. return this._projectionMatrix;
  19785. };
  19786. Camera.prototype.getTranformationMatrix = function () {
  19787. this._computedViewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  19788. return this._transformMatrix;
  19789. };
  19790. Camera.prototype.updateFrustumPlanes = function () {
  19791. if (!this._refreshFrustumPlanes) {
  19792. return;
  19793. }
  19794. this.getTranformationMatrix();
  19795. if (!this._frustumPlanes) {
  19796. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  19797. }
  19798. else {
  19799. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  19800. }
  19801. this._refreshFrustumPlanes = false;
  19802. };
  19803. Camera.prototype.isInFrustum = function (target) {
  19804. this.updateFrustumPlanes();
  19805. return target.isInFrustum(this._frustumPlanes);
  19806. };
  19807. Camera.prototype.isCompletelyInFrustum = function (target) {
  19808. this.updateFrustumPlanes();
  19809. return target.isCompletelyInFrustum(this._frustumPlanes);
  19810. };
  19811. Camera.prototype.getForwardRay = function (length, transform, origin) {
  19812. if (length === void 0) { length = 100; }
  19813. if (!transform) {
  19814. transform = this.getWorldMatrix();
  19815. }
  19816. if (!origin) {
  19817. origin = this.position;
  19818. }
  19819. var forward = new BABYLON.Vector3(0, 0, 1);
  19820. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, transform);
  19821. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  19822. return new BABYLON.Ray(origin, direction, length);
  19823. };
  19824. Camera.prototype.dispose = function () {
  19825. // Observables
  19826. this.onViewMatrixChangedObservable.clear();
  19827. this.onProjectionMatrixChangedObservable.clear();
  19828. this.onAfterCheckInputsObservable.clear();
  19829. this.onRestoreStateObservable.clear();
  19830. // Inputs
  19831. if (this.inputs) {
  19832. this.inputs.clear();
  19833. }
  19834. // Animations
  19835. this.getScene().stopAnimation(this);
  19836. // Remove from scene
  19837. this.getScene().removeCamera(this);
  19838. while (this._rigCameras.length > 0) {
  19839. var camera = this._rigCameras.pop();
  19840. if (camera) {
  19841. camera.dispose();
  19842. }
  19843. }
  19844. // Postprocesses
  19845. if (this._rigPostProcess) {
  19846. this._rigPostProcess.dispose(this);
  19847. this._rigPostProcess = null;
  19848. this._postProcesses = [];
  19849. }
  19850. else if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  19851. this._rigPostProcess = null;
  19852. this._postProcesses = [];
  19853. }
  19854. else {
  19855. var i = this._postProcesses.length;
  19856. while (--i >= 0) {
  19857. this._postProcesses[i].dispose(this);
  19858. }
  19859. }
  19860. // Render targets
  19861. var i = this.customRenderTargets.length;
  19862. while (--i >= 0) {
  19863. this.customRenderTargets[i].dispose();
  19864. }
  19865. this.customRenderTargets = [];
  19866. // Active Meshes
  19867. this._activeMeshes.dispose();
  19868. _super.prototype.dispose.call(this);
  19869. };
  19870. Object.defineProperty(Camera.prototype, "leftCamera", {
  19871. // ---- Camera rigs section ----
  19872. get: function () {
  19873. if (this._rigCameras.length < 1) {
  19874. return null;
  19875. }
  19876. return this._rigCameras[0];
  19877. },
  19878. enumerable: true,
  19879. configurable: true
  19880. });
  19881. Object.defineProperty(Camera.prototype, "rightCamera", {
  19882. get: function () {
  19883. if (this._rigCameras.length < 2) {
  19884. return null;
  19885. }
  19886. return this._rigCameras[1];
  19887. },
  19888. enumerable: true,
  19889. configurable: true
  19890. });
  19891. Camera.prototype.getLeftTarget = function () {
  19892. if (this._rigCameras.length < 1) {
  19893. return null;
  19894. }
  19895. return this._rigCameras[0].getTarget();
  19896. };
  19897. Camera.prototype.getRightTarget = function () {
  19898. if (this._rigCameras.length < 2) {
  19899. return null;
  19900. }
  19901. return this._rigCameras[1].getTarget();
  19902. };
  19903. Camera.prototype.setCameraRigMode = function (mode, rigParams) {
  19904. if (this.cameraRigMode === mode) {
  19905. return;
  19906. }
  19907. while (this._rigCameras.length > 0) {
  19908. var camera = this._rigCameras.pop();
  19909. if (camera) {
  19910. camera.dispose();
  19911. }
  19912. }
  19913. this.cameraRigMode = mode;
  19914. this._cameraRigParams = {};
  19915. //we have to implement stereo camera calcultating left and right viewpoints from interaxialDistance and target,
  19916. //not from a given angle as it is now, but until that complete code rewriting provisional stereoHalfAngle value is introduced
  19917. this._cameraRigParams.interaxialDistance = rigParams.interaxialDistance || 0.0637;
  19918. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(this._cameraRigParams.interaxialDistance / 0.0637);
  19919. // create the rig cameras, unless none
  19920. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  19921. var leftCamera = this.createRigCamera(this.name + "_L", 0);
  19922. var rightCamera = this.createRigCamera(this.name + "_R", 1);
  19923. if (leftCamera && rightCamera) {
  19924. this._rigCameras.push(leftCamera);
  19925. this._rigCameras.push(rightCamera);
  19926. }
  19927. }
  19928. switch (this.cameraRigMode) {
  19929. case Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  19930. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  19931. this._rigCameras[1]._rigPostProcess = new BABYLON.AnaglyphPostProcess(this.name + "_anaglyph", 1.0, this._rigCameras);
  19932. break;
  19933. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  19934. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  19935. case Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  19936. var isStereoscopicHoriz = this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL || this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  19937. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  19938. this._rigCameras[1]._rigPostProcess = new BABYLON.StereoscopicInterlacePostProcess(this.name + "_stereoInterlace", this._rigCameras, isStereoscopicHoriz);
  19939. break;
  19940. case Camera.RIG_MODE_VR:
  19941. var metrics = rigParams.vrCameraMetrics || BABYLON.VRCameraMetrics.GetDefault();
  19942. this._rigCameras[0]._cameraRigParams.vrMetrics = metrics;
  19943. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  19944. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  19945. this._rigCameras[0]._cameraRigParams.vrHMatrix = metrics.leftHMatrix;
  19946. this._rigCameras[0]._cameraRigParams.vrPreViewMatrix = metrics.leftPreViewMatrix;
  19947. this._rigCameras[0].getProjectionMatrix = this._rigCameras[0]._getVRProjectionMatrix;
  19948. this._rigCameras[1]._cameraRigParams.vrMetrics = metrics;
  19949. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  19950. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  19951. this._rigCameras[1]._cameraRigParams.vrHMatrix = metrics.rightHMatrix;
  19952. this._rigCameras[1]._cameraRigParams.vrPreViewMatrix = metrics.rightPreViewMatrix;
  19953. this._rigCameras[1].getProjectionMatrix = this._rigCameras[1]._getVRProjectionMatrix;
  19954. if (metrics.compensateDistortion) {
  19955. this._rigCameras[0]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Left", this._rigCameras[0], false, metrics);
  19956. this._rigCameras[1]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Right", this._rigCameras[1], true, metrics);
  19957. }
  19958. break;
  19959. case Camera.RIG_MODE_WEBVR:
  19960. if (rigParams.vrDisplay) {
  19961. var leftEye = rigParams.vrDisplay.getEyeParameters('left');
  19962. var rightEye = rigParams.vrDisplay.getEyeParameters('right');
  19963. //Left eye
  19964. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  19965. this._rigCameras[0].setCameraRigParameter("left", true);
  19966. //leaving this for future reference
  19967. this._rigCameras[0].setCameraRigParameter("specs", rigParams.specs);
  19968. this._rigCameras[0].setCameraRigParameter("eyeParameters", leftEye);
  19969. this._rigCameras[0].setCameraRigParameter("frameData", rigParams.frameData);
  19970. this._rigCameras[0].setCameraRigParameter("parentCamera", rigParams.parentCamera);
  19971. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  19972. this._rigCameras[0].getProjectionMatrix = this._getWebVRProjectionMatrix;
  19973. this._rigCameras[0].parent = this;
  19974. this._rigCameras[0]._getViewMatrix = this._getWebVRViewMatrix;
  19975. //Right eye
  19976. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  19977. this._rigCameras[1].setCameraRigParameter('eyeParameters', rightEye);
  19978. this._rigCameras[1].setCameraRigParameter("specs", rigParams.specs);
  19979. this._rigCameras[1].setCameraRigParameter("frameData", rigParams.frameData);
  19980. this._rigCameras[1].setCameraRigParameter("parentCamera", rigParams.parentCamera);
  19981. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  19982. this._rigCameras[1].getProjectionMatrix = this._getWebVRProjectionMatrix;
  19983. this._rigCameras[1].parent = this;
  19984. this._rigCameras[1]._getViewMatrix = this._getWebVRViewMatrix;
  19985. if (Camera.UseAlternateWebVRRendering) {
  19986. this._rigCameras[1]._skipRendering = true;
  19987. this._rigCameras[0]._alternateCamera = this._rigCameras[1];
  19988. }
  19989. }
  19990. break;
  19991. }
  19992. this._cascadePostProcessesToRigCams();
  19993. this.update();
  19994. };
  19995. Camera.prototype._getVRProjectionMatrix = function () {
  19996. BABYLON.Matrix.PerspectiveFovLHToRef(this._cameraRigParams.vrMetrics.aspectRatioFov, this._cameraRigParams.vrMetrics.aspectRatio, this.minZ, this.maxZ, this._cameraRigParams.vrWorkMatrix);
  19997. this._cameraRigParams.vrWorkMatrix.multiplyToRef(this._cameraRigParams.vrHMatrix, this._projectionMatrix);
  19998. return this._projectionMatrix;
  19999. };
  20000. Camera.prototype._updateCameraRotationMatrix = function () {
  20001. //Here for WebVR
  20002. };
  20003. Camera.prototype._updateWebVRCameraRotationMatrix = function () {
  20004. //Here for WebVR
  20005. };
  20006. /**
  20007. * This function MUST be overwritten by the different WebVR cameras available.
  20008. * The context in which it is running is the RIG camera. So 'this' is the TargetCamera, left or right.
  20009. */
  20010. Camera.prototype._getWebVRProjectionMatrix = function () {
  20011. return BABYLON.Matrix.Identity();
  20012. };
  20013. /**
  20014. * This function MUST be overwritten by the different WebVR cameras available.
  20015. * The context in which it is running is the RIG camera. So 'this' is the TargetCamera, left or right.
  20016. */
  20017. Camera.prototype._getWebVRViewMatrix = function () {
  20018. return BABYLON.Matrix.Identity();
  20019. };
  20020. Camera.prototype.setCameraRigParameter = function (name, value) {
  20021. if (!this._cameraRigParams) {
  20022. this._cameraRigParams = {};
  20023. }
  20024. this._cameraRigParams[name] = value;
  20025. //provisionnally:
  20026. if (name === "interaxialDistance") {
  20027. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(value / 0.0637);
  20028. }
  20029. };
  20030. /**
  20031. * needs to be overridden by children so sub has required properties to be copied
  20032. */
  20033. Camera.prototype.createRigCamera = function (name, cameraIndex) {
  20034. return null;
  20035. };
  20036. /**
  20037. * May need to be overridden by children
  20038. */
  20039. Camera.prototype._updateRigCameras = function () {
  20040. for (var i = 0; i < this._rigCameras.length; i++) {
  20041. this._rigCameras[i].minZ = this.minZ;
  20042. this._rigCameras[i].maxZ = this.maxZ;
  20043. this._rigCameras[i].fov = this.fov;
  20044. }
  20045. // only update viewport when ANAGLYPH
  20046. if (this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH) {
  20047. this._rigCameras[0].viewport = this._rigCameras[1].viewport = this.viewport;
  20048. }
  20049. };
  20050. Camera.prototype._setupInputs = function () {
  20051. };
  20052. Camera.prototype.serialize = function () {
  20053. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  20054. // Type
  20055. serializationObject.type = this.getClassName();
  20056. // Parent
  20057. if (this.parent) {
  20058. serializationObject.parentId = this.parent.id;
  20059. }
  20060. if (this.inputs) {
  20061. this.inputs.serialize(serializationObject);
  20062. }
  20063. // Animations
  20064. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  20065. serializationObject.ranges = this.serializeAnimationRanges();
  20066. return serializationObject;
  20067. };
  20068. Camera.prototype.clone = function (name) {
  20069. return BABYLON.SerializationHelper.Clone(Camera.GetConstructorFromName(this.getClassName(), name, this.getScene(), this.interaxialDistance, this.isStereoscopicSideBySide), this);
  20070. };
  20071. Camera.prototype.getDirection = function (localAxis) {
  20072. var result = BABYLON.Vector3.Zero();
  20073. this.getDirectionToRef(localAxis, result);
  20074. return result;
  20075. };
  20076. Camera.prototype.getDirectionToRef = function (localAxis, result) {
  20077. BABYLON.Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result);
  20078. };
  20079. Camera.GetConstructorFromName = function (type, name, scene, interaxial_distance, isStereoscopicSideBySide) {
  20080. if (interaxial_distance === void 0) { interaxial_distance = 0; }
  20081. if (isStereoscopicSideBySide === void 0) { isStereoscopicSideBySide = true; }
  20082. switch (type) {
  20083. case "ArcRotateCamera":
  20084. return function () { return new BABYLON.ArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), scene); };
  20085. case "DeviceOrientationCamera":
  20086. return function () { return new BABYLON.DeviceOrientationCamera(name, BABYLON.Vector3.Zero(), scene); };
  20087. case "FollowCamera":
  20088. return function () { return new BABYLON.FollowCamera(name, BABYLON.Vector3.Zero(), scene); };
  20089. case "ArcFollowCamera":
  20090. return function () { return new BABYLON.ArcFollowCamera(name, 0, 0, 1.0, null, scene); };
  20091. case "GamepadCamera":
  20092. return function () { return new BABYLON.GamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  20093. case "TouchCamera":
  20094. return function () { return new BABYLON.TouchCamera(name, BABYLON.Vector3.Zero(), scene); };
  20095. case "VirtualJoysticksCamera":
  20096. return function () { return new BABYLON.VirtualJoysticksCamera(name, BABYLON.Vector3.Zero(), scene); };
  20097. case "WebVRFreeCamera":
  20098. return function () { return new BABYLON.WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  20099. case "WebVRGamepadCamera":
  20100. return function () { return new BABYLON.WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  20101. case "VRDeviceOrientationFreeCamera":
  20102. return function () { return new BABYLON.VRDeviceOrientationFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  20103. case "VRDeviceOrientationGamepadCamera":
  20104. return function () { return new BABYLON.VRDeviceOrientationGamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  20105. case "AnaglyphArcRotateCamera":
  20106. return function () { return new BABYLON.AnaglyphArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  20107. case "AnaglyphFreeCamera":
  20108. return function () { return new BABYLON.AnaglyphFreeCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  20109. case "AnaglyphGamepadCamera":
  20110. return function () { return new BABYLON.AnaglyphGamepadCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  20111. case "AnaglyphUniversalCamera":
  20112. return function () { return new BABYLON.AnaglyphUniversalCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  20113. case "StereoscopicArcRotateCamera":
  20114. return function () { return new BABYLON.StereoscopicArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  20115. case "StereoscopicFreeCamera":
  20116. return function () { return new BABYLON.StereoscopicFreeCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  20117. case "StereoscopicGamepadCamera":
  20118. return function () { return new BABYLON.StereoscopicGamepadCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  20119. case "StereoscopicUniversalCamera":
  20120. return function () { return new BABYLON.StereoscopicUniversalCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  20121. case "FreeCamera":// Forcing Universal here
  20122. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  20123. default:// Universal Camera is the default value
  20124. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  20125. }
  20126. };
  20127. Camera.prototype.computeWorldMatrix = function () {
  20128. return this.getWorldMatrix();
  20129. };
  20130. Camera.Parse = function (parsedCamera, scene) {
  20131. var type = parsedCamera.type;
  20132. var construct = Camera.GetConstructorFromName(type, parsedCamera.name, scene, parsedCamera.interaxial_distance, parsedCamera.isStereoscopicSideBySide);
  20133. var camera = BABYLON.SerializationHelper.Parse(construct, parsedCamera, scene);
  20134. // Parent
  20135. if (parsedCamera.parentId) {
  20136. camera._waitingParentId = parsedCamera.parentId;
  20137. }
  20138. //If camera has an input manager, let it parse inputs settings
  20139. if (camera.inputs) {
  20140. camera.inputs.parse(parsedCamera);
  20141. camera._setupInputs();
  20142. }
  20143. if (camera.setPosition) {
  20144. camera.position.copyFromFloats(0, 0, 0);
  20145. camera.setPosition(BABYLON.Vector3.FromArray(parsedCamera.position));
  20146. }
  20147. // Target
  20148. if (parsedCamera.target) {
  20149. if (camera.setTarget) {
  20150. camera.setTarget(BABYLON.Vector3.FromArray(parsedCamera.target));
  20151. }
  20152. }
  20153. // Apply 3d rig, when found
  20154. if (parsedCamera.cameraRigMode) {
  20155. var rigParams = (parsedCamera.interaxial_distance) ? { interaxialDistance: parsedCamera.interaxial_distance } : {};
  20156. camera.setCameraRigMode(parsedCamera.cameraRigMode, rigParams);
  20157. }
  20158. // Animations
  20159. if (parsedCamera.animations) {
  20160. for (var animationIndex = 0; animationIndex < parsedCamera.animations.length; animationIndex++) {
  20161. var parsedAnimation = parsedCamera.animations[animationIndex];
  20162. camera.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  20163. }
  20164. BABYLON.Node.ParseAnimationRanges(camera, parsedCamera, scene);
  20165. }
  20166. if (parsedCamera.autoAnimate) {
  20167. scene.beginAnimation(camera, parsedCamera.autoAnimateFrom, parsedCamera.autoAnimateTo, parsedCamera.autoAnimateLoop, parsedCamera.autoAnimateSpeed || 1.0);
  20168. }
  20169. return camera;
  20170. };
  20171. // Statics
  20172. Camera._PERSPECTIVE_CAMERA = 0;
  20173. Camera._ORTHOGRAPHIC_CAMERA = 1;
  20174. Camera._FOVMODE_VERTICAL_FIXED = 0;
  20175. Camera._FOVMODE_HORIZONTAL_FIXED = 1;
  20176. Camera._RIG_MODE_NONE = 0;
  20177. Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH = 10;
  20178. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL = 11;
  20179. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED = 12;
  20180. Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER = 13;
  20181. Camera._RIG_MODE_VR = 20;
  20182. Camera._RIG_MODE_WEBVR = 21;
  20183. Camera.ForceAttachControlToAlwaysPreventDefault = false;
  20184. Camera.UseAlternateWebVRRendering = false;
  20185. __decorate([
  20186. BABYLON.serializeAsVector3()
  20187. ], Camera.prototype, "position", void 0);
  20188. __decorate([
  20189. BABYLON.serializeAsVector3()
  20190. ], Camera.prototype, "upVector", void 0);
  20191. __decorate([
  20192. BABYLON.serialize()
  20193. ], Camera.prototype, "orthoLeft", void 0);
  20194. __decorate([
  20195. BABYLON.serialize()
  20196. ], Camera.prototype, "orthoRight", void 0);
  20197. __decorate([
  20198. BABYLON.serialize()
  20199. ], Camera.prototype, "orthoBottom", void 0);
  20200. __decorate([
  20201. BABYLON.serialize()
  20202. ], Camera.prototype, "orthoTop", void 0);
  20203. __decorate([
  20204. BABYLON.serialize()
  20205. ], Camera.prototype, "fov", void 0);
  20206. __decorate([
  20207. BABYLON.serialize()
  20208. ], Camera.prototype, "minZ", void 0);
  20209. __decorate([
  20210. BABYLON.serialize()
  20211. ], Camera.prototype, "maxZ", void 0);
  20212. __decorate([
  20213. BABYLON.serialize()
  20214. ], Camera.prototype, "inertia", void 0);
  20215. __decorate([
  20216. BABYLON.serialize()
  20217. ], Camera.prototype, "mode", void 0);
  20218. __decorate([
  20219. BABYLON.serialize()
  20220. ], Camera.prototype, "layerMask", void 0);
  20221. __decorate([
  20222. BABYLON.serialize()
  20223. ], Camera.prototype, "fovMode", void 0);
  20224. __decorate([
  20225. BABYLON.serialize()
  20226. ], Camera.prototype, "cameraRigMode", void 0);
  20227. __decorate([
  20228. BABYLON.serialize()
  20229. ], Camera.prototype, "interaxialDistance", void 0);
  20230. __decorate([
  20231. BABYLON.serialize()
  20232. ], Camera.prototype, "isStereoscopicSideBySide", void 0);
  20233. return Camera;
  20234. }(BABYLON.Node));
  20235. BABYLON.Camera = Camera;
  20236. })(BABYLON || (BABYLON = {}));
  20237. //# sourceMappingURL=babylon.camera.js.map
  20238. var BABYLON;
  20239. (function (BABYLON) {
  20240. var RenderingManager = /** @class */ (function () {
  20241. function RenderingManager(scene) {
  20242. this._renderingGroups = new Array();
  20243. this._autoClearDepthStencil = {};
  20244. this._customOpaqueSortCompareFn = {};
  20245. this._customAlphaTestSortCompareFn = {};
  20246. this._customTransparentSortCompareFn = {};
  20247. this._renderinGroupInfo = null;
  20248. this._scene = scene;
  20249. for (var i = RenderingManager.MIN_RENDERINGGROUPS; i < RenderingManager.MAX_RENDERINGGROUPS; i++) {
  20250. this._autoClearDepthStencil[i] = { autoClear: true, depth: true, stencil: true };
  20251. }
  20252. }
  20253. RenderingManager.prototype._clearDepthStencilBuffer = function (depth, stencil) {
  20254. if (depth === void 0) { depth = true; }
  20255. if (stencil === void 0) { stencil = true; }
  20256. if (this._depthStencilBufferAlreadyCleaned) {
  20257. return;
  20258. }
  20259. this._scene.getEngine().clear(null, false, depth, stencil);
  20260. this._depthStencilBufferAlreadyCleaned = true;
  20261. };
  20262. RenderingManager.prototype.render = function (customRenderFunction, activeMeshes, renderParticles, renderSprites) {
  20263. // Check if there's at least on observer on the onRenderingGroupObservable and initialize things to fire it
  20264. var observable = this._scene.onRenderingGroupObservable.hasObservers() ? this._scene.onRenderingGroupObservable : null;
  20265. var info = null;
  20266. if (observable) {
  20267. if (!this._renderinGroupInfo) {
  20268. this._renderinGroupInfo = new BABYLON.RenderingGroupInfo();
  20269. }
  20270. info = this._renderinGroupInfo;
  20271. info.scene = this._scene;
  20272. info.camera = this._scene.activeCamera;
  20273. }
  20274. // Dispatch sprites
  20275. if (renderSprites) {
  20276. for (var index = 0; index < this._scene.spriteManagers.length; index++) {
  20277. var manager = this._scene.spriteManagers[index];
  20278. this.dispatchSprites(manager);
  20279. }
  20280. }
  20281. // Render
  20282. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  20283. this._depthStencilBufferAlreadyCleaned = index === RenderingManager.MIN_RENDERINGGROUPS;
  20284. var renderingGroup = this._renderingGroups[index];
  20285. if (!renderingGroup && !observable)
  20286. continue;
  20287. var renderingGroupMask = 0;
  20288. // Fire PRECLEAR stage
  20289. if (observable && info) {
  20290. renderingGroupMask = Math.pow(2, index);
  20291. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PRECLEAR;
  20292. info.renderingGroupId = index;
  20293. observable.notifyObservers(info, renderingGroupMask);
  20294. }
  20295. // Clear depth/stencil if needed
  20296. if (RenderingManager.AUTOCLEAR) {
  20297. var autoClear = this._autoClearDepthStencil[index];
  20298. if (autoClear && autoClear.autoClear) {
  20299. this._clearDepthStencilBuffer(autoClear.depth, autoClear.stencil);
  20300. }
  20301. }
  20302. if (observable && info) {
  20303. // Fire PREOPAQUE stage
  20304. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PREOPAQUE;
  20305. observable.notifyObservers(info, renderingGroupMask);
  20306. // Fire PRETRANSPARENT stage
  20307. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PRETRANSPARENT;
  20308. observable.notifyObservers(info, renderingGroupMask);
  20309. }
  20310. if (renderingGroup)
  20311. renderingGroup.render(customRenderFunction, renderSprites, renderParticles, activeMeshes);
  20312. // Fire POSTTRANSPARENT stage
  20313. if (observable && info) {
  20314. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_POSTTRANSPARENT;
  20315. observable.notifyObservers(info, renderingGroupMask);
  20316. }
  20317. }
  20318. };
  20319. RenderingManager.prototype.reset = function () {
  20320. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  20321. var renderingGroup = this._renderingGroups[index];
  20322. if (renderingGroup) {
  20323. renderingGroup.prepare();
  20324. }
  20325. }
  20326. };
  20327. RenderingManager.prototype.dispose = function () {
  20328. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  20329. var renderingGroup = this._renderingGroups[index];
  20330. if (renderingGroup) {
  20331. renderingGroup.dispose();
  20332. }
  20333. }
  20334. this._renderingGroups.length = 0;
  20335. };
  20336. RenderingManager.prototype._prepareRenderingGroup = function (renderingGroupId) {
  20337. if (this._renderingGroups[renderingGroupId] === undefined) {
  20338. this._renderingGroups[renderingGroupId] = new BABYLON.RenderingGroup(renderingGroupId, this._scene, this._customOpaqueSortCompareFn[renderingGroupId], this._customAlphaTestSortCompareFn[renderingGroupId], this._customTransparentSortCompareFn[renderingGroupId]);
  20339. }
  20340. };
  20341. RenderingManager.prototype.dispatchSprites = function (spriteManager) {
  20342. var renderingGroupId = spriteManager.renderingGroupId || 0;
  20343. this._prepareRenderingGroup(renderingGroupId);
  20344. this._renderingGroups[renderingGroupId].dispatchSprites(spriteManager);
  20345. };
  20346. RenderingManager.prototype.dispatchParticles = function (particleSystem) {
  20347. var renderingGroupId = particleSystem.renderingGroupId || 0;
  20348. this._prepareRenderingGroup(renderingGroupId);
  20349. this._renderingGroups[renderingGroupId].dispatchParticles(particleSystem);
  20350. };
  20351. /**
  20352. * @param subMesh The submesh to dispatch
  20353. * @param [mesh] Optional reference to the submeshes's mesh. Provide if you have an exiting reference to improve performance.
  20354. * @param [material] Optional reference to the submeshes's material. Provide if you have an exiting reference to improve performance.
  20355. */
  20356. RenderingManager.prototype.dispatch = function (subMesh, mesh, material) {
  20357. if (mesh === undefined) {
  20358. mesh = subMesh.getMesh();
  20359. }
  20360. var renderingGroupId = mesh.renderingGroupId || 0;
  20361. this._prepareRenderingGroup(renderingGroupId);
  20362. this._renderingGroups[renderingGroupId].dispatch(subMesh, mesh, material);
  20363. };
  20364. /**
  20365. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  20366. * This allowed control for front to back rendering or reversly depending of the special needs.
  20367. *
  20368. * @param renderingGroupId The rendering group id corresponding to its index
  20369. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  20370. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  20371. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  20372. */
  20373. RenderingManager.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  20374. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  20375. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  20376. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  20377. this._customOpaqueSortCompareFn[renderingGroupId] = opaqueSortCompareFn;
  20378. this._customAlphaTestSortCompareFn[renderingGroupId] = alphaTestSortCompareFn;
  20379. this._customTransparentSortCompareFn[renderingGroupId] = transparentSortCompareFn;
  20380. if (this._renderingGroups[renderingGroupId]) {
  20381. var group = this._renderingGroups[renderingGroupId];
  20382. group.opaqueSortCompareFn = this._customOpaqueSortCompareFn[renderingGroupId];
  20383. group.alphaTestSortCompareFn = this._customAlphaTestSortCompareFn[renderingGroupId];
  20384. group.transparentSortCompareFn = this._customTransparentSortCompareFn[renderingGroupId];
  20385. }
  20386. };
  20387. /**
  20388. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  20389. *
  20390. * @param renderingGroupId The rendering group id corresponding to its index
  20391. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  20392. * @param depth Automatically clears depth between groups if true and autoClear is true.
  20393. * @param stencil Automatically clears stencil between groups if true and autoClear is true.
  20394. */
  20395. RenderingManager.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil, depth, stencil) {
  20396. if (depth === void 0) { depth = true; }
  20397. if (stencil === void 0) { stencil = true; }
  20398. this._autoClearDepthStencil[renderingGroupId] = {
  20399. autoClear: autoClearDepthStencil,
  20400. depth: depth,
  20401. stencil: stencil
  20402. };
  20403. };
  20404. /**
  20405. * The max id used for rendering groups (not included)
  20406. */
  20407. RenderingManager.MAX_RENDERINGGROUPS = 4;
  20408. /**
  20409. * The min id used for rendering groups (included)
  20410. */
  20411. RenderingManager.MIN_RENDERINGGROUPS = 0;
  20412. /**
  20413. * Used to globally prevent autoclearing scenes.
  20414. */
  20415. RenderingManager.AUTOCLEAR = true;
  20416. return RenderingManager;
  20417. }());
  20418. BABYLON.RenderingManager = RenderingManager;
  20419. })(BABYLON || (BABYLON = {}));
  20420. //# sourceMappingURL=babylon.renderingManager.js.map
  20421. var BABYLON;
  20422. (function (BABYLON) {
  20423. var RenderingGroup = /** @class */ (function () {
  20424. /**
  20425. * Creates a new rendering group.
  20426. * @param index The rendering group index
  20427. * @param opaqueSortCompareFn The opaque sort comparison function. If null no order is applied
  20428. * @param alphaTestSortCompareFn The alpha test sort comparison function. If null no order is applied
  20429. * @param transparentSortCompareFn The transparent sort comparison function. If null back to front + alpha index sort is applied
  20430. */
  20431. function RenderingGroup(index, scene, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  20432. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  20433. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  20434. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  20435. this.index = index;
  20436. this._opaqueSubMeshes = new BABYLON.SmartArray(256);
  20437. this._transparentSubMeshes = new BABYLON.SmartArray(256);
  20438. this._alphaTestSubMeshes = new BABYLON.SmartArray(256);
  20439. this._depthOnlySubMeshes = new BABYLON.SmartArray(256);
  20440. this._particleSystems = new BABYLON.SmartArray(256);
  20441. this._spriteManagers = new BABYLON.SmartArray(256);
  20442. this._edgesRenderers = new BABYLON.SmartArray(16);
  20443. this._scene = scene;
  20444. this.opaqueSortCompareFn = opaqueSortCompareFn;
  20445. this.alphaTestSortCompareFn = alphaTestSortCompareFn;
  20446. this.transparentSortCompareFn = transparentSortCompareFn;
  20447. }
  20448. Object.defineProperty(RenderingGroup.prototype, "opaqueSortCompareFn", {
  20449. /**
  20450. * Set the opaque sort comparison function.
  20451. * If null the sub meshes will be render in the order they were created
  20452. */
  20453. set: function (value) {
  20454. this._opaqueSortCompareFn = value;
  20455. if (value) {
  20456. this._renderOpaque = this.renderOpaqueSorted;
  20457. }
  20458. else {
  20459. this._renderOpaque = RenderingGroup.renderUnsorted;
  20460. }
  20461. },
  20462. enumerable: true,
  20463. configurable: true
  20464. });
  20465. Object.defineProperty(RenderingGroup.prototype, "alphaTestSortCompareFn", {
  20466. /**
  20467. * Set the alpha test sort comparison function.
  20468. * If null the sub meshes will be render in the order they were created
  20469. */
  20470. set: function (value) {
  20471. this._alphaTestSortCompareFn = value;
  20472. if (value) {
  20473. this._renderAlphaTest = this.renderAlphaTestSorted;
  20474. }
  20475. else {
  20476. this._renderAlphaTest = RenderingGroup.renderUnsorted;
  20477. }
  20478. },
  20479. enumerable: true,
  20480. configurable: true
  20481. });
  20482. Object.defineProperty(RenderingGroup.prototype, "transparentSortCompareFn", {
  20483. /**
  20484. * Set the transparent sort comparison function.
  20485. * If null the sub meshes will be render in the order they were created
  20486. */
  20487. set: function (value) {
  20488. if (value) {
  20489. this._transparentSortCompareFn = value;
  20490. }
  20491. else {
  20492. this._transparentSortCompareFn = RenderingGroup.defaultTransparentSortCompare;
  20493. }
  20494. this._renderTransparent = this.renderTransparentSorted;
  20495. },
  20496. enumerable: true,
  20497. configurable: true
  20498. });
  20499. /**
  20500. * Render all the sub meshes contained in the group.
  20501. * @param customRenderFunction Used to override the default render behaviour of the group.
  20502. * @returns true if rendered some submeshes.
  20503. */
  20504. RenderingGroup.prototype.render = function (customRenderFunction, renderSprites, renderParticles, activeMeshes) {
  20505. if (customRenderFunction) {
  20506. customRenderFunction(this._opaqueSubMeshes, this._alphaTestSubMeshes, this._transparentSubMeshes, this._depthOnlySubMeshes);
  20507. return;
  20508. }
  20509. var engine = this._scene.getEngine();
  20510. // Depth only
  20511. if (this._depthOnlySubMeshes.length !== 0) {
  20512. engine.setColorWrite(false);
  20513. this._renderAlphaTest(this._depthOnlySubMeshes);
  20514. engine.setColorWrite(true);
  20515. }
  20516. // Opaque
  20517. if (this._opaqueSubMeshes.length !== 0) {
  20518. this._renderOpaque(this._opaqueSubMeshes);
  20519. }
  20520. // Alpha test
  20521. if (this._alphaTestSubMeshes.length !== 0) {
  20522. this._renderAlphaTest(this._alphaTestSubMeshes);
  20523. }
  20524. var stencilState = engine.getStencilBuffer();
  20525. engine.setStencilBuffer(false);
  20526. // Sprites
  20527. if (renderSprites) {
  20528. this._renderSprites();
  20529. }
  20530. // Particles
  20531. if (renderParticles) {
  20532. this._renderParticles(activeMeshes);
  20533. }
  20534. if (this.onBeforeTransparentRendering) {
  20535. this.onBeforeTransparentRendering();
  20536. }
  20537. // Transparent
  20538. if (this._transparentSubMeshes.length !== 0) {
  20539. this._renderTransparent(this._transparentSubMeshes);
  20540. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  20541. }
  20542. // Set back stencil to false in case it changes before the edge renderer.
  20543. engine.setStencilBuffer(false);
  20544. // Edges
  20545. for (var edgesRendererIndex = 0; edgesRendererIndex < this._edgesRenderers.length; edgesRendererIndex++) {
  20546. this._edgesRenderers.data[edgesRendererIndex].render();
  20547. }
  20548. // Restore Stencil state.
  20549. engine.setStencilBuffer(stencilState);
  20550. };
  20551. /**
  20552. * Renders the opaque submeshes in the order from the opaqueSortCompareFn.
  20553. * @param subMeshes The submeshes to render
  20554. */
  20555. RenderingGroup.prototype.renderOpaqueSorted = function (subMeshes) {
  20556. return RenderingGroup.renderSorted(subMeshes, this._opaqueSortCompareFn, this._scene.activeCamera, false);
  20557. };
  20558. /**
  20559. * Renders the opaque submeshes in the order from the alphatestSortCompareFn.
  20560. * @param subMeshes The submeshes to render
  20561. */
  20562. RenderingGroup.prototype.renderAlphaTestSorted = function (subMeshes) {
  20563. return RenderingGroup.renderSorted(subMeshes, this._alphaTestSortCompareFn, this._scene.activeCamera, false);
  20564. };
  20565. /**
  20566. * Renders the opaque submeshes in the order from the transparentSortCompareFn.
  20567. * @param subMeshes The submeshes to render
  20568. */
  20569. RenderingGroup.prototype.renderTransparentSorted = function (subMeshes) {
  20570. return RenderingGroup.renderSorted(subMeshes, this._transparentSortCompareFn, this._scene.activeCamera, true);
  20571. };
  20572. /**
  20573. * Renders the submeshes in a specified order.
  20574. * @param subMeshes The submeshes to sort before render
  20575. * @param sortCompareFn The comparison function use to sort
  20576. * @param cameraPosition The camera position use to preprocess the submeshes to help sorting
  20577. * @param transparent Specifies to activate blending if true
  20578. */
  20579. RenderingGroup.renderSorted = function (subMeshes, sortCompareFn, camera, transparent) {
  20580. var subIndex = 0;
  20581. var subMesh;
  20582. var cameraPosition = camera ? camera.globalPosition : BABYLON.Vector3.Zero();
  20583. for (; subIndex < subMeshes.length; subIndex++) {
  20584. subMesh = subMeshes.data[subIndex];
  20585. subMesh._alphaIndex = subMesh.getMesh().alphaIndex;
  20586. subMesh._distanceToCamera = subMesh.getBoundingInfo().boundingSphere.centerWorld.subtract(cameraPosition).length();
  20587. }
  20588. var sortedArray = subMeshes.data.slice(0, subMeshes.length);
  20589. if (sortCompareFn) {
  20590. sortedArray.sort(sortCompareFn);
  20591. }
  20592. for (subIndex = 0; subIndex < sortedArray.length; subIndex++) {
  20593. subMesh = sortedArray[subIndex];
  20594. if (transparent) {
  20595. var material = subMesh.getMaterial();
  20596. if (material && material.needDepthPrePass) {
  20597. var engine = material.getScene().getEngine();
  20598. engine.setColorWrite(false);
  20599. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  20600. subMesh.render(false);
  20601. engine.setColorWrite(true);
  20602. }
  20603. }
  20604. subMesh.render(transparent);
  20605. }
  20606. };
  20607. /**
  20608. * Renders the submeshes in the order they were dispatched (no sort applied).
  20609. * @param subMeshes The submeshes to render
  20610. */
  20611. RenderingGroup.renderUnsorted = function (subMeshes) {
  20612. for (var subIndex = 0; subIndex < subMeshes.length; subIndex++) {
  20613. var submesh = subMeshes.data[subIndex];
  20614. submesh.render(false);
  20615. }
  20616. };
  20617. /**
  20618. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  20619. * are rendered back to front if in the same alpha index.
  20620. *
  20621. * @param a The first submesh
  20622. * @param b The second submesh
  20623. * @returns The result of the comparison
  20624. */
  20625. RenderingGroup.defaultTransparentSortCompare = function (a, b) {
  20626. // Alpha index first
  20627. if (a._alphaIndex > b._alphaIndex) {
  20628. return 1;
  20629. }
  20630. if (a._alphaIndex < b._alphaIndex) {
  20631. return -1;
  20632. }
  20633. // Then distance to camera
  20634. return RenderingGroup.backToFrontSortCompare(a, b);
  20635. };
  20636. /**
  20637. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  20638. * are rendered back to front.
  20639. *
  20640. * @param a The first submesh
  20641. * @param b The second submesh
  20642. * @returns The result of the comparison
  20643. */
  20644. RenderingGroup.backToFrontSortCompare = function (a, b) {
  20645. // Then distance to camera
  20646. if (a._distanceToCamera < b._distanceToCamera) {
  20647. return 1;
  20648. }
  20649. if (a._distanceToCamera > b._distanceToCamera) {
  20650. return -1;
  20651. }
  20652. return 0;
  20653. };
  20654. /**
  20655. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  20656. * are rendered front to back (prevent overdraw).
  20657. *
  20658. * @param a The first submesh
  20659. * @param b The second submesh
  20660. * @returns The result of the comparison
  20661. */
  20662. RenderingGroup.frontToBackSortCompare = function (a, b) {
  20663. // Then distance to camera
  20664. if (a._distanceToCamera < b._distanceToCamera) {
  20665. return -1;
  20666. }
  20667. if (a._distanceToCamera > b._distanceToCamera) {
  20668. return 1;
  20669. }
  20670. return 0;
  20671. };
  20672. /**
  20673. * Resets the different lists of submeshes to prepare a new frame.
  20674. */
  20675. RenderingGroup.prototype.prepare = function () {
  20676. this._opaqueSubMeshes.reset();
  20677. this._transparentSubMeshes.reset();
  20678. this._alphaTestSubMeshes.reset();
  20679. this._depthOnlySubMeshes.reset();
  20680. this._particleSystems.reset();
  20681. this._spriteManagers.reset();
  20682. this._edgesRenderers.reset();
  20683. };
  20684. RenderingGroup.prototype.dispose = function () {
  20685. this._opaqueSubMeshes.dispose();
  20686. this._transparentSubMeshes.dispose();
  20687. this._alphaTestSubMeshes.dispose();
  20688. this._depthOnlySubMeshes.dispose();
  20689. this._particleSystems.dispose();
  20690. this._spriteManagers.dispose();
  20691. this._edgesRenderers.dispose();
  20692. };
  20693. /**
  20694. * Inserts the submesh in its correct queue depending on its material.
  20695. * @param subMesh The submesh to dispatch
  20696. * @param [mesh] Optional reference to the submeshes's mesh. Provide if you have an exiting reference to improve performance.
  20697. * @param [material] Optional reference to the submeshes's material. Provide if you have an exiting reference to improve performance.
  20698. */
  20699. RenderingGroup.prototype.dispatch = function (subMesh, mesh, material) {
  20700. // Get mesh and materials if not provided
  20701. if (mesh === undefined) {
  20702. mesh = subMesh.getMesh();
  20703. }
  20704. if (material === undefined) {
  20705. material = subMesh.getMaterial();
  20706. }
  20707. if (material === null || material === undefined) {
  20708. return;
  20709. }
  20710. if (material.needAlphaBlendingForMesh(mesh)) {
  20711. this._transparentSubMeshes.push(subMesh);
  20712. }
  20713. else if (material.needAlphaTesting()) {
  20714. if (material.needDepthPrePass) {
  20715. this._depthOnlySubMeshes.push(subMesh);
  20716. }
  20717. this._alphaTestSubMeshes.push(subMesh);
  20718. }
  20719. else {
  20720. if (material.needDepthPrePass) {
  20721. this._depthOnlySubMeshes.push(subMesh);
  20722. }
  20723. this._opaqueSubMeshes.push(subMesh); // Opaque
  20724. }
  20725. if (mesh._edgesRenderer !== null && mesh._edgesRenderer !== undefined) {
  20726. this._edgesRenderers.push(mesh._edgesRenderer);
  20727. }
  20728. };
  20729. RenderingGroup.prototype.dispatchSprites = function (spriteManager) {
  20730. this._spriteManagers.push(spriteManager);
  20731. };
  20732. RenderingGroup.prototype.dispatchParticles = function (particleSystem) {
  20733. this._particleSystems.push(particleSystem);
  20734. };
  20735. RenderingGroup.prototype._renderParticles = function (activeMeshes) {
  20736. if (this._particleSystems.length === 0) {
  20737. return;
  20738. }
  20739. // Particles
  20740. var activeCamera = this._scene.activeCamera;
  20741. this._scene.onBeforeParticlesRenderingObservable.notifyObservers(this._scene);
  20742. for (var particleIndex = 0; particleIndex < this._particleSystems.length; particleIndex++) {
  20743. var particleSystem = this._particleSystems.data[particleIndex];
  20744. if ((activeCamera && activeCamera.layerMask & particleSystem.layerMask) === 0) {
  20745. continue;
  20746. }
  20747. var emitter = particleSystem.emitter;
  20748. if (!emitter.position || !activeMeshes || activeMeshes.indexOf(emitter) !== -1) {
  20749. this._scene._activeParticles.addCount(particleSystem.render(), false);
  20750. }
  20751. }
  20752. this._scene.onAfterParticlesRenderingObservable.notifyObservers(this._scene);
  20753. };
  20754. RenderingGroup.prototype._renderSprites = function () {
  20755. if (!this._scene.spritesEnabled || this._spriteManagers.length === 0) {
  20756. return;
  20757. }
  20758. // Sprites
  20759. var activeCamera = this._scene.activeCamera;
  20760. this._scene.onBeforeSpritesRenderingObservable.notifyObservers(this._scene);
  20761. for (var id = 0; id < this._spriteManagers.length; id++) {
  20762. var spriteManager = this._spriteManagers.data[id];
  20763. if (((activeCamera && activeCamera.layerMask & spriteManager.layerMask) !== 0)) {
  20764. spriteManager.render();
  20765. }
  20766. }
  20767. this._scene.onAfterSpritesRenderingObservable.notifyObservers(this._scene);
  20768. };
  20769. return RenderingGroup;
  20770. }());
  20771. BABYLON.RenderingGroup = RenderingGroup;
  20772. })(BABYLON || (BABYLON = {}));
  20773. //# sourceMappingURL=babylon.renderingGroup.js.map
  20774. var BABYLON;
  20775. (function (BABYLON) {
  20776. var ClickInfo = /** @class */ (function () {
  20777. function ClickInfo() {
  20778. this._singleClick = false;
  20779. this._doubleClick = false;
  20780. this._hasSwiped = false;
  20781. this._ignore = false;
  20782. }
  20783. Object.defineProperty(ClickInfo.prototype, "singleClick", {
  20784. get: function () {
  20785. return this._singleClick;
  20786. },
  20787. set: function (b) {
  20788. this._singleClick = b;
  20789. },
  20790. enumerable: true,
  20791. configurable: true
  20792. });
  20793. Object.defineProperty(ClickInfo.prototype, "doubleClick", {
  20794. get: function () {
  20795. return this._doubleClick;
  20796. },
  20797. set: function (b) {
  20798. this._doubleClick = b;
  20799. },
  20800. enumerable: true,
  20801. configurable: true
  20802. });
  20803. Object.defineProperty(ClickInfo.prototype, "hasSwiped", {
  20804. get: function () {
  20805. return this._hasSwiped;
  20806. },
  20807. set: function (b) {
  20808. this._hasSwiped = b;
  20809. },
  20810. enumerable: true,
  20811. configurable: true
  20812. });
  20813. Object.defineProperty(ClickInfo.prototype, "ignore", {
  20814. get: function () {
  20815. return this._ignore;
  20816. },
  20817. set: function (b) {
  20818. this._ignore = b;
  20819. },
  20820. enumerable: true,
  20821. configurable: true
  20822. });
  20823. return ClickInfo;
  20824. }());
  20825. /**
  20826. * This class is used by the onRenderingGroupObservable
  20827. */
  20828. var RenderingGroupInfo = /** @class */ (function () {
  20829. function RenderingGroupInfo() {
  20830. }
  20831. /**
  20832. * Stage corresponding to the very first hook in the renderingGroup phase: before the render buffer may be cleared
  20833. * This stage will be fired no matter what
  20834. */
  20835. RenderingGroupInfo.STAGE_PRECLEAR = 1;
  20836. /**
  20837. * Called before opaque object are rendered.
  20838. * This stage will be fired only if there's 3D Opaque content to render
  20839. */
  20840. RenderingGroupInfo.STAGE_PREOPAQUE = 2;
  20841. /**
  20842. * Called after the opaque objects are rendered and before the transparent ones
  20843. * This stage will be fired only if there's 3D transparent content to render
  20844. */
  20845. RenderingGroupInfo.STAGE_PRETRANSPARENT = 3;
  20846. /**
  20847. * Called after the transparent object are rendered, last hook of the renderingGroup phase
  20848. * This stage will be fired no matter what
  20849. */
  20850. RenderingGroupInfo.STAGE_POSTTRANSPARENT = 4;
  20851. return RenderingGroupInfo;
  20852. }());
  20853. BABYLON.RenderingGroupInfo = RenderingGroupInfo;
  20854. /**
  20855. * Represents a scene to be rendered by the engine.
  20856. * @see http://doc.babylonjs.com/page.php?p=21911
  20857. */
  20858. var Scene = /** @class */ (function () {
  20859. /**
  20860. * @constructor
  20861. * @param {BABYLON.Engine} engine - the engine to be used to render this scene.
  20862. */
  20863. function Scene(engine) {
  20864. // Members
  20865. this.autoClear = true;
  20866. this.autoClearDepthAndStencil = true;
  20867. this.clearColor = new BABYLON.Color4(0.2, 0.2, 0.3, 1.0);
  20868. this.ambientColor = new BABYLON.Color3(0, 0, 0);
  20869. this.forceWireframe = false;
  20870. this._forcePointsCloud = false;
  20871. this.forceShowBoundingBoxes = false;
  20872. this.animationsEnabled = true;
  20873. this.useConstantAnimationDeltaTime = false;
  20874. this.constantlyUpdateMeshUnderPointer = false;
  20875. this.hoverCursor = "pointer";
  20876. this.defaultCursor = "";
  20877. /**
  20878. * This is used to call preventDefault() on pointer down
  20879. * in order to block unwanted artifacts like system double clicks
  20880. */
  20881. this.preventDefaultOnPointerDown = true;
  20882. // Metadata
  20883. this.metadata = null;
  20884. /**
  20885. * An event triggered when the scene is disposed.
  20886. * @type {BABYLON.Observable}
  20887. */
  20888. this.onDisposeObservable = new BABYLON.Observable();
  20889. /**
  20890. * An event triggered before rendering the scene (right after animations and physics)
  20891. * @type {BABYLON.Observable}
  20892. */
  20893. this.onBeforeRenderObservable = new BABYLON.Observable();
  20894. /**
  20895. * An event triggered after rendering the scene
  20896. * @type {BABYLON.Observable}
  20897. */
  20898. this.onAfterRenderObservable = new BABYLON.Observable();
  20899. /**
  20900. * An event triggered before animating the scene
  20901. * @type {BABYLON.Observable}
  20902. */
  20903. this.onBeforeAnimationsObservable = new BABYLON.Observable();
  20904. /**
  20905. * An event triggered after animations processing
  20906. * @type {BABYLON.Observable}
  20907. */
  20908. this.onAfterAnimationsObservable = new BABYLON.Observable();
  20909. /**
  20910. * An event triggered before draw calls are ready to be sent
  20911. * @type {BABYLON.Observable}
  20912. */
  20913. this.onBeforeDrawPhaseObservable = new BABYLON.Observable();
  20914. /**
  20915. * An event triggered after draw calls have been sent
  20916. * @type {BABYLON.Observable}
  20917. */
  20918. this.onAfterDrawPhaseObservable = new BABYLON.Observable();
  20919. /**
  20920. * An event triggered when physic simulation is about to be run
  20921. * @type {BABYLON.Observable}
  20922. */
  20923. this.onBeforePhysicsObservable = new BABYLON.Observable();
  20924. /**
  20925. * An event triggered when physic simulation has been done
  20926. * @type {BABYLON.Observable}
  20927. */
  20928. this.onAfterPhysicsObservable = new BABYLON.Observable();
  20929. /**
  20930. * An event triggered when the scene is ready
  20931. * @type {BABYLON.Observable}
  20932. */
  20933. this.onReadyObservable = new BABYLON.Observable();
  20934. /**
  20935. * An event triggered before rendering a camera
  20936. * @type {BABYLON.Observable}
  20937. */
  20938. this.onBeforeCameraRenderObservable = new BABYLON.Observable();
  20939. /**
  20940. * An event triggered after rendering a camera
  20941. * @type {BABYLON.Observable}
  20942. */
  20943. this.onAfterCameraRenderObservable = new BABYLON.Observable();
  20944. /**
  20945. * An event triggered when active meshes evaluation is about to start
  20946. * @type {BABYLON.Observable}
  20947. */
  20948. this.onBeforeActiveMeshesEvaluationObservable = new BABYLON.Observable();
  20949. /**
  20950. * An event triggered when active meshes evaluation is done
  20951. * @type {BABYLON.Observable}
  20952. */
  20953. this.onAfterActiveMeshesEvaluationObservable = new BABYLON.Observable();
  20954. /**
  20955. * An event triggered when particles rendering is about to start
  20956. * Note: This event can be trigger more than once per frame (because particles can be rendered by render target textures as well)
  20957. * @type {BABYLON.Observable}
  20958. */
  20959. this.onBeforeParticlesRenderingObservable = new BABYLON.Observable();
  20960. /**
  20961. * An event triggered when particles rendering is done
  20962. * Note: This event can be trigger more than once per frame (because particles can be rendered by render target textures as well)
  20963. * @type {BABYLON.Observable}
  20964. */
  20965. this.onAfterParticlesRenderingObservable = new BABYLON.Observable();
  20966. /**
  20967. * An event triggered when sprites rendering is about to start
  20968. * Note: This event can be trigger more than once per frame (because sprites can be rendered by render target textures as well)
  20969. * @type {BABYLON.Observable}
  20970. */
  20971. this.onBeforeSpritesRenderingObservable = new BABYLON.Observable();
  20972. /**
  20973. * An event triggered when sprites rendering is done
  20974. * Note: This event can be trigger more than once per frame (because sprites can be rendered by render target textures as well)
  20975. * @type {BABYLON.Observable}
  20976. */
  20977. this.onAfterSpritesRenderingObservable = new BABYLON.Observable();
  20978. /**
  20979. * An event triggered when SceneLoader.Append or SceneLoader.Load or SceneLoader.ImportMesh were successfully executed
  20980. * @type {BABYLON.Observable}
  20981. */
  20982. this.onDataLoadedObservable = new BABYLON.Observable();
  20983. /**
  20984. * An event triggered when a camera is created
  20985. * @type {BABYLON.Observable}
  20986. */
  20987. this.onNewCameraAddedObservable = new BABYLON.Observable();
  20988. /**
  20989. * An event triggered when a camera is removed
  20990. * @type {BABYLON.Observable}
  20991. */
  20992. this.onCameraRemovedObservable = new BABYLON.Observable();
  20993. /**
  20994. * An event triggered when a light is created
  20995. * @type {BABYLON.Observable}
  20996. */
  20997. this.onNewLightAddedObservable = new BABYLON.Observable();
  20998. /**
  20999. * An event triggered when a light is removed
  21000. * @type {BABYLON.Observable}
  21001. */
  21002. this.onLightRemovedObservable = new BABYLON.Observable();
  21003. /**
  21004. * An event triggered when a geometry is created
  21005. * @type {BABYLON.Observable}
  21006. */
  21007. this.onNewGeometryAddedObservable = new BABYLON.Observable();
  21008. /**
  21009. * An event triggered when a geometry is removed
  21010. * @type {BABYLON.Observable}
  21011. */
  21012. this.onGeometryRemovedObservable = new BABYLON.Observable();
  21013. /**
  21014. * An event triggered when a transform node is created
  21015. * @type {BABYLON.Observable}
  21016. */
  21017. this.onNewTransformNodeAddedObservable = new BABYLON.Observable();
  21018. /**
  21019. * An event triggered when a transform node is removed
  21020. * @type {BABYLON.Observable}
  21021. */
  21022. this.onTransformNodeRemovedObservable = new BABYLON.Observable();
  21023. /**
  21024. * An event triggered when a mesh is created
  21025. * @type {BABYLON.Observable}
  21026. */
  21027. this.onNewMeshAddedObservable = new BABYLON.Observable();
  21028. /**
  21029. * An event triggered when a mesh is removed
  21030. * @type {BABYLON.Observable}
  21031. */
  21032. this.onMeshRemovedObservable = new BABYLON.Observable();
  21033. /**
  21034. * An event triggered when render targets are about to be rendered
  21035. * Can happen multiple times per frame.
  21036. * @type {BABYLON.Observable}
  21037. */
  21038. this.OnBeforeRenderTargetsRenderObservable = new BABYLON.Observable();
  21039. /**
  21040. * An event triggered when render targets were rendered.
  21041. * Can happen multiple times per frame.
  21042. * @type {BABYLON.Observable}
  21043. */
  21044. this.OnAfterRenderTargetsRenderObservable = new BABYLON.Observable();
  21045. /**
  21046. * An event triggered before calculating deterministic simulation step
  21047. * @type {BABYLON.Observable}
  21048. */
  21049. this.onBeforeStepObservable = new BABYLON.Observable();
  21050. /**
  21051. * An event triggered after calculating deterministic simulation step
  21052. * @type {BABYLON.Observable}
  21053. */
  21054. this.onAfterStepObservable = new BABYLON.Observable();
  21055. /**
  21056. * This Observable will be triggered for each stage of each renderingGroup of each rendered camera.
  21057. * The RenderinGroupInfo class contains all the information about the context in which the observable is called
  21058. * If you wish to register an Observer only for a given set of renderingGroup, use the mask with a combination of the renderingGroup index elevated to the power of two (1 for renderingGroup 0, 2 for renderingrOup1, 4 for 2 and 8 for 3)
  21059. */
  21060. this.onRenderingGroupObservable = new BABYLON.Observable();
  21061. // Animations
  21062. this.animations = [];
  21063. /**
  21064. * This observable event is triggered when any ponter event is triggered. It is registered during Scene.attachControl() and it is called BEFORE the 3D engine process anything (mesh/sprite picking for instance).
  21065. * You have the possibility to skip the process and the call to onPointerObservable by setting PointerInfoPre.skipOnPointerObservable to true
  21066. */
  21067. this.onPrePointerObservable = new BABYLON.Observable();
  21068. /**
  21069. * Observable event triggered each time an input event is received from the rendering canvas
  21070. */
  21071. this.onPointerObservable = new BABYLON.Observable();
  21072. this._meshPickProceed = false;
  21073. this._currentPickResult = null;
  21074. this._previousPickResult = null;
  21075. this._totalPointersPressed = 0;
  21076. this._doubleClickOccured = false;
  21077. /** Define this parameter if you are using multiple cameras and you want to specify which one should be used for pointer position */
  21078. this.cameraToUseForPointers = null;
  21079. this._startingPointerPosition = new BABYLON.Vector2(0, 0);
  21080. this._previousStartingPointerPosition = new BABYLON.Vector2(0, 0);
  21081. this._startingPointerTime = 0;
  21082. this._previousStartingPointerTime = 0;
  21083. // Deterministic lockstep
  21084. this._timeAccumulator = 0;
  21085. this._currentStepId = 0;
  21086. this._currentInternalStep = 0;
  21087. // Keyboard
  21088. /**
  21089. * This observable event is triggered when any keyboard event si raised and registered during Scene.attachControl()
  21090. * You have the possibility to skip the process and the call to onKeyboardObservable by setting KeyboardInfoPre.skipOnPointerObservable to true
  21091. */
  21092. this.onPreKeyboardObservable = new BABYLON.Observable();
  21093. /**
  21094. * Observable event triggered each time an keyboard event is received from the hosting window
  21095. */
  21096. this.onKeyboardObservable = new BABYLON.Observable();
  21097. // Coordinate system
  21098. /**
  21099. * use right-handed coordinate system on this scene.
  21100. * @type {boolean}
  21101. */
  21102. this._useRightHandedSystem = false;
  21103. // Fog
  21104. this._fogEnabled = true;
  21105. this._fogMode = Scene.FOGMODE_NONE;
  21106. this.fogColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  21107. this.fogDensity = 0.1;
  21108. this.fogStart = 0;
  21109. this.fogEnd = 1000.0;
  21110. // Lights
  21111. /**
  21112. * is shadow enabled on this scene.
  21113. * @type {boolean}
  21114. */
  21115. this._shadowsEnabled = true;
  21116. /**
  21117. * is light enabled on this scene.
  21118. * @type {boolean}
  21119. */
  21120. this._lightsEnabled = true;
  21121. /**
  21122. * All of the lights added to this scene.
  21123. * @see BABYLON.Light
  21124. * @type {BABYLON.Light[]}
  21125. */
  21126. this.lights = new Array();
  21127. // Cameras
  21128. /** All of the cameras added to this scene. */
  21129. this.cameras = new Array();
  21130. /** All of the active cameras added to this scene. */
  21131. this.activeCameras = new Array();
  21132. // Meshes
  21133. /**
  21134. * All of the tranform nodes added to this scene.
  21135. * @see BABYLON.TransformNode
  21136. * @type {BABYLON.TransformNode[]}
  21137. */
  21138. this.transformNodes = new Array();
  21139. /**
  21140. * All of the (abstract) meshes added to this scene.
  21141. * @see BABYLON.AbstractMesh
  21142. * @type {BABYLON.AbstractMesh[]}
  21143. */
  21144. this.meshes = new Array();
  21145. /**
  21146. * All of the animation groups added to this scene.
  21147. * @see BABYLON.AnimationGroup
  21148. * @type {BABYLON.AnimationGroup[]}
  21149. */
  21150. this.animationGroups = new Array();
  21151. // Geometries
  21152. this._geometries = new Array();
  21153. this.materials = new Array();
  21154. this.multiMaterials = new Array();
  21155. // Textures
  21156. this._texturesEnabled = true;
  21157. this.textures = new Array();
  21158. // Particles
  21159. this.particlesEnabled = true;
  21160. this.particleSystems = new Array();
  21161. // Sprites
  21162. this.spritesEnabled = true;
  21163. this.spriteManagers = new Array();
  21164. /**
  21165. * The list of layers (background and foreground) of the scene.
  21166. */
  21167. this.layers = new Array();
  21168. /**
  21169. * The list of effect layers (highlights/glow) contained in the scene.
  21170. */
  21171. this.effectLayers = new Array();
  21172. // Skeletons
  21173. this._skeletonsEnabled = true;
  21174. this.skeletons = new Array();
  21175. // Morph targets
  21176. this.morphTargetManagers = new Array();
  21177. // Lens flares
  21178. this.lensFlaresEnabled = true;
  21179. this.lensFlareSystems = new Array();
  21180. // Collisions
  21181. this.collisionsEnabled = true;
  21182. /** Defines the gravity applied to this scene */
  21183. this.gravity = new BABYLON.Vector3(0, -9.807, 0);
  21184. // Postprocesses
  21185. this.postProcesses = new Array();
  21186. this.postProcessesEnabled = true;
  21187. // Customs render targets
  21188. this.renderTargetsEnabled = true;
  21189. this.dumpNextRenderTargets = false;
  21190. this.customRenderTargets = new Array();
  21191. // Imported meshes
  21192. this.importedMeshesFiles = new Array();
  21193. // Probes
  21194. this.probesEnabled = true;
  21195. this.reflectionProbes = new Array();
  21196. this._actionManagers = new Array();
  21197. this._meshesForIntersections = new BABYLON.SmartArrayNoDuplicate(256);
  21198. // Procedural textures
  21199. this.proceduralTexturesEnabled = true;
  21200. this._proceduralTextures = new Array();
  21201. this.soundTracks = new Array();
  21202. this._audioEnabled = true;
  21203. this._headphone = false;
  21204. // Performance counters
  21205. this._totalVertices = new BABYLON.PerfCounter();
  21206. this._activeIndices = new BABYLON.PerfCounter();
  21207. this._activeParticles = new BABYLON.PerfCounter();
  21208. this._activeBones = new BABYLON.PerfCounter();
  21209. this._animationTime = 0;
  21210. this.animationTimeScale = 1;
  21211. this._renderId = 0;
  21212. this._executeWhenReadyTimeoutId = -1;
  21213. this._intermediateRendering = false;
  21214. this._viewUpdateFlag = -1;
  21215. this._projectionUpdateFlag = -1;
  21216. this._alternateViewUpdateFlag = -1;
  21217. this._alternateProjectionUpdateFlag = -1;
  21218. this._toBeDisposed = new BABYLON.SmartArray(256);
  21219. this._activeRequests = new Array();
  21220. this._pendingData = new Array();
  21221. this._isDisposed = false;
  21222. this.dispatchAllSubMeshesOfActiveMeshes = false;
  21223. this._activeMeshes = new BABYLON.SmartArray(256);
  21224. this._processedMaterials = new BABYLON.SmartArray(256);
  21225. this._renderTargets = new BABYLON.SmartArrayNoDuplicate(256);
  21226. this._activeParticleSystems = new BABYLON.SmartArray(256);
  21227. this._activeSkeletons = new BABYLON.SmartArrayNoDuplicate(32);
  21228. this._softwareSkinnedMeshes = new BABYLON.SmartArrayNoDuplicate(32);
  21229. this._activeAnimatables = new Array();
  21230. this._transformMatrix = BABYLON.Matrix.Zero();
  21231. this._useAlternateCameraConfiguration = false;
  21232. this._alternateRendering = false;
  21233. this.requireLightSorting = false;
  21234. this._activeMeshesFrozen = false;
  21235. this._tempPickingRay = BABYLON.Ray ? BABYLON.Ray.Zero() : null;
  21236. this._engine = engine || BABYLON.Engine.LastCreatedEngine;
  21237. this._engine.scenes.push(this);
  21238. this._uid = null;
  21239. this._renderingManager = new BABYLON.RenderingManager(this);
  21240. this.postProcessManager = new BABYLON.PostProcessManager(this);
  21241. if (BABYLON.OutlineRenderer) {
  21242. this._outlineRenderer = new BABYLON.OutlineRenderer(this);
  21243. }
  21244. if (BABYLON.Tools.IsWindowObjectExist()) {
  21245. this.attachControl();
  21246. }
  21247. //simplification queue
  21248. if (BABYLON.SimplificationQueue) {
  21249. this.simplificationQueue = new BABYLON.SimplificationQueue();
  21250. }
  21251. //collision coordinator initialization. For now legacy per default.
  21252. this.workerCollisions = false; //(!!Worker && (!!BABYLON.CollisionWorker || BABYLON.WorkerIncluded));
  21253. // Uniform Buffer
  21254. this._createUbo();
  21255. // Default Image processing definition.
  21256. this._imageProcessingConfiguration = new BABYLON.ImageProcessingConfiguration();
  21257. }
  21258. Object.defineProperty(Scene, "FOGMODE_NONE", {
  21259. /** The fog is deactivated */
  21260. get: function () {
  21261. return Scene._FOGMODE_NONE;
  21262. },
  21263. enumerable: true,
  21264. configurable: true
  21265. });
  21266. Object.defineProperty(Scene, "FOGMODE_EXP", {
  21267. /** The fog density is following an exponential function */
  21268. get: function () {
  21269. return Scene._FOGMODE_EXP;
  21270. },
  21271. enumerable: true,
  21272. configurable: true
  21273. });
  21274. Object.defineProperty(Scene, "FOGMODE_EXP2", {
  21275. /** The fog density is following an exponential function faster than FOGMODE_EXP */
  21276. get: function () {
  21277. return Scene._FOGMODE_EXP2;
  21278. },
  21279. enumerable: true,
  21280. configurable: true
  21281. });
  21282. Object.defineProperty(Scene, "FOGMODE_LINEAR", {
  21283. /** The fog density is following a linear function. */
  21284. get: function () {
  21285. return Scene._FOGMODE_LINEAR;
  21286. },
  21287. enumerable: true,
  21288. configurable: true
  21289. });
  21290. Object.defineProperty(Scene.prototype, "environmentTexture", {
  21291. /**
  21292. * Texture used in all pbr material as the reflection texture.
  21293. * As in the majority of the scene they are the same (exception for multi room and so on),
  21294. * this is easier to reference from here than from all the materials.
  21295. */
  21296. get: function () {
  21297. return this._environmentTexture;
  21298. },
  21299. /**
  21300. * Texture used in all pbr material as the reflection texture.
  21301. * As in the majority of the scene they are the same (exception for multi room and so on),
  21302. * this is easier to set here than in all the materials.
  21303. */
  21304. set: function (value) {
  21305. if (this._environmentTexture === value) {
  21306. return;
  21307. }
  21308. this._environmentTexture = value;
  21309. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  21310. },
  21311. enumerable: true,
  21312. configurable: true
  21313. });
  21314. Object.defineProperty(Scene.prototype, "imageProcessingConfiguration", {
  21315. /**
  21316. * Default image processing configuration used either in the rendering
  21317. * Forward main pass or through the imageProcessingPostProcess if present.
  21318. * As in the majority of the scene they are the same (exception for multi camera),
  21319. * this is easier to reference from here than from all the materials and post process.
  21320. *
  21321. * No setter as we it is a shared configuration, you can set the values instead.
  21322. */
  21323. get: function () {
  21324. return this._imageProcessingConfiguration;
  21325. },
  21326. enumerable: true,
  21327. configurable: true
  21328. });
  21329. Object.defineProperty(Scene.prototype, "forcePointsCloud", {
  21330. get: function () {
  21331. return this._forcePointsCloud;
  21332. },
  21333. set: function (value) {
  21334. if (this._forcePointsCloud === value) {
  21335. return;
  21336. }
  21337. this._forcePointsCloud = value;
  21338. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  21339. },
  21340. enumerable: true,
  21341. configurable: true
  21342. });
  21343. Object.defineProperty(Scene.prototype, "onDispose", {
  21344. /** A function to be executed when this scene is disposed. */
  21345. set: function (callback) {
  21346. if (this._onDisposeObserver) {
  21347. this.onDisposeObservable.remove(this._onDisposeObserver);
  21348. }
  21349. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  21350. },
  21351. enumerable: true,
  21352. configurable: true
  21353. });
  21354. Object.defineProperty(Scene.prototype, "beforeRender", {
  21355. /** A function to be executed before rendering this scene */
  21356. set: function (callback) {
  21357. if (this._onBeforeRenderObserver) {
  21358. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  21359. }
  21360. if (callback) {
  21361. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  21362. }
  21363. },
  21364. enumerable: true,
  21365. configurable: true
  21366. });
  21367. Object.defineProperty(Scene.prototype, "afterRender", {
  21368. /** A function to be executed after rendering this scene */
  21369. set: function (callback) {
  21370. if (this._onAfterRenderObserver) {
  21371. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  21372. }
  21373. if (callback) {
  21374. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  21375. }
  21376. },
  21377. enumerable: true,
  21378. configurable: true
  21379. });
  21380. Object.defineProperty(Scene.prototype, "beforeCameraRender", {
  21381. set: function (callback) {
  21382. if (this._onBeforeCameraRenderObserver) {
  21383. this.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver);
  21384. }
  21385. this._onBeforeCameraRenderObserver = this.onBeforeCameraRenderObservable.add(callback);
  21386. },
  21387. enumerable: true,
  21388. configurable: true
  21389. });
  21390. Object.defineProperty(Scene.prototype, "afterCameraRender", {
  21391. set: function (callback) {
  21392. if (this._onAfterCameraRenderObserver) {
  21393. this.onAfterCameraRenderObservable.remove(this._onAfterCameraRenderObserver);
  21394. }
  21395. this._onAfterCameraRenderObserver = this.onAfterCameraRenderObservable.add(callback);
  21396. },
  21397. enumerable: true,
  21398. configurable: true
  21399. });
  21400. Object.defineProperty(Scene.prototype, "gamepadManager", {
  21401. get: function () {
  21402. if (!this._gamepadManager) {
  21403. this._gamepadManager = new BABYLON.GamepadManager(this);
  21404. }
  21405. return this._gamepadManager;
  21406. },
  21407. enumerable: true,
  21408. configurable: true
  21409. });
  21410. Object.defineProperty(Scene.prototype, "unTranslatedPointer", {
  21411. get: function () {
  21412. return new BABYLON.Vector2(this._unTranslatedPointerX, this._unTranslatedPointerY);
  21413. },
  21414. enumerable: true,
  21415. configurable: true
  21416. });
  21417. Object.defineProperty(Scene.prototype, "useRightHandedSystem", {
  21418. get: function () {
  21419. return this._useRightHandedSystem;
  21420. },
  21421. set: function (value) {
  21422. if (this._useRightHandedSystem === value) {
  21423. return;
  21424. }
  21425. this._useRightHandedSystem = value;
  21426. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  21427. },
  21428. enumerable: true,
  21429. configurable: true
  21430. });
  21431. Scene.prototype.setStepId = function (newStepId) {
  21432. this._currentStepId = newStepId;
  21433. };
  21434. ;
  21435. Scene.prototype.getStepId = function () {
  21436. return this._currentStepId;
  21437. };
  21438. ;
  21439. Scene.prototype.getInternalStep = function () {
  21440. return this._currentInternalStep;
  21441. };
  21442. ;
  21443. Object.defineProperty(Scene.prototype, "fogEnabled", {
  21444. get: function () {
  21445. return this._fogEnabled;
  21446. },
  21447. /**
  21448. * is fog enabled on this scene.
  21449. */
  21450. set: function (value) {
  21451. if (this._fogEnabled === value) {
  21452. return;
  21453. }
  21454. this._fogEnabled = value;
  21455. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  21456. },
  21457. enumerable: true,
  21458. configurable: true
  21459. });
  21460. Object.defineProperty(Scene.prototype, "fogMode", {
  21461. get: function () {
  21462. return this._fogMode;
  21463. },
  21464. set: function (value) {
  21465. if (this._fogMode === value) {
  21466. return;
  21467. }
  21468. this._fogMode = value;
  21469. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  21470. },
  21471. enumerable: true,
  21472. configurable: true
  21473. });
  21474. Object.defineProperty(Scene.prototype, "shadowsEnabled", {
  21475. get: function () {
  21476. return this._shadowsEnabled;
  21477. },
  21478. set: function (value) {
  21479. if (this._shadowsEnabled === value) {
  21480. return;
  21481. }
  21482. this._shadowsEnabled = value;
  21483. this.markAllMaterialsAsDirty(BABYLON.Material.LightDirtyFlag);
  21484. },
  21485. enumerable: true,
  21486. configurable: true
  21487. });
  21488. Object.defineProperty(Scene.prototype, "lightsEnabled", {
  21489. get: function () {
  21490. return this._lightsEnabled;
  21491. },
  21492. set: function (value) {
  21493. if (this._lightsEnabled === value) {
  21494. return;
  21495. }
  21496. this._lightsEnabled = value;
  21497. this.markAllMaterialsAsDirty(BABYLON.Material.LightDirtyFlag);
  21498. },
  21499. enumerable: true,
  21500. configurable: true
  21501. });
  21502. Object.defineProperty(Scene.prototype, "defaultMaterial", {
  21503. /** The default material used on meshes when no material is affected */
  21504. get: function () {
  21505. if (!this._defaultMaterial) {
  21506. this._defaultMaterial = new BABYLON.StandardMaterial("default material", this);
  21507. }
  21508. return this._defaultMaterial;
  21509. },
  21510. /** The default material used on meshes when no material is affected */
  21511. set: function (value) {
  21512. this._defaultMaterial = value;
  21513. },
  21514. enumerable: true,
  21515. configurable: true
  21516. });
  21517. Object.defineProperty(Scene.prototype, "texturesEnabled", {
  21518. get: function () {
  21519. return this._texturesEnabled;
  21520. },
  21521. set: function (value) {
  21522. if (this._texturesEnabled === value) {
  21523. return;
  21524. }
  21525. this._texturesEnabled = value;
  21526. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  21527. },
  21528. enumerable: true,
  21529. configurable: true
  21530. });
  21531. Object.defineProperty(Scene.prototype, "skeletonsEnabled", {
  21532. get: function () {
  21533. return this._skeletonsEnabled;
  21534. },
  21535. set: function (value) {
  21536. if (this._skeletonsEnabled === value) {
  21537. return;
  21538. }
  21539. this._skeletonsEnabled = value;
  21540. this.markAllMaterialsAsDirty(BABYLON.Material.AttributesDirtyFlag);
  21541. },
  21542. enumerable: true,
  21543. configurable: true
  21544. });
  21545. Object.defineProperty(Scene.prototype, "postProcessRenderPipelineManager", {
  21546. get: function () {
  21547. if (!this._postProcessRenderPipelineManager) {
  21548. this._postProcessRenderPipelineManager = new BABYLON.PostProcessRenderPipelineManager();
  21549. }
  21550. return this._postProcessRenderPipelineManager;
  21551. },
  21552. enumerable: true,
  21553. configurable: true
  21554. });
  21555. Object.defineProperty(Scene.prototype, "mainSoundTrack", {
  21556. get: function () {
  21557. if (!this._mainSoundTrack) {
  21558. this._mainSoundTrack = new BABYLON.SoundTrack(this, { mainTrack: true });
  21559. }
  21560. return this._mainSoundTrack;
  21561. },
  21562. enumerable: true,
  21563. configurable: true
  21564. });
  21565. Object.defineProperty(Scene.prototype, "_isAlternateRenderingEnabled", {
  21566. get: function () {
  21567. return this._alternateRendering;
  21568. },
  21569. enumerable: true,
  21570. configurable: true
  21571. });
  21572. Object.defineProperty(Scene.prototype, "frustumPlanes", {
  21573. get: function () {
  21574. return this._frustumPlanes;
  21575. },
  21576. enumerable: true,
  21577. configurable: true
  21578. });
  21579. Object.defineProperty(Scene.prototype, "geometryBufferRenderer", {
  21580. /**
  21581. * Gets the current geometry buffer associated to the scene.
  21582. */
  21583. get: function () {
  21584. return this._geometryBufferRenderer;
  21585. },
  21586. /**
  21587. * Sets the current geometry buffer for the scene.
  21588. */
  21589. set: function (geometryBufferRenderer) {
  21590. if (geometryBufferRenderer && geometryBufferRenderer.isSupported) {
  21591. this._geometryBufferRenderer = geometryBufferRenderer;
  21592. }
  21593. },
  21594. enumerable: true,
  21595. configurable: true
  21596. });
  21597. Object.defineProperty(Scene.prototype, "debugLayer", {
  21598. // Properties
  21599. get: function () {
  21600. if (!this._debugLayer) {
  21601. this._debugLayer = new BABYLON.DebugLayer(this);
  21602. }
  21603. return this._debugLayer;
  21604. },
  21605. enumerable: true,
  21606. configurable: true
  21607. });
  21608. Object.defineProperty(Scene.prototype, "workerCollisions", {
  21609. get: function () {
  21610. return this._workerCollisions;
  21611. },
  21612. set: function (enabled) {
  21613. if (!BABYLON.CollisionCoordinatorLegacy) {
  21614. return;
  21615. }
  21616. enabled = (enabled && !!Worker);
  21617. this._workerCollisions = enabled;
  21618. if (this.collisionCoordinator) {
  21619. this.collisionCoordinator.destroy();
  21620. }
  21621. this.collisionCoordinator = enabled ? new BABYLON.CollisionCoordinatorWorker() : new BABYLON.CollisionCoordinatorLegacy();
  21622. this.collisionCoordinator.init(this);
  21623. },
  21624. enumerable: true,
  21625. configurable: true
  21626. });
  21627. Object.defineProperty(Scene.prototype, "selectionOctree", {
  21628. get: function () {
  21629. return this._selectionOctree;
  21630. },
  21631. enumerable: true,
  21632. configurable: true
  21633. });
  21634. Object.defineProperty(Scene.prototype, "meshUnderPointer", {
  21635. /**
  21636. * The mesh that is currently under the pointer.
  21637. * @return {BABYLON.AbstractMesh} mesh under the pointer/mouse cursor or null if none.
  21638. */
  21639. get: function () {
  21640. return this._pointerOverMesh;
  21641. },
  21642. enumerable: true,
  21643. configurable: true
  21644. });
  21645. Object.defineProperty(Scene.prototype, "pointerX", {
  21646. /**
  21647. * Current on-screen X position of the pointer
  21648. * @return {number} X position of the pointer
  21649. */
  21650. get: function () {
  21651. return this._pointerX;
  21652. },
  21653. enumerable: true,
  21654. configurable: true
  21655. });
  21656. Object.defineProperty(Scene.prototype, "pointerY", {
  21657. /**
  21658. * Current on-screen Y position of the pointer
  21659. * @return {number} Y position of the pointer
  21660. */
  21661. get: function () {
  21662. return this._pointerY;
  21663. },
  21664. enumerable: true,
  21665. configurable: true
  21666. });
  21667. Scene.prototype.getCachedMaterial = function () {
  21668. return this._cachedMaterial;
  21669. };
  21670. Scene.prototype.getCachedEffect = function () {
  21671. return this._cachedEffect;
  21672. };
  21673. Scene.prototype.getCachedVisibility = function () {
  21674. return this._cachedVisibility;
  21675. };
  21676. Scene.prototype.isCachedMaterialInvalid = function (material, effect, visibility) {
  21677. if (visibility === void 0) { visibility = 1; }
  21678. return this._cachedEffect !== effect || this._cachedMaterial !== material || this._cachedVisibility !== visibility;
  21679. };
  21680. Scene.prototype.getBoundingBoxRenderer = function () {
  21681. if (!this._boundingBoxRenderer) {
  21682. this._boundingBoxRenderer = new BABYLON.BoundingBoxRenderer(this);
  21683. }
  21684. return this._boundingBoxRenderer;
  21685. };
  21686. Scene.prototype.getOutlineRenderer = function () {
  21687. return this._outlineRenderer;
  21688. };
  21689. Scene.prototype.getEngine = function () {
  21690. return this._engine;
  21691. };
  21692. Scene.prototype.getTotalVertices = function () {
  21693. return this._totalVertices.current;
  21694. };
  21695. Object.defineProperty(Scene.prototype, "totalVerticesPerfCounter", {
  21696. get: function () {
  21697. return this._totalVertices;
  21698. },
  21699. enumerable: true,
  21700. configurable: true
  21701. });
  21702. Scene.prototype.getActiveIndices = function () {
  21703. return this._activeIndices.current;
  21704. };
  21705. Object.defineProperty(Scene.prototype, "totalActiveIndicesPerfCounter", {
  21706. get: function () {
  21707. return this._activeIndices;
  21708. },
  21709. enumerable: true,
  21710. configurable: true
  21711. });
  21712. Scene.prototype.getActiveParticles = function () {
  21713. return this._activeParticles.current;
  21714. };
  21715. Object.defineProperty(Scene.prototype, "activeParticlesPerfCounter", {
  21716. get: function () {
  21717. return this._activeParticles;
  21718. },
  21719. enumerable: true,
  21720. configurable: true
  21721. });
  21722. Scene.prototype.getActiveBones = function () {
  21723. return this._activeBones.current;
  21724. };
  21725. Object.defineProperty(Scene.prototype, "activeBonesPerfCounter", {
  21726. get: function () {
  21727. return this._activeBones;
  21728. },
  21729. enumerable: true,
  21730. configurable: true
  21731. });
  21732. // Stats
  21733. Scene.prototype.getInterFramePerfCounter = function () {
  21734. BABYLON.Tools.Warn("getInterFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  21735. return 0;
  21736. };
  21737. Object.defineProperty(Scene.prototype, "interFramePerfCounter", {
  21738. get: function () {
  21739. BABYLON.Tools.Warn("interFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  21740. return null;
  21741. },
  21742. enumerable: true,
  21743. configurable: true
  21744. });
  21745. Scene.prototype.getLastFrameDuration = function () {
  21746. BABYLON.Tools.Warn("getLastFrameDuration is deprecated. Please use SceneInstrumentation class");
  21747. return 0;
  21748. };
  21749. Object.defineProperty(Scene.prototype, "lastFramePerfCounter", {
  21750. get: function () {
  21751. BABYLON.Tools.Warn("lastFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  21752. return null;
  21753. },
  21754. enumerable: true,
  21755. configurable: true
  21756. });
  21757. Scene.prototype.getEvaluateActiveMeshesDuration = function () {
  21758. BABYLON.Tools.Warn("getEvaluateActiveMeshesDuration is deprecated. Please use SceneInstrumentation class");
  21759. return 0;
  21760. };
  21761. Object.defineProperty(Scene.prototype, "evaluateActiveMeshesDurationPerfCounter", {
  21762. get: function () {
  21763. BABYLON.Tools.Warn("evaluateActiveMeshesDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  21764. return null;
  21765. },
  21766. enumerable: true,
  21767. configurable: true
  21768. });
  21769. Scene.prototype.getActiveMeshes = function () {
  21770. return this._activeMeshes;
  21771. };
  21772. Scene.prototype.getRenderTargetsDuration = function () {
  21773. BABYLON.Tools.Warn("getRenderTargetsDuration is deprecated. Please use SceneInstrumentation class");
  21774. return 0;
  21775. };
  21776. Scene.prototype.getRenderDuration = function () {
  21777. BABYLON.Tools.Warn("getRenderDuration is deprecated. Please use SceneInstrumentation class");
  21778. return 0;
  21779. };
  21780. Object.defineProperty(Scene.prototype, "renderDurationPerfCounter", {
  21781. get: function () {
  21782. BABYLON.Tools.Warn("renderDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  21783. return null;
  21784. },
  21785. enumerable: true,
  21786. configurable: true
  21787. });
  21788. Scene.prototype.getParticlesDuration = function () {
  21789. BABYLON.Tools.Warn("getParticlesDuration is deprecated. Please use SceneInstrumentation class");
  21790. return 0;
  21791. };
  21792. Object.defineProperty(Scene.prototype, "particlesDurationPerfCounter", {
  21793. get: function () {
  21794. BABYLON.Tools.Warn("particlesDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  21795. return null;
  21796. },
  21797. enumerable: true,
  21798. configurable: true
  21799. });
  21800. Scene.prototype.getSpritesDuration = function () {
  21801. BABYLON.Tools.Warn("getSpritesDuration is deprecated. Please use SceneInstrumentation class");
  21802. return 0;
  21803. };
  21804. Object.defineProperty(Scene.prototype, "spriteDuractionPerfCounter", {
  21805. get: function () {
  21806. BABYLON.Tools.Warn("spriteDuractionPerfCounter is deprecated. Please use SceneInstrumentation class");
  21807. return null;
  21808. },
  21809. enumerable: true,
  21810. configurable: true
  21811. });
  21812. Scene.prototype.getAnimationRatio = function () {
  21813. return this._animationRatio;
  21814. };
  21815. Scene.prototype.getRenderId = function () {
  21816. return this._renderId;
  21817. };
  21818. Scene.prototype.incrementRenderId = function () {
  21819. this._renderId++;
  21820. };
  21821. Scene.prototype._updatePointerPosition = function (evt) {
  21822. var canvasRect = this._engine.getRenderingCanvasClientRect();
  21823. if (!canvasRect) {
  21824. return;
  21825. }
  21826. this._pointerX = evt.clientX - canvasRect.left;
  21827. this._pointerY = evt.clientY - canvasRect.top;
  21828. this._unTranslatedPointerX = this._pointerX;
  21829. this._unTranslatedPointerY = this._pointerY;
  21830. };
  21831. Scene.prototype._createUbo = function () {
  21832. this._sceneUbo = new BABYLON.UniformBuffer(this._engine, undefined, true);
  21833. this._sceneUbo.addUniform("viewProjection", 16);
  21834. this._sceneUbo.addUniform("view", 16);
  21835. };
  21836. Scene.prototype._createAlternateUbo = function () {
  21837. this._alternateSceneUbo = new BABYLON.UniformBuffer(this._engine, undefined, true);
  21838. this._alternateSceneUbo.addUniform("viewProjection", 16);
  21839. this._alternateSceneUbo.addUniform("view", 16);
  21840. };
  21841. // Pointers handling
  21842. /**
  21843. * Use this method to simulate a pointer move on a mesh
  21844. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  21845. */
  21846. Scene.prototype.simulatePointerMove = function (pickResult) {
  21847. var evt = new PointerEvent("pointermove");
  21848. return this._processPointerMove(pickResult, evt);
  21849. };
  21850. Scene.prototype._processPointerMove = function (pickResult, evt) {
  21851. var canvas = this._engine.getRenderingCanvas();
  21852. if (!canvas) {
  21853. return this;
  21854. }
  21855. if (pickResult && pickResult.hit && pickResult.pickedMesh) {
  21856. this.setPointerOverSprite(null);
  21857. this.setPointerOverMesh(pickResult.pickedMesh);
  21858. if (this._pointerOverMesh && this._pointerOverMesh.actionManager && this._pointerOverMesh.actionManager.hasPointerTriggers) {
  21859. if (this._pointerOverMesh.actionManager.hoverCursor) {
  21860. canvas.style.cursor = this._pointerOverMesh.actionManager.hoverCursor;
  21861. }
  21862. else {
  21863. canvas.style.cursor = this.hoverCursor;
  21864. }
  21865. }
  21866. else {
  21867. canvas.style.cursor = this.defaultCursor;
  21868. }
  21869. }
  21870. else {
  21871. this.setPointerOverMesh(null);
  21872. // Sprites
  21873. pickResult = this.pickSprite(this._unTranslatedPointerX, this._unTranslatedPointerY, this._spritePredicate, false, this.cameraToUseForPointers || undefined);
  21874. if (pickResult && pickResult.hit && pickResult.pickedSprite) {
  21875. this.setPointerOverSprite(pickResult.pickedSprite);
  21876. if (this._pointerOverSprite && this._pointerOverSprite.actionManager && this._pointerOverSprite.actionManager.hoverCursor) {
  21877. canvas.style.cursor = this._pointerOverSprite.actionManager.hoverCursor;
  21878. }
  21879. else {
  21880. canvas.style.cursor = this.hoverCursor;
  21881. }
  21882. }
  21883. else {
  21884. this.setPointerOverSprite(null);
  21885. // Restore pointer
  21886. canvas.style.cursor = this.defaultCursor;
  21887. }
  21888. }
  21889. if (pickResult) {
  21890. if (this.onPointerMove) {
  21891. this.onPointerMove(evt, pickResult);
  21892. }
  21893. if (this.onPointerObservable.hasObservers()) {
  21894. var type = evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? BABYLON.PointerEventTypes.POINTERWHEEL : BABYLON.PointerEventTypes.POINTERMOVE;
  21895. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  21896. this.onPointerObservable.notifyObservers(pi, type);
  21897. }
  21898. }
  21899. return this;
  21900. };
  21901. /**
  21902. * Use this method to simulate a pointer down on a mesh
  21903. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  21904. */
  21905. Scene.prototype.simulatePointerDown = function (pickResult) {
  21906. var evt = new PointerEvent("pointerdown");
  21907. return this._processPointerDown(pickResult, evt);
  21908. };
  21909. Scene.prototype._processPointerDown = function (pickResult, evt) {
  21910. var _this = this;
  21911. if (pickResult && pickResult.hit && pickResult.pickedMesh) {
  21912. this._pickedDownMesh = pickResult.pickedMesh;
  21913. var actionManager = pickResult.pickedMesh.actionManager;
  21914. if (actionManager) {
  21915. if (actionManager.hasPickTriggers) {
  21916. actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  21917. switch (evt.button) {
  21918. case 0:
  21919. actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  21920. break;
  21921. case 1:
  21922. actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  21923. break;
  21924. case 2:
  21925. actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  21926. break;
  21927. }
  21928. }
  21929. if (actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnLongPressTrigger)) {
  21930. window.setTimeout(function () {
  21931. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, function (mesh) { return (mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.actionManager && mesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnLongPressTrigger) && mesh == _this._pickedDownMesh); }, false, _this.cameraToUseForPointers);
  21932. if (pickResult && pickResult.hit && pickResult.pickedMesh && actionManager) {
  21933. if (_this._totalPointersPressed !== 0 &&
  21934. ((new Date().getTime() - _this._startingPointerTime) > Scene.LongPressDelay) &&
  21935. (Math.abs(_this._startingPointerPosition.x - _this._pointerX) < Scene.DragMovementThreshold &&
  21936. Math.abs(_this._startingPointerPosition.y - _this._pointerY) < Scene.DragMovementThreshold)) {
  21937. _this._startingPointerTime = 0;
  21938. actionManager.processTrigger(BABYLON.ActionManager.OnLongPressTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  21939. }
  21940. }
  21941. }, Scene.LongPressDelay);
  21942. }
  21943. }
  21944. }
  21945. if (pickResult) {
  21946. if (this.onPointerDown) {
  21947. this.onPointerDown(evt, pickResult);
  21948. }
  21949. if (this.onPointerObservable.hasObservers()) {
  21950. var type = BABYLON.PointerEventTypes.POINTERDOWN;
  21951. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  21952. this.onPointerObservable.notifyObservers(pi, type);
  21953. }
  21954. }
  21955. return this;
  21956. };
  21957. /**
  21958. * Use this method to simulate a pointer up on a mesh
  21959. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  21960. */
  21961. Scene.prototype.simulatePointerUp = function (pickResult) {
  21962. var evt = new PointerEvent("pointerup");
  21963. var clickInfo = new ClickInfo();
  21964. clickInfo.singleClick = true;
  21965. clickInfo.ignore = true;
  21966. return this._processPointerUp(pickResult, evt, clickInfo);
  21967. };
  21968. Scene.prototype._processPointerUp = function (pickResult, evt, clickInfo) {
  21969. if (pickResult && pickResult && pickResult.pickedMesh) {
  21970. this._pickedUpMesh = pickResult.pickedMesh;
  21971. if (this._pickedDownMesh === this._pickedUpMesh) {
  21972. if (this.onPointerPick) {
  21973. this.onPointerPick(evt, pickResult);
  21974. }
  21975. if (clickInfo.singleClick && !clickInfo.ignore && this.onPointerObservable.hasObservers()) {
  21976. var type = BABYLON.PointerEventTypes.POINTERPICK;
  21977. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  21978. this.onPointerObservable.notifyObservers(pi, type);
  21979. }
  21980. }
  21981. if (pickResult.pickedMesh.actionManager) {
  21982. if (clickInfo.ignore) {
  21983. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  21984. }
  21985. if (!clickInfo.hasSwiped && !clickInfo.ignore && clickInfo.singleClick) {
  21986. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  21987. }
  21988. if (clickInfo.doubleClick && !clickInfo.ignore && pickResult.pickedMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  21989. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnDoublePickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  21990. }
  21991. }
  21992. }
  21993. if (this._pickedDownMesh &&
  21994. this._pickedDownMesh.actionManager &&
  21995. this._pickedDownMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnPickOutTrigger) &&
  21996. this._pickedDownMesh !== this._pickedUpMesh) {
  21997. this._pickedDownMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNew(this._pickedDownMesh, evt));
  21998. }
  21999. if (this.onPointerUp) {
  22000. this.onPointerUp(evt, pickResult);
  22001. }
  22002. if (this.onPointerObservable.hasObservers()) {
  22003. if (!clickInfo.ignore) {
  22004. if (!clickInfo.hasSwiped) {
  22005. if (clickInfo.singleClick && this.onPointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)) {
  22006. var type = BABYLON.PointerEventTypes.POINTERTAP;
  22007. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  22008. this.onPointerObservable.notifyObservers(pi, type);
  22009. }
  22010. if (clickInfo.doubleClick && this.onPointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP)) {
  22011. var type = BABYLON.PointerEventTypes.POINTERDOUBLETAP;
  22012. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  22013. this.onPointerObservable.notifyObservers(pi, type);
  22014. }
  22015. }
  22016. }
  22017. else {
  22018. var type = BABYLON.PointerEventTypes.POINTERUP;
  22019. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  22020. this.onPointerObservable.notifyObservers(pi, type);
  22021. }
  22022. }
  22023. return this;
  22024. };
  22025. /**
  22026. * Attach events to the canvas (To handle actionManagers triggers and raise onPointerMove, onPointerDown and onPointerUp
  22027. * @param attachUp defines if you want to attach events to pointerup
  22028. * @param attachDown defines if you want to attach events to pointerdown
  22029. * @param attachMove defines if you want to attach events to pointermove
  22030. */
  22031. Scene.prototype.attachControl = function (attachUp, attachDown, attachMove) {
  22032. var _this = this;
  22033. if (attachUp === void 0) { attachUp = true; }
  22034. if (attachDown === void 0) { attachDown = true; }
  22035. if (attachMove === void 0) { attachMove = true; }
  22036. this._initActionManager = function (act, clickInfo) {
  22037. if (!_this._meshPickProceed) {
  22038. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);
  22039. _this._currentPickResult = pickResult;
  22040. if (pickResult) {
  22041. act = (pickResult.hit && pickResult.pickedMesh) ? pickResult.pickedMesh.actionManager : null;
  22042. }
  22043. _this._meshPickProceed = true;
  22044. }
  22045. return act;
  22046. };
  22047. this._delayedSimpleClick = function (btn, clickInfo, cb) {
  22048. // double click delay is over and that no double click has been raised since, or the 2 consecutive keys pressed are different
  22049. if ((new Date().getTime() - _this._previousStartingPointerTime > Scene.DoubleClickDelay && !_this._doubleClickOccured) ||
  22050. btn !== _this._previousButtonPressed) {
  22051. _this._doubleClickOccured = false;
  22052. clickInfo.singleClick = true;
  22053. clickInfo.ignore = false;
  22054. cb(clickInfo, _this._currentPickResult);
  22055. }
  22056. };
  22057. this._initClickEvent = function (obs1, obs2, evt, cb) {
  22058. var clickInfo = new ClickInfo();
  22059. _this._currentPickResult = null;
  22060. var act = null;
  22061. var checkPicking = obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERPICK) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERPICK)
  22062. || obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)
  22063. || obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  22064. if (!checkPicking && BABYLON.ActionManager && BABYLON.ActionManager.HasPickTriggers) {
  22065. act = _this._initActionManager(act, clickInfo);
  22066. if (act)
  22067. checkPicking = act.hasPickTriggers;
  22068. }
  22069. if (checkPicking) {
  22070. var btn = evt.button;
  22071. clickInfo.hasSwiped = Math.abs(_this._startingPointerPosition.x - _this._pointerX) > Scene.DragMovementThreshold ||
  22072. Math.abs(_this._startingPointerPosition.y - _this._pointerY) > Scene.DragMovementThreshold;
  22073. if (!clickInfo.hasSwiped) {
  22074. var checkSingleClickImmediately = !Scene.ExclusiveDoubleClickMode;
  22075. if (!checkSingleClickImmediately) {
  22076. checkSingleClickImmediately = !obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) &&
  22077. !obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  22078. if (checkSingleClickImmediately && !BABYLON.ActionManager.HasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  22079. act = _this._initActionManager(act, clickInfo);
  22080. if (act)
  22081. checkSingleClickImmediately = !act.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger);
  22082. }
  22083. }
  22084. if (checkSingleClickImmediately) {
  22085. // single click detected if double click delay is over or two different successive keys pressed without exclusive double click or no double click required
  22086. if (new Date().getTime() - _this._previousStartingPointerTime > Scene.DoubleClickDelay ||
  22087. btn !== _this._previousButtonPressed) {
  22088. clickInfo.singleClick = true;
  22089. cb(clickInfo, _this._currentPickResult);
  22090. }
  22091. }
  22092. else {
  22093. // wait that no double click has been raised during the double click delay
  22094. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  22095. _this._delayedSimpleClickTimeout = window.setTimeout(_this._delayedSimpleClick.bind(_this, btn, clickInfo, cb), Scene.DoubleClickDelay);
  22096. }
  22097. var checkDoubleClick = obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) ||
  22098. obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  22099. if (!checkDoubleClick && BABYLON.ActionManager.HasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  22100. act = _this._initActionManager(act, clickInfo);
  22101. if (act)
  22102. checkDoubleClick = act.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger);
  22103. }
  22104. if (checkDoubleClick) {
  22105. // two successive keys pressed are equal, double click delay is not over and double click has not just occurred
  22106. if (btn === _this._previousButtonPressed &&
  22107. new Date().getTime() - _this._previousStartingPointerTime < Scene.DoubleClickDelay &&
  22108. !_this._doubleClickOccured) {
  22109. // pointer has not moved for 2 clicks, it's a double click
  22110. if (!clickInfo.hasSwiped &&
  22111. Math.abs(_this._previousStartingPointerPosition.x - _this._startingPointerPosition.x) < Scene.DragMovementThreshold &&
  22112. Math.abs(_this._previousStartingPointerPosition.y - _this._startingPointerPosition.y) < Scene.DragMovementThreshold) {
  22113. _this._previousStartingPointerTime = 0;
  22114. _this._doubleClickOccured = true;
  22115. clickInfo.doubleClick = true;
  22116. clickInfo.ignore = false;
  22117. if (Scene.ExclusiveDoubleClickMode && _this._previousDelayedSimpleClickTimeout) {
  22118. clearTimeout(_this._previousDelayedSimpleClickTimeout);
  22119. }
  22120. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  22121. cb(clickInfo, _this._currentPickResult);
  22122. }
  22123. else {
  22124. _this._doubleClickOccured = false;
  22125. _this._previousStartingPointerTime = _this._startingPointerTime;
  22126. _this._previousStartingPointerPosition.x = _this._startingPointerPosition.x;
  22127. _this._previousStartingPointerPosition.y = _this._startingPointerPosition.y;
  22128. _this._previousButtonPressed = btn;
  22129. if (Scene.ExclusiveDoubleClickMode) {
  22130. if (_this._previousDelayedSimpleClickTimeout) {
  22131. clearTimeout(_this._previousDelayedSimpleClickTimeout);
  22132. }
  22133. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  22134. cb(clickInfo, _this._previousPickResult);
  22135. }
  22136. else {
  22137. cb(clickInfo, _this._currentPickResult);
  22138. }
  22139. }
  22140. }
  22141. else {
  22142. _this._doubleClickOccured = false;
  22143. _this._previousStartingPointerTime = _this._startingPointerTime;
  22144. _this._previousStartingPointerPosition.x = _this._startingPointerPosition.x;
  22145. _this._previousStartingPointerPosition.y = _this._startingPointerPosition.y;
  22146. _this._previousButtonPressed = btn;
  22147. }
  22148. }
  22149. }
  22150. }
  22151. clickInfo.ignore = true;
  22152. cb(clickInfo, _this._currentPickResult);
  22153. };
  22154. this._spritePredicate = function (sprite) {
  22155. return sprite.isPickable && sprite.actionManager && sprite.actionManager.hasPointerTriggers;
  22156. };
  22157. this._onPointerMove = function (evt) {
  22158. _this._updatePointerPosition(evt);
  22159. // PreObservable support
  22160. if (_this.onPrePointerObservable.hasObservers()) {
  22161. var type = evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? BABYLON.PointerEventTypes.POINTERWHEEL : BABYLON.PointerEventTypes.POINTERMOVE;
  22162. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  22163. _this.onPrePointerObservable.notifyObservers(pi, type);
  22164. if (pi.skipOnPointerObservable) {
  22165. return;
  22166. }
  22167. }
  22168. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  22169. return;
  22170. }
  22171. if (!_this.pointerMovePredicate) {
  22172. _this.pointerMovePredicate = function (mesh) { return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled() && (mesh.enablePointerMoveEvents || _this.constantlyUpdateMeshUnderPointer || (mesh.actionManager !== null && mesh.actionManager !== undefined)); };
  22173. }
  22174. // Meshes
  22175. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerMovePredicate, false, _this.cameraToUseForPointers);
  22176. _this._processPointerMove(pickResult, evt);
  22177. };
  22178. this._onPointerDown = function (evt) {
  22179. _this._totalPointersPressed++;
  22180. _this._pickedDownMesh = null;
  22181. _this._meshPickProceed = false;
  22182. _this._updatePointerPosition(evt);
  22183. if (_this.preventDefaultOnPointerDown && canvas) {
  22184. evt.preventDefault();
  22185. canvas.focus();
  22186. }
  22187. // PreObservable support
  22188. if (_this.onPrePointerObservable.hasObservers()) {
  22189. var type = BABYLON.PointerEventTypes.POINTERDOWN;
  22190. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  22191. _this.onPrePointerObservable.notifyObservers(pi, type);
  22192. if (pi.skipOnPointerObservable) {
  22193. return;
  22194. }
  22195. }
  22196. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  22197. return;
  22198. }
  22199. _this._startingPointerPosition.x = _this._pointerX;
  22200. _this._startingPointerPosition.y = _this._pointerY;
  22201. _this._startingPointerTime = new Date().getTime();
  22202. if (!_this.pointerDownPredicate) {
  22203. _this.pointerDownPredicate = function (mesh) {
  22204. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled();
  22205. };
  22206. }
  22207. // Meshes
  22208. _this._pickedDownMesh = null;
  22209. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);
  22210. _this._processPointerDown(pickResult, evt);
  22211. // Sprites
  22212. _this._pickedDownSprite = null;
  22213. if (_this.spriteManagers.length > 0) {
  22214. pickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this._spritePredicate, false, _this.cameraToUseForPointers || undefined);
  22215. if (pickResult && pickResult.hit && pickResult.pickedSprite) {
  22216. if (pickResult.pickedSprite.actionManager) {
  22217. _this._pickedDownSprite = pickResult.pickedSprite;
  22218. switch (evt.button) {
  22219. case 0:
  22220. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  22221. break;
  22222. case 1:
  22223. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  22224. break;
  22225. case 2:
  22226. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  22227. break;
  22228. }
  22229. if (pickResult.pickedSprite.actionManager) {
  22230. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  22231. }
  22232. }
  22233. }
  22234. }
  22235. };
  22236. this._onPointerUp = function (evt) {
  22237. if (_this._totalPointersPressed === 0) {
  22238. return; // So we need to test it the pointer down was pressed before.
  22239. }
  22240. _this._totalPointersPressed--;
  22241. _this._pickedUpMesh = null;
  22242. _this._meshPickProceed = false;
  22243. _this._updatePointerPosition(evt);
  22244. _this._initClickEvent(_this.onPrePointerObservable, _this.onPointerObservable, evt, function (clickInfo, pickResult) {
  22245. // PreObservable support
  22246. if (_this.onPrePointerObservable.hasObservers()) {
  22247. if (!clickInfo.ignore) {
  22248. if (!clickInfo.hasSwiped) {
  22249. if (clickInfo.singleClick && _this.onPrePointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)) {
  22250. var type = BABYLON.PointerEventTypes.POINTERTAP;
  22251. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  22252. _this.onPrePointerObservable.notifyObservers(pi, type);
  22253. if (pi.skipOnPointerObservable) {
  22254. return;
  22255. }
  22256. }
  22257. if (clickInfo.doubleClick && _this.onPrePointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP)) {
  22258. var type = BABYLON.PointerEventTypes.POINTERDOUBLETAP;
  22259. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  22260. _this.onPrePointerObservable.notifyObservers(pi, type);
  22261. if (pi.skipOnPointerObservable) {
  22262. return;
  22263. }
  22264. }
  22265. }
  22266. }
  22267. else {
  22268. var type = BABYLON.PointerEventTypes.POINTERUP;
  22269. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  22270. _this.onPrePointerObservable.notifyObservers(pi, type);
  22271. if (pi.skipOnPointerObservable) {
  22272. return;
  22273. }
  22274. }
  22275. }
  22276. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  22277. return;
  22278. }
  22279. if (!_this.pointerUpPredicate) {
  22280. _this.pointerUpPredicate = function (mesh) {
  22281. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled();
  22282. };
  22283. }
  22284. // Meshes
  22285. if (!_this._meshPickProceed && (BABYLON.ActionManager && BABYLON.ActionManager.HasTriggers || _this.onPointerObservable.hasObservers())) {
  22286. _this._initActionManager(null, clickInfo);
  22287. }
  22288. if (!pickResult) {
  22289. pickResult = _this._currentPickResult;
  22290. }
  22291. _this._processPointerUp(pickResult, evt, clickInfo);
  22292. // Sprites
  22293. if (_this.spriteManagers.length > 0) {
  22294. var spritePickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this._spritePredicate, false, _this.cameraToUseForPointers || undefined);
  22295. if (spritePickResult) {
  22296. if (spritePickResult.hit && spritePickResult.pickedSprite) {
  22297. if (spritePickResult.pickedSprite.actionManager) {
  22298. spritePickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNewFromSprite(spritePickResult.pickedSprite, _this, evt));
  22299. if (spritePickResult.pickedSprite.actionManager) {
  22300. if (Math.abs(_this._startingPointerPosition.x - _this._pointerX) < Scene.DragMovementThreshold && Math.abs(_this._startingPointerPosition.y - _this._pointerY) < Scene.DragMovementThreshold) {
  22301. spritePickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(spritePickResult.pickedSprite, _this, evt));
  22302. }
  22303. }
  22304. }
  22305. }
  22306. if (_this._pickedDownSprite && _this._pickedDownSprite.actionManager && _this._pickedDownSprite !== spritePickResult.pickedSprite) {
  22307. _this._pickedDownSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(_this._pickedDownSprite, _this, evt));
  22308. }
  22309. }
  22310. }
  22311. _this._previousPickResult = _this._currentPickResult;
  22312. });
  22313. };
  22314. this._onKeyDown = function (evt) {
  22315. var type = BABYLON.KeyboardEventTypes.KEYDOWN;
  22316. if (_this.onPreKeyboardObservable.hasObservers()) {
  22317. var pi = new BABYLON.KeyboardInfoPre(type, evt);
  22318. _this.onPreKeyboardObservable.notifyObservers(pi, type);
  22319. if (pi.skipOnPointerObservable) {
  22320. return;
  22321. }
  22322. }
  22323. if (_this.onKeyboardObservable.hasObservers()) {
  22324. var pi = new BABYLON.KeyboardInfo(type, evt);
  22325. _this.onKeyboardObservable.notifyObservers(pi, type);
  22326. }
  22327. if (_this.actionManager) {
  22328. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyDownTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  22329. }
  22330. };
  22331. this._onKeyUp = function (evt) {
  22332. var type = BABYLON.KeyboardEventTypes.KEYUP;
  22333. if (_this.onPreKeyboardObservable.hasObservers()) {
  22334. var pi = new BABYLON.KeyboardInfoPre(type, evt);
  22335. _this.onPreKeyboardObservable.notifyObservers(pi, type);
  22336. if (pi.skipOnPointerObservable) {
  22337. return;
  22338. }
  22339. }
  22340. if (_this.onKeyboardObservable.hasObservers()) {
  22341. var pi = new BABYLON.KeyboardInfo(type, evt);
  22342. _this.onKeyboardObservable.notifyObservers(pi, type);
  22343. }
  22344. if (_this.actionManager) {
  22345. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyUpTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  22346. }
  22347. };
  22348. var engine = this.getEngine();
  22349. this._onCanvasFocusObserver = engine.onCanvasFocusObservable.add(function () {
  22350. if (!canvas) {
  22351. return;
  22352. }
  22353. canvas.addEventListener("keydown", _this._onKeyDown, false);
  22354. canvas.addEventListener("keyup", _this._onKeyUp, false);
  22355. });
  22356. this._onCanvasBlurObserver = engine.onCanvasBlurObservable.add(function () {
  22357. if (!canvas) {
  22358. return;
  22359. }
  22360. canvas.removeEventListener("keydown", _this._onKeyDown);
  22361. canvas.removeEventListener("keyup", _this._onKeyUp);
  22362. });
  22363. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  22364. var canvas = this._engine.getRenderingCanvas();
  22365. if (!canvas) {
  22366. return;
  22367. }
  22368. if (attachMove) {
  22369. canvas.addEventListener(eventPrefix + "move", this._onPointerMove, false);
  22370. // Wheel
  22371. canvas.addEventListener('mousewheel', this._onPointerMove, false);
  22372. canvas.addEventListener('DOMMouseScroll', this._onPointerMove, false);
  22373. }
  22374. if (attachDown) {
  22375. canvas.addEventListener(eventPrefix + "down", this._onPointerDown, false);
  22376. }
  22377. if (attachUp) {
  22378. window.addEventListener(eventPrefix + "up", this._onPointerUp, false);
  22379. }
  22380. canvas.tabIndex = 1;
  22381. };
  22382. Scene.prototype.detachControl = function () {
  22383. var engine = this.getEngine();
  22384. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  22385. var canvas = engine.getRenderingCanvas();
  22386. if (!canvas) {
  22387. return;
  22388. }
  22389. canvas.removeEventListener(eventPrefix + "move", this._onPointerMove);
  22390. canvas.removeEventListener(eventPrefix + "down", this._onPointerDown);
  22391. window.removeEventListener(eventPrefix + "up", this._onPointerUp);
  22392. if (this._onCanvasBlurObserver) {
  22393. engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  22394. }
  22395. if (this._onCanvasFocusObserver) {
  22396. engine.onCanvasFocusObservable.remove(this._onCanvasFocusObserver);
  22397. }
  22398. // Wheel
  22399. canvas.removeEventListener('mousewheel', this._onPointerMove);
  22400. canvas.removeEventListener('DOMMouseScroll', this._onPointerMove);
  22401. // Keyboard
  22402. canvas.removeEventListener("keydown", this._onKeyDown);
  22403. canvas.removeEventListener("keyup", this._onKeyUp);
  22404. // Observables
  22405. this.onKeyboardObservable.clear();
  22406. this.onPreKeyboardObservable.clear();
  22407. this.onPointerObservable.clear();
  22408. this.onPrePointerObservable.clear();
  22409. };
  22410. /**
  22411. * This function will check if the scene can be rendered (textures are loaded, shaders are compiled)
  22412. * Delay loaded resources are not taking in account
  22413. * @return true if all required resources are ready
  22414. */
  22415. Scene.prototype.isReady = function () {
  22416. if (this._isDisposed) {
  22417. return false;
  22418. }
  22419. if (this._pendingData.length > 0) {
  22420. return false;
  22421. }
  22422. var index;
  22423. var engine = this.getEngine();
  22424. // Geometries
  22425. for (index = 0; index < this._geometries.length; index++) {
  22426. var geometry = this._geometries[index];
  22427. if (geometry.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  22428. return false;
  22429. }
  22430. }
  22431. // Meshes
  22432. for (index = 0; index < this.meshes.length; index++) {
  22433. var mesh = this.meshes[index];
  22434. if (!mesh.isEnabled()) {
  22435. continue;
  22436. }
  22437. if (!mesh.subMeshes || mesh.subMeshes.length === 0) {
  22438. continue;
  22439. }
  22440. if (!mesh.isReady(true)) {
  22441. return false;
  22442. }
  22443. // Effect layers
  22444. var hardwareInstancedRendering = mesh.getClassName() === "InstancedMesh" || engine.getCaps().instancedArrays && mesh.instances.length > 0;
  22445. for (var _i = 0, _a = this.effectLayers; _i < _a.length; _i++) {
  22446. var layer = _a[_i];
  22447. if (!layer.hasMesh(mesh)) {
  22448. continue;
  22449. }
  22450. for (var _b = 0, _c = mesh.subMeshes; _b < _c.length; _b++) {
  22451. var subMesh = _c[_b];
  22452. if (!layer.isReady(subMesh, hardwareInstancedRendering)) {
  22453. return false;
  22454. }
  22455. }
  22456. }
  22457. }
  22458. return true;
  22459. };
  22460. Scene.prototype.resetCachedMaterial = function () {
  22461. this._cachedMaterial = null;
  22462. this._cachedEffect = null;
  22463. this._cachedVisibility = null;
  22464. };
  22465. Scene.prototype.registerBeforeRender = function (func) {
  22466. this.onBeforeRenderObservable.add(func);
  22467. };
  22468. Scene.prototype.unregisterBeforeRender = function (func) {
  22469. this.onBeforeRenderObservable.removeCallback(func);
  22470. };
  22471. Scene.prototype.registerAfterRender = function (func) {
  22472. this.onAfterRenderObservable.add(func);
  22473. };
  22474. Scene.prototype.unregisterAfterRender = function (func) {
  22475. this.onAfterRenderObservable.removeCallback(func);
  22476. };
  22477. Scene.prototype._executeOnceBeforeRender = function (func) {
  22478. var _this = this;
  22479. var execFunc = function () {
  22480. func();
  22481. setTimeout(function () {
  22482. _this.unregisterBeforeRender(execFunc);
  22483. });
  22484. };
  22485. this.registerBeforeRender(execFunc);
  22486. };
  22487. /**
  22488. * The provided function will run before render once and will be disposed afterwards.
  22489. * A timeout delay can be provided so that the function will be executed in N ms.
  22490. * The timeout is using the browser's native setTimeout so time percision cannot be guaranteed.
  22491. * @param func The function to be executed.
  22492. * @param timeout optional delay in ms
  22493. */
  22494. Scene.prototype.executeOnceBeforeRender = function (func, timeout) {
  22495. var _this = this;
  22496. if (timeout !== undefined) {
  22497. setTimeout(function () {
  22498. _this._executeOnceBeforeRender(func);
  22499. }, timeout);
  22500. }
  22501. else {
  22502. this._executeOnceBeforeRender(func);
  22503. }
  22504. };
  22505. Scene.prototype._addPendingData = function (data) {
  22506. this._pendingData.push(data);
  22507. };
  22508. Scene.prototype._removePendingData = function (data) {
  22509. var wasLoading = this.isLoading;
  22510. var index = this._pendingData.indexOf(data);
  22511. if (index !== -1) {
  22512. this._pendingData.splice(index, 1);
  22513. }
  22514. if (wasLoading && !this.isLoading) {
  22515. this.onDataLoadedObservable.notifyObservers(this);
  22516. }
  22517. };
  22518. Scene.prototype.getWaitingItemsCount = function () {
  22519. return this._pendingData.length;
  22520. };
  22521. Object.defineProperty(Scene.prototype, "isLoading", {
  22522. get: function () {
  22523. return this._pendingData.length > 0;
  22524. },
  22525. enumerable: true,
  22526. configurable: true
  22527. });
  22528. /**
  22529. * Registers a function to be executed when the scene is ready.
  22530. * @param {Function} func - the function to be executed.
  22531. */
  22532. Scene.prototype.executeWhenReady = function (func) {
  22533. var _this = this;
  22534. this.onReadyObservable.add(func);
  22535. if (this._executeWhenReadyTimeoutId !== -1) {
  22536. return;
  22537. }
  22538. this._executeWhenReadyTimeoutId = setTimeout(function () {
  22539. _this._checkIsReady();
  22540. }, 150);
  22541. };
  22542. /**
  22543. * Returns a promise that resolves when the scene is ready.
  22544. * @returns A promise that resolves when the scene is ready.
  22545. */
  22546. Scene.prototype.whenReadyAsync = function () {
  22547. var _this = this;
  22548. return new Promise(function (resolve) {
  22549. _this.executeWhenReady(function () {
  22550. resolve();
  22551. });
  22552. });
  22553. };
  22554. Scene.prototype._checkIsReady = function () {
  22555. var _this = this;
  22556. if (this.isReady()) {
  22557. this.onReadyObservable.notifyObservers(this);
  22558. this.onReadyObservable.clear();
  22559. this._executeWhenReadyTimeoutId = -1;
  22560. return;
  22561. }
  22562. this._executeWhenReadyTimeoutId = setTimeout(function () {
  22563. _this._checkIsReady();
  22564. }, 150);
  22565. };
  22566. // Animations
  22567. /**
  22568. * Will start the animation sequence of a given target
  22569. * @param target - the target
  22570. * @param {number} from - from which frame should animation start
  22571. * @param {number} to - till which frame should animation run.
  22572. * @param {boolean} [loop] - should the animation loop
  22573. * @param {number} [speedRatio] - the speed in which to run the animation
  22574. * @param {Function} [onAnimationEnd] function to be executed when the animation ended.
  22575. * @param {BABYLON.Animatable} [animatable] an animatable object. If not provided a new one will be created from the given params.
  22576. * Returns {BABYLON.Animatable} the animatable object created for this animation
  22577. * See BABYLON.Animatable
  22578. */
  22579. Scene.prototype.beginAnimation = function (target, from, to, loop, speedRatio, onAnimationEnd, animatable) {
  22580. if (speedRatio === void 0) { speedRatio = 1.0; }
  22581. if (from > to && speedRatio > 0) {
  22582. speedRatio *= -1;
  22583. }
  22584. this.stopAnimation(target);
  22585. if (!animatable) {
  22586. animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd);
  22587. }
  22588. // Local animations
  22589. if (target.animations) {
  22590. animatable.appendAnimations(target, target.animations);
  22591. }
  22592. // Children animations
  22593. if (target.getAnimatables) {
  22594. var animatables = target.getAnimatables();
  22595. for (var index = 0; index < animatables.length; index++) {
  22596. this.beginAnimation(animatables[index], from, to, loop, speedRatio, onAnimationEnd, animatable);
  22597. }
  22598. }
  22599. animatable.reset();
  22600. return animatable;
  22601. };
  22602. /**
  22603. * Begin a new animation on a given node
  22604. * @param {BABYLON.Node} node defines the root node where the animation will take place
  22605. * @param {BABYLON.Animation[]} defines the list of animations to start
  22606. * @param {number} from defines the initial value
  22607. * @param {number} to defines the final value
  22608. * @param {boolean} loop defines if you want animation to loop (off by default)
  22609. * @param {number} speedRatio defines the speed ratio to apply to all animations
  22610. * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)
  22611. * @returns the list of created animatables
  22612. */
  22613. Scene.prototype.beginDirectAnimation = function (target, animations, from, to, loop, speedRatio, onAnimationEnd) {
  22614. if (speedRatio === undefined) {
  22615. speedRatio = 1.0;
  22616. }
  22617. var animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd, animations);
  22618. return animatable;
  22619. };
  22620. /**
  22621. * Begin a new animation on a given node and its hierarchy
  22622. * @param {BABYLON.Node} node defines the root node where the animation will take place
  22623. * @param {boolean} directDescendantsOnly if true only direct descendants will be used, if false direct and also indirect (children of children, an so on in a recursive manner) descendants will be used.
  22624. * @param {BABYLON.Animation[]} defines the list of animations to start
  22625. * @param {number} from defines the initial value
  22626. * @param {number} to defines the final value
  22627. * @param {boolean} loop defines if you want animation to loop (off by default)
  22628. * @param {number} speedRatio defines the speed ratio to apply to all animations
  22629. * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)
  22630. * @returns the list of animatables created for all nodes
  22631. */
  22632. Scene.prototype.beginDirectHierarchyAnimation = function (target, directDescendantsOnly, animations, from, to, loop, speedRatio, onAnimationEnd) {
  22633. var children = target.getDescendants(directDescendantsOnly);
  22634. var result = [];
  22635. for (var _i = 0, children_1 = children; _i < children_1.length; _i++) {
  22636. var child = children_1[_i];
  22637. result.push(this.beginDirectAnimation(child, animations, from, to, loop, speedRatio, onAnimationEnd));
  22638. }
  22639. return result;
  22640. };
  22641. Scene.prototype.getAnimatableByTarget = function (target) {
  22642. for (var index = 0; index < this._activeAnimatables.length; index++) {
  22643. if (this._activeAnimatables[index].target === target) {
  22644. return this._activeAnimatables[index];
  22645. }
  22646. }
  22647. return null;
  22648. };
  22649. Object.defineProperty(Scene.prototype, "animatables", {
  22650. get: function () {
  22651. return this._activeAnimatables;
  22652. },
  22653. enumerable: true,
  22654. configurable: true
  22655. });
  22656. /**
  22657. * Will stop the animation of the given target
  22658. * @param target - the target
  22659. * @param animationName - the name of the animation to stop (all animations will be stopped is empty)
  22660. * @see beginAnimation
  22661. */
  22662. Scene.prototype.stopAnimation = function (target, animationName) {
  22663. var animatable = this.getAnimatableByTarget(target);
  22664. if (animatable) {
  22665. animatable.stop(animationName);
  22666. }
  22667. };
  22668. /**
  22669. * Stops and removes all animations that have been applied to the scene
  22670. */
  22671. Scene.prototype.stopAllAnimations = function () {
  22672. if (this._activeAnimatables) {
  22673. for (var i = 0; i < this._activeAnimatables.length; i++) {
  22674. this._activeAnimatables[i].stop();
  22675. }
  22676. this._activeAnimatables = [];
  22677. }
  22678. };
  22679. Scene.prototype._animate = function () {
  22680. if (!this.animationsEnabled || this._activeAnimatables.length === 0) {
  22681. return;
  22682. }
  22683. // Getting time
  22684. var now = BABYLON.Tools.Now;
  22685. if (!this._animationTimeLast) {
  22686. if (this._pendingData.length > 0) {
  22687. return;
  22688. }
  22689. this._animationTimeLast = now;
  22690. }
  22691. var deltaTime = this.useConstantAnimationDeltaTime ? 16.0 : (now - this._animationTimeLast) * this.animationTimeScale;
  22692. this._animationTime += deltaTime;
  22693. this._animationTimeLast = now;
  22694. for (var index = 0; index < this._activeAnimatables.length; index++) {
  22695. this._activeAnimatables[index]._animate(this._animationTime);
  22696. }
  22697. };
  22698. // Matrix
  22699. Scene.prototype._switchToAlternateCameraConfiguration = function (active) {
  22700. this._useAlternateCameraConfiguration = active;
  22701. };
  22702. Scene.prototype.getViewMatrix = function () {
  22703. return this._useAlternateCameraConfiguration ? this._alternateViewMatrix : this._viewMatrix;
  22704. };
  22705. Scene.prototype.getProjectionMatrix = function () {
  22706. return this._useAlternateCameraConfiguration ? this._alternateProjectionMatrix : this._projectionMatrix;
  22707. };
  22708. Scene.prototype.getTransformMatrix = function () {
  22709. return this._useAlternateCameraConfiguration ? this._alternateTransformMatrix : this._transformMatrix;
  22710. };
  22711. Scene.prototype.setTransformMatrix = function (view, projection) {
  22712. if (this._viewUpdateFlag === view.updateFlag && this._projectionUpdateFlag === projection.updateFlag) {
  22713. return;
  22714. }
  22715. this._viewUpdateFlag = view.updateFlag;
  22716. this._projectionUpdateFlag = projection.updateFlag;
  22717. this._viewMatrix = view;
  22718. this._projectionMatrix = projection;
  22719. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  22720. // Update frustum
  22721. if (!this._frustumPlanes) {
  22722. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  22723. }
  22724. else {
  22725. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  22726. }
  22727. if (this.activeCamera && this.activeCamera._alternateCamera) {
  22728. var otherCamera = this.activeCamera._alternateCamera;
  22729. otherCamera.getViewMatrix().multiplyToRef(otherCamera.getProjectionMatrix(), BABYLON.Tmp.Matrix[0]);
  22730. BABYLON.Frustum.GetRightPlaneToRef(BABYLON.Tmp.Matrix[0], this._frustumPlanes[3]); // Replace right plane by second camera right plane
  22731. }
  22732. if (this._sceneUbo.useUbo) {
  22733. this._sceneUbo.updateMatrix("viewProjection", this._transformMatrix);
  22734. this._sceneUbo.updateMatrix("view", this._viewMatrix);
  22735. this._sceneUbo.update();
  22736. }
  22737. };
  22738. Scene.prototype._setAlternateTransformMatrix = function (view, projection) {
  22739. if (this._alternateViewUpdateFlag === view.updateFlag && this._alternateProjectionUpdateFlag === projection.updateFlag) {
  22740. return;
  22741. }
  22742. this._alternateViewUpdateFlag = view.updateFlag;
  22743. this._alternateProjectionUpdateFlag = projection.updateFlag;
  22744. this._alternateViewMatrix = view;
  22745. this._alternateProjectionMatrix = projection;
  22746. if (!this._alternateTransformMatrix) {
  22747. this._alternateTransformMatrix = BABYLON.Matrix.Zero();
  22748. }
  22749. this._alternateViewMatrix.multiplyToRef(this._alternateProjectionMatrix, this._alternateTransformMatrix);
  22750. if (!this._alternateSceneUbo) {
  22751. this._createAlternateUbo();
  22752. }
  22753. if (this._alternateSceneUbo.useUbo) {
  22754. this._alternateSceneUbo.updateMatrix("viewProjection", this._alternateTransformMatrix);
  22755. this._alternateSceneUbo.updateMatrix("view", this._alternateViewMatrix);
  22756. this._alternateSceneUbo.update();
  22757. }
  22758. };
  22759. Scene.prototype.getSceneUniformBuffer = function () {
  22760. return this._useAlternateCameraConfiguration ? this._alternateSceneUbo : this._sceneUbo;
  22761. };
  22762. // Methods
  22763. Scene.prototype.getUniqueId = function () {
  22764. var result = Scene._uniqueIdCounter;
  22765. Scene._uniqueIdCounter++;
  22766. return result;
  22767. };
  22768. Scene.prototype.addMesh = function (newMesh) {
  22769. this.meshes.push(newMesh);
  22770. //notify the collision coordinator
  22771. if (this.collisionCoordinator) {
  22772. this.collisionCoordinator.onMeshAdded(newMesh);
  22773. }
  22774. newMesh._resyncLightSources();
  22775. this.onNewMeshAddedObservable.notifyObservers(newMesh);
  22776. };
  22777. Scene.prototype.removeMesh = function (toRemove) {
  22778. var index = this.meshes.indexOf(toRemove);
  22779. if (index !== -1) {
  22780. // Remove from the scene if mesh found
  22781. this.meshes.splice(index, 1);
  22782. }
  22783. this.onMeshRemovedObservable.notifyObservers(toRemove);
  22784. return index;
  22785. };
  22786. Scene.prototype.addTransformNode = function (newTransformNode) {
  22787. this.transformNodes.push(newTransformNode);
  22788. this.onNewTransformNodeAddedObservable.notifyObservers(newTransformNode);
  22789. };
  22790. Scene.prototype.removeTransformNode = function (toRemove) {
  22791. var index = this.transformNodes.indexOf(toRemove);
  22792. if (index !== -1) {
  22793. // Remove from the scene if found
  22794. this.transformNodes.splice(index, 1);
  22795. }
  22796. this.onTransformNodeRemovedObservable.notifyObservers(toRemove);
  22797. return index;
  22798. };
  22799. Scene.prototype.removeSkeleton = function (toRemove) {
  22800. var index = this.skeletons.indexOf(toRemove);
  22801. if (index !== -1) {
  22802. // Remove from the scene if found
  22803. this.skeletons.splice(index, 1);
  22804. }
  22805. return index;
  22806. };
  22807. Scene.prototype.removeMorphTargetManager = function (toRemove) {
  22808. var index = this.morphTargetManagers.indexOf(toRemove);
  22809. if (index !== -1) {
  22810. // Remove from the scene if found
  22811. this.morphTargetManagers.splice(index, 1);
  22812. }
  22813. return index;
  22814. };
  22815. Scene.prototype.removeLight = function (toRemove) {
  22816. var index = this.lights.indexOf(toRemove);
  22817. if (index !== -1) {
  22818. // Remove from meshes
  22819. for (var _i = 0, _a = this.meshes; _i < _a.length; _i++) {
  22820. var mesh = _a[_i];
  22821. mesh._removeLightSource(toRemove);
  22822. }
  22823. // Remove from the scene if mesh found
  22824. this.lights.splice(index, 1);
  22825. this.sortLightsByPriority();
  22826. }
  22827. this.onLightRemovedObservable.notifyObservers(toRemove);
  22828. return index;
  22829. };
  22830. Scene.prototype.removeCamera = function (toRemove) {
  22831. var index = this.cameras.indexOf(toRemove);
  22832. if (index !== -1) {
  22833. // Remove from the scene if mesh found
  22834. this.cameras.splice(index, 1);
  22835. }
  22836. // Remove from activeCameras
  22837. var index2 = this.activeCameras.indexOf(toRemove);
  22838. if (index2 !== -1) {
  22839. // Remove from the scene if mesh found
  22840. this.activeCameras.splice(index2, 1);
  22841. }
  22842. // Reset the activeCamera
  22843. if (this.activeCamera === toRemove) {
  22844. if (this.cameras.length > 0) {
  22845. this.activeCamera = this.cameras[0];
  22846. }
  22847. else {
  22848. this.activeCamera = null;
  22849. }
  22850. }
  22851. this.onCameraRemovedObservable.notifyObservers(toRemove);
  22852. return index;
  22853. };
  22854. Scene.prototype.removeParticleSystem = function (toRemove) {
  22855. var index = this.particleSystems.indexOf(toRemove);
  22856. if (index !== -1) {
  22857. this.particleSystems.splice(index, 1);
  22858. }
  22859. return index;
  22860. };
  22861. ;
  22862. Scene.prototype.removeAnimation = function (toRemove) {
  22863. var index = this.animations.indexOf(toRemove);
  22864. if (index !== -1) {
  22865. this.animations.splice(index, 1);
  22866. }
  22867. return index;
  22868. };
  22869. ;
  22870. Scene.prototype.removeMultiMaterial = function (toRemove) {
  22871. var index = this.multiMaterials.indexOf(toRemove);
  22872. if (index !== -1) {
  22873. this.multiMaterials.splice(index, 1);
  22874. }
  22875. return index;
  22876. };
  22877. ;
  22878. Scene.prototype.removeMaterial = function (toRemove) {
  22879. var index = this.materials.indexOf(toRemove);
  22880. if (index !== -1) {
  22881. this.materials.splice(index, 1);
  22882. }
  22883. return index;
  22884. };
  22885. ;
  22886. Scene.prototype.removeLensFlareSystem = function (toRemove) {
  22887. var index = this.lensFlareSystems.indexOf(toRemove);
  22888. if (index !== -1) {
  22889. this.lensFlareSystems.splice(index, 1);
  22890. }
  22891. return index;
  22892. };
  22893. ;
  22894. Scene.prototype.removeActionManager = function (toRemove) {
  22895. var index = this._actionManagers.indexOf(toRemove);
  22896. if (index !== -1) {
  22897. this._actionManagers.splice(index, 1);
  22898. }
  22899. return index;
  22900. };
  22901. ;
  22902. Scene.prototype.addLight = function (newLight) {
  22903. this.lights.push(newLight);
  22904. this.sortLightsByPriority();
  22905. // Add light to all meshes (To support if the light is removed and then readded)
  22906. for (var _i = 0, _a = this.meshes; _i < _a.length; _i++) {
  22907. var mesh = _a[_i];
  22908. if (mesh._lightSources.indexOf(newLight) === -1) {
  22909. mesh._lightSources.push(newLight);
  22910. mesh._resyncLightSources();
  22911. }
  22912. }
  22913. this.onNewLightAddedObservable.notifyObservers(newLight);
  22914. };
  22915. Scene.prototype.sortLightsByPriority = function () {
  22916. if (this.requireLightSorting) {
  22917. this.lights.sort(BABYLON.Light.CompareLightsPriority);
  22918. }
  22919. };
  22920. Scene.prototype.addCamera = function (newCamera) {
  22921. this.cameras.push(newCamera);
  22922. this.onNewCameraAddedObservable.notifyObservers(newCamera);
  22923. };
  22924. Scene.prototype.addSkeleton = function (newSkeleton) {
  22925. this.skeletons.push(newSkeleton);
  22926. };
  22927. Scene.prototype.addParticleSystem = function (newParticleSystem) {
  22928. this.particleSystems.push(newParticleSystem);
  22929. };
  22930. Scene.prototype.addAnimation = function (newAnimation) {
  22931. this.animations.push(newAnimation);
  22932. };
  22933. Scene.prototype.addMultiMaterial = function (newMultiMaterial) {
  22934. this.multiMaterials.push(newMultiMaterial);
  22935. };
  22936. Scene.prototype.addMaterial = function (newMaterial) {
  22937. this.materials.push(newMaterial);
  22938. };
  22939. Scene.prototype.addMorphTargetManager = function (newMorphTargetManager) {
  22940. this.morphTargetManagers.push(newMorphTargetManager);
  22941. };
  22942. Scene.prototype.addGeometry = function (newGeometrie) {
  22943. this._geometries.push(newGeometrie);
  22944. };
  22945. Scene.prototype.addLensFlareSystem = function (newLensFlareSystem) {
  22946. this.lensFlareSystems.push(newLensFlareSystem);
  22947. };
  22948. Scene.prototype.addActionManager = function (newActionManager) {
  22949. this._actionManagers.push(newActionManager);
  22950. };
  22951. /**
  22952. * Switch active camera
  22953. * @param {Camera} newCamera - new active camera
  22954. * @param {boolean} attachControl - call attachControl for the new active camera (default: true)
  22955. */
  22956. Scene.prototype.switchActiveCamera = function (newCamera, attachControl) {
  22957. if (attachControl === void 0) { attachControl = true; }
  22958. var canvas = this._engine.getRenderingCanvas();
  22959. if (!canvas) {
  22960. return;
  22961. }
  22962. if (this.activeCamera) {
  22963. this.activeCamera.detachControl(canvas);
  22964. }
  22965. this.activeCamera = newCamera;
  22966. if (attachControl) {
  22967. newCamera.attachControl(canvas);
  22968. }
  22969. };
  22970. /**
  22971. * sets the active camera of the scene using its ID
  22972. * @param {string} id - the camera's ID
  22973. * @return {BABYLON.Camera|null} the new active camera or null if none found.
  22974. * @see activeCamera
  22975. */
  22976. Scene.prototype.setActiveCameraByID = function (id) {
  22977. var camera = this.getCameraByID(id);
  22978. if (camera) {
  22979. this.activeCamera = camera;
  22980. return camera;
  22981. }
  22982. return null;
  22983. };
  22984. /**
  22985. * sets the active camera of the scene using its name
  22986. * @param {string} name - the camera's name
  22987. * @return {BABYLON.Camera|null} the new active camera or null if none found.
  22988. * @see activeCamera
  22989. */
  22990. Scene.prototype.setActiveCameraByName = function (name) {
  22991. var camera = this.getCameraByName(name);
  22992. if (camera) {
  22993. this.activeCamera = camera;
  22994. return camera;
  22995. }
  22996. return null;
  22997. };
  22998. /**
  22999. * get an animation group using its name
  23000. * @param {string} the material's name
  23001. * @return {BABYLON.AnimationGroup|null} the animation group or null if none found.
  23002. */
  23003. Scene.prototype.getAnimationGroupByName = function (name) {
  23004. for (var index = 0; index < this.animationGroups.length; index++) {
  23005. if (this.animationGroups[index].name === name) {
  23006. return this.animationGroups[index];
  23007. }
  23008. }
  23009. return null;
  23010. };
  23011. /**
  23012. * get a material using its id
  23013. * @param {string} the material's ID
  23014. * @return {BABYLON.Material|null} the material or null if none found.
  23015. */
  23016. Scene.prototype.getMaterialByID = function (id) {
  23017. for (var index = 0; index < this.materials.length; index++) {
  23018. if (this.materials[index].id === id) {
  23019. return this.materials[index];
  23020. }
  23021. }
  23022. return null;
  23023. };
  23024. /**
  23025. * get a material using its name
  23026. * @param {string} the material's name
  23027. * @return {BABYLON.Material|null} the material or null if none found.
  23028. */
  23029. Scene.prototype.getMaterialByName = function (name) {
  23030. for (var index = 0; index < this.materials.length; index++) {
  23031. if (this.materials[index].name === name) {
  23032. return this.materials[index];
  23033. }
  23034. }
  23035. return null;
  23036. };
  23037. Scene.prototype.getLensFlareSystemByName = function (name) {
  23038. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  23039. if (this.lensFlareSystems[index].name === name) {
  23040. return this.lensFlareSystems[index];
  23041. }
  23042. }
  23043. return null;
  23044. };
  23045. Scene.prototype.getLensFlareSystemByID = function (id) {
  23046. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  23047. if (this.lensFlareSystems[index].id === id) {
  23048. return this.lensFlareSystems[index];
  23049. }
  23050. }
  23051. return null;
  23052. };
  23053. Scene.prototype.getCameraByID = function (id) {
  23054. for (var index = 0; index < this.cameras.length; index++) {
  23055. if (this.cameras[index].id === id) {
  23056. return this.cameras[index];
  23057. }
  23058. }
  23059. return null;
  23060. };
  23061. Scene.prototype.getCameraByUniqueID = function (uniqueId) {
  23062. for (var index = 0; index < this.cameras.length; index++) {
  23063. if (this.cameras[index].uniqueId === uniqueId) {
  23064. return this.cameras[index];
  23065. }
  23066. }
  23067. return null;
  23068. };
  23069. /**
  23070. * get a camera using its name
  23071. * @param {string} the camera's name
  23072. * @return {BABYLON.Camera|null} the camera or null if none found.
  23073. */
  23074. Scene.prototype.getCameraByName = function (name) {
  23075. for (var index = 0; index < this.cameras.length; index++) {
  23076. if (this.cameras[index].name === name) {
  23077. return this.cameras[index];
  23078. }
  23079. }
  23080. return null;
  23081. };
  23082. /**
  23083. * get a bone using its id
  23084. * @param {string} the bone's id
  23085. * @return {BABYLON.Bone|null} the bone or null if not found
  23086. */
  23087. Scene.prototype.getBoneByID = function (id) {
  23088. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  23089. var skeleton = this.skeletons[skeletonIndex];
  23090. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  23091. if (skeleton.bones[boneIndex].id === id) {
  23092. return skeleton.bones[boneIndex];
  23093. }
  23094. }
  23095. }
  23096. return null;
  23097. };
  23098. /**
  23099. * get a bone using its id
  23100. * @param {string} the bone's name
  23101. * @return {BABYLON.Bone|null} the bone or null if not found
  23102. */
  23103. Scene.prototype.getBoneByName = function (name) {
  23104. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  23105. var skeleton = this.skeletons[skeletonIndex];
  23106. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  23107. if (skeleton.bones[boneIndex].name === name) {
  23108. return skeleton.bones[boneIndex];
  23109. }
  23110. }
  23111. }
  23112. return null;
  23113. };
  23114. /**
  23115. * get a light node using its name
  23116. * @param {string} the light's name
  23117. * @return {BABYLON.Light|null} the light or null if none found.
  23118. */
  23119. Scene.prototype.getLightByName = function (name) {
  23120. for (var index = 0; index < this.lights.length; index++) {
  23121. if (this.lights[index].name === name) {
  23122. return this.lights[index];
  23123. }
  23124. }
  23125. return null;
  23126. };
  23127. /**
  23128. * get a light node using its ID
  23129. * @param {string} the light's id
  23130. * @return {BABYLON.Light|null} the light or null if none found.
  23131. */
  23132. Scene.prototype.getLightByID = function (id) {
  23133. for (var index = 0; index < this.lights.length; index++) {
  23134. if (this.lights[index].id === id) {
  23135. return this.lights[index];
  23136. }
  23137. }
  23138. return null;
  23139. };
  23140. /**
  23141. * get a light node using its scene-generated unique ID
  23142. * @param {number} the light's unique id
  23143. * @return {BABYLON.Light|null} the light or null if none found.
  23144. */
  23145. Scene.prototype.getLightByUniqueID = function (uniqueId) {
  23146. for (var index = 0; index < this.lights.length; index++) {
  23147. if (this.lights[index].uniqueId === uniqueId) {
  23148. return this.lights[index];
  23149. }
  23150. }
  23151. return null;
  23152. };
  23153. /**
  23154. * get a particle system by id
  23155. * @param id {number} the particle system id
  23156. * @return {BABYLON.IParticleSystem|null} the corresponding system or null if none found.
  23157. */
  23158. Scene.prototype.getParticleSystemByID = function (id) {
  23159. for (var index = 0; index < this.particleSystems.length; index++) {
  23160. if (this.particleSystems[index].id === id) {
  23161. return this.particleSystems[index];
  23162. }
  23163. }
  23164. return null;
  23165. };
  23166. /**
  23167. * get a geometry using its ID
  23168. * @param {string} the geometry's id
  23169. * @return {BABYLON.Geometry|null} the geometry or null if none found.
  23170. */
  23171. Scene.prototype.getGeometryByID = function (id) {
  23172. for (var index = 0; index < this._geometries.length; index++) {
  23173. if (this._geometries[index].id === id) {
  23174. return this._geometries[index];
  23175. }
  23176. }
  23177. return null;
  23178. };
  23179. /**
  23180. * add a new geometry to this scene.
  23181. * @param {BABYLON.Geometry} geometry - the geometry to be added to the scene.
  23182. * @param {boolean} [force] - force addition, even if a geometry with this ID already exists
  23183. * @return {boolean} was the geometry added or not
  23184. */
  23185. Scene.prototype.pushGeometry = function (geometry, force) {
  23186. if (!force && this.getGeometryByID(geometry.id)) {
  23187. return false;
  23188. }
  23189. this._geometries.push(geometry);
  23190. //notify the collision coordinator
  23191. if (this.collisionCoordinator) {
  23192. this.collisionCoordinator.onGeometryAdded(geometry);
  23193. }
  23194. this.onNewGeometryAddedObservable.notifyObservers(geometry);
  23195. return true;
  23196. };
  23197. /**
  23198. * Removes an existing geometry
  23199. * @param {BABYLON.Geometry} geometry - the geometry to be removed from the scene.
  23200. * @return {boolean} was the geometry removed or not
  23201. */
  23202. Scene.prototype.removeGeometry = function (geometry) {
  23203. var index = this._geometries.indexOf(geometry);
  23204. if (index > -1) {
  23205. this._geometries.splice(index, 1);
  23206. //notify the collision coordinator
  23207. if (this.collisionCoordinator) {
  23208. this.collisionCoordinator.onGeometryDeleted(geometry);
  23209. }
  23210. this.onGeometryRemovedObservable.notifyObservers(geometry);
  23211. return true;
  23212. }
  23213. return false;
  23214. };
  23215. Scene.prototype.getGeometries = function () {
  23216. return this._geometries;
  23217. };
  23218. /**
  23219. * Get the first added mesh found of a given ID
  23220. * @param {string} id - the id to search for
  23221. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  23222. */
  23223. Scene.prototype.getMeshByID = function (id) {
  23224. for (var index = 0; index < this.meshes.length; index++) {
  23225. if (this.meshes[index].id === id) {
  23226. return this.meshes[index];
  23227. }
  23228. }
  23229. return null;
  23230. };
  23231. Scene.prototype.getMeshesByID = function (id) {
  23232. return this.meshes.filter(function (m) {
  23233. return m.id === id;
  23234. });
  23235. };
  23236. /**
  23237. * Get the first added transform node found of a given ID
  23238. * @param {string} id - the id to search for
  23239. * @return {BABYLON.TransformNode|null} the transform node found or null if not found at all.
  23240. */
  23241. Scene.prototype.getTransformNodeByID = function (id) {
  23242. for (var index = 0; index < this.transformNodes.length; index++) {
  23243. if (this.transformNodes[index].id === id) {
  23244. return this.transformNodes[index];
  23245. }
  23246. }
  23247. return null;
  23248. };
  23249. Scene.prototype.getTransformNodesByID = function (id) {
  23250. return this.transformNodes.filter(function (m) {
  23251. return m.id === id;
  23252. });
  23253. };
  23254. /**
  23255. * Get a mesh with its auto-generated unique id
  23256. * @param {number} uniqueId - the unique id to search for
  23257. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  23258. */
  23259. Scene.prototype.getMeshByUniqueID = function (uniqueId) {
  23260. for (var index = 0; index < this.meshes.length; index++) {
  23261. if (this.meshes[index].uniqueId === uniqueId) {
  23262. return this.meshes[index];
  23263. }
  23264. }
  23265. return null;
  23266. };
  23267. /**
  23268. * Get a the last added mesh found of a given ID
  23269. * @param {string} id - the id to search for
  23270. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  23271. */
  23272. Scene.prototype.getLastMeshByID = function (id) {
  23273. for (var index = this.meshes.length - 1; index >= 0; index--) {
  23274. if (this.meshes[index].id === id) {
  23275. return this.meshes[index];
  23276. }
  23277. }
  23278. return null;
  23279. };
  23280. /**
  23281. * Get a the last added node (Mesh, Camera, Light) found of a given ID
  23282. * @param {string} id - the id to search for
  23283. * @return {BABYLON.Node|null} the node found or null if not found at all.
  23284. */
  23285. Scene.prototype.getLastEntryByID = function (id) {
  23286. var index;
  23287. for (index = this.meshes.length - 1; index >= 0; index--) {
  23288. if (this.meshes[index].id === id) {
  23289. return this.meshes[index];
  23290. }
  23291. }
  23292. for (index = this.transformNodes.length - 1; index >= 0; index--) {
  23293. if (this.transformNodes[index].id === id) {
  23294. return this.transformNodes[index];
  23295. }
  23296. }
  23297. for (index = this.cameras.length - 1; index >= 0; index--) {
  23298. if (this.cameras[index].id === id) {
  23299. return this.cameras[index];
  23300. }
  23301. }
  23302. for (index = this.lights.length - 1; index >= 0; index--) {
  23303. if (this.lights[index].id === id) {
  23304. return this.lights[index];
  23305. }
  23306. }
  23307. return null;
  23308. };
  23309. Scene.prototype.getNodeByID = function (id) {
  23310. var mesh = this.getMeshByID(id);
  23311. if (mesh) {
  23312. return mesh;
  23313. }
  23314. var light = this.getLightByID(id);
  23315. if (light) {
  23316. return light;
  23317. }
  23318. var camera = this.getCameraByID(id);
  23319. if (camera) {
  23320. return camera;
  23321. }
  23322. var bone = this.getBoneByID(id);
  23323. return bone;
  23324. };
  23325. Scene.prototype.getNodeByName = function (name) {
  23326. var mesh = this.getMeshByName(name);
  23327. if (mesh) {
  23328. return mesh;
  23329. }
  23330. var light = this.getLightByName(name);
  23331. if (light) {
  23332. return light;
  23333. }
  23334. var camera = this.getCameraByName(name);
  23335. if (camera) {
  23336. return camera;
  23337. }
  23338. var bone = this.getBoneByName(name);
  23339. return bone;
  23340. };
  23341. Scene.prototype.getMeshByName = function (name) {
  23342. for (var index = 0; index < this.meshes.length; index++) {
  23343. if (this.meshes[index].name === name) {
  23344. return this.meshes[index];
  23345. }
  23346. }
  23347. return null;
  23348. };
  23349. Scene.prototype.getTransformNodeByName = function (name) {
  23350. for (var index = 0; index < this.transformNodes.length; index++) {
  23351. if (this.transformNodes[index].name === name) {
  23352. return this.transformNodes[index];
  23353. }
  23354. }
  23355. return null;
  23356. };
  23357. Scene.prototype.getSoundByName = function (name) {
  23358. var index;
  23359. if (BABYLON.AudioEngine) {
  23360. for (index = 0; index < this.mainSoundTrack.soundCollection.length; index++) {
  23361. if (this.mainSoundTrack.soundCollection[index].name === name) {
  23362. return this.mainSoundTrack.soundCollection[index];
  23363. }
  23364. }
  23365. for (var sdIndex = 0; sdIndex < this.soundTracks.length; sdIndex++) {
  23366. for (index = 0; index < this.soundTracks[sdIndex].soundCollection.length; index++) {
  23367. if (this.soundTracks[sdIndex].soundCollection[index].name === name) {
  23368. return this.soundTracks[sdIndex].soundCollection[index];
  23369. }
  23370. }
  23371. }
  23372. }
  23373. return null;
  23374. };
  23375. Scene.prototype.getLastSkeletonByID = function (id) {
  23376. for (var index = this.skeletons.length - 1; index >= 0; index--) {
  23377. if (this.skeletons[index].id === id) {
  23378. return this.skeletons[index];
  23379. }
  23380. }
  23381. return null;
  23382. };
  23383. Scene.prototype.getSkeletonById = function (id) {
  23384. for (var index = 0; index < this.skeletons.length; index++) {
  23385. if (this.skeletons[index].id === id) {
  23386. return this.skeletons[index];
  23387. }
  23388. }
  23389. return null;
  23390. };
  23391. Scene.prototype.getSkeletonByName = function (name) {
  23392. for (var index = 0; index < this.skeletons.length; index++) {
  23393. if (this.skeletons[index].name === name) {
  23394. return this.skeletons[index];
  23395. }
  23396. }
  23397. return null;
  23398. };
  23399. Scene.prototype.getMorphTargetManagerById = function (id) {
  23400. for (var index = 0; index < this.morphTargetManagers.length; index++) {
  23401. if (this.morphTargetManagers[index].uniqueId === id) {
  23402. return this.morphTargetManagers[index];
  23403. }
  23404. }
  23405. return null;
  23406. };
  23407. Scene.prototype.isActiveMesh = function (mesh) {
  23408. return (this._activeMeshes.indexOf(mesh) !== -1);
  23409. };
  23410. /**
  23411. * Return a the first highlight layer of the scene with a given name.
  23412. * @param name The name of the highlight layer to look for.
  23413. * @return The highlight layer if found otherwise null.
  23414. */
  23415. Scene.prototype.getHighlightLayerByName = function (name) {
  23416. for (var index = 0; index < this.effectLayers.length; index++) {
  23417. if (this.effectLayers[index].name === name && this.effectLayers[index].getEffectName() === BABYLON.HighlightLayer.EffectName) {
  23418. return this.effectLayers[index];
  23419. }
  23420. }
  23421. return null;
  23422. };
  23423. /**
  23424. * Return a the first highlight layer of the scene with a given name.
  23425. * @param name The name of the highlight layer to look for.
  23426. * @return The highlight layer if found otherwise null.
  23427. */
  23428. Scene.prototype.getGlowLayerByName = function (name) {
  23429. for (var index = 0; index < this.effectLayers.length; index++) {
  23430. if (this.effectLayers[index].name === name && this.effectLayers[index].getEffectName() === BABYLON.GlowLayer.EffectName) {
  23431. return this.effectLayers[index];
  23432. }
  23433. }
  23434. return null;
  23435. };
  23436. Object.defineProperty(Scene.prototype, "uid", {
  23437. /**
  23438. * Return a unique id as a string which can serve as an identifier for the scene
  23439. */
  23440. get: function () {
  23441. if (!this._uid) {
  23442. this._uid = BABYLON.Tools.RandomId();
  23443. }
  23444. return this._uid;
  23445. },
  23446. enumerable: true,
  23447. configurable: true
  23448. });
  23449. /**
  23450. * Add an externaly attached data from its key.
  23451. * This method call will fail and return false, if such key already exists.
  23452. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  23453. * @param key the unique key that identifies the data
  23454. * @param data the data object to associate to the key for this Engine instance
  23455. * @return true if no such key were already present and the data was added successfully, false otherwise
  23456. */
  23457. Scene.prototype.addExternalData = function (key, data) {
  23458. if (!this._externalData) {
  23459. this._externalData = new BABYLON.StringDictionary();
  23460. }
  23461. return this._externalData.add(key, data);
  23462. };
  23463. /**
  23464. * Get an externaly attached data from its key
  23465. * @param key the unique key that identifies the data
  23466. * @return the associated data, if present (can be null), or undefined if not present
  23467. */
  23468. Scene.prototype.getExternalData = function (key) {
  23469. if (!this._externalData) {
  23470. return null;
  23471. }
  23472. return this._externalData.get(key);
  23473. };
  23474. /**
  23475. * Get an externaly attached data from its key, create it using a factory if it's not already present
  23476. * @param key the unique key that identifies the data
  23477. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  23478. * @return the associated data, can be null if the factory returned null.
  23479. */
  23480. Scene.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  23481. if (!this._externalData) {
  23482. this._externalData = new BABYLON.StringDictionary();
  23483. }
  23484. return this._externalData.getOrAddWithFactory(key, factory);
  23485. };
  23486. /**
  23487. * Remove an externaly attached data from the Engine instance
  23488. * @param key the unique key that identifies the data
  23489. * @return true if the data was successfully removed, false if it doesn't exist
  23490. */
  23491. Scene.prototype.removeExternalData = function (key) {
  23492. return this._externalData.remove(key);
  23493. };
  23494. Scene.prototype._evaluateSubMesh = function (subMesh, mesh) {
  23495. if (this.dispatchAllSubMeshesOfActiveMeshes || mesh.alwaysSelectAsActiveMesh || mesh.subMeshes.length === 1 || subMesh.isInFrustum(this._frustumPlanes)) {
  23496. if (mesh.showSubMeshesBoundingBox) {
  23497. var boundingInfo = subMesh.getBoundingInfo();
  23498. if (boundingInfo !== null && boundingInfo !== undefined) {
  23499. this.getBoundingBoxRenderer().renderList.push(boundingInfo.boundingBox);
  23500. }
  23501. }
  23502. var material = subMesh.getMaterial();
  23503. if (material !== null && material !== undefined) {
  23504. // Render targets
  23505. if (material.getRenderTargetTextures !== undefined) {
  23506. if (this._processedMaterials.indexOf(material) === -1) {
  23507. this._processedMaterials.push(material);
  23508. this._renderTargets.concatWithNoDuplicate(material.getRenderTargetTextures());
  23509. }
  23510. }
  23511. // Dispatch
  23512. this._activeIndices.addCount(subMesh.indexCount, false);
  23513. this._renderingManager.dispatch(subMesh, mesh, material);
  23514. }
  23515. }
  23516. };
  23517. Scene.prototype._isInIntermediateRendering = function () {
  23518. return this._intermediateRendering;
  23519. };
  23520. Scene.prototype.setActiveMeshCandidateProvider = function (provider) {
  23521. this._activeMeshCandidateProvider = provider;
  23522. };
  23523. Scene.prototype.getActiveMeshCandidateProvider = function () {
  23524. return this._activeMeshCandidateProvider;
  23525. };
  23526. /**
  23527. * Use this function to stop evaluating active meshes. The current list will be keep alive between frames
  23528. */
  23529. Scene.prototype.freezeActiveMeshes = function () {
  23530. this._evaluateActiveMeshes();
  23531. this._activeMeshesFrozen = true;
  23532. return this;
  23533. };
  23534. /**
  23535. * Use this function to restart evaluating active meshes on every frame
  23536. */
  23537. Scene.prototype.unfreezeActiveMeshes = function () {
  23538. this._activeMeshesFrozen = false;
  23539. return this;
  23540. };
  23541. Scene.prototype._evaluateActiveMeshes = function () {
  23542. if (this._activeMeshesFrozen && this._activeMeshes.length) {
  23543. return;
  23544. }
  23545. if (!this.activeCamera) {
  23546. return;
  23547. }
  23548. this.onBeforeActiveMeshesEvaluationObservable.notifyObservers(this);
  23549. this.activeCamera._activeMeshes.reset();
  23550. this._activeMeshes.reset();
  23551. this._renderingManager.reset();
  23552. this._processedMaterials.reset();
  23553. this._activeParticleSystems.reset();
  23554. this._activeSkeletons.reset();
  23555. this._softwareSkinnedMeshes.reset();
  23556. if (this._boundingBoxRenderer) {
  23557. this._boundingBoxRenderer.reset();
  23558. }
  23559. // Meshes
  23560. var meshes;
  23561. var len;
  23562. var checkIsEnabled = true;
  23563. // Determine mesh candidates
  23564. if (this._activeMeshCandidateProvider !== undefined) {
  23565. // Use _activeMeshCandidateProvider
  23566. meshes = this._activeMeshCandidateProvider.getMeshes(this);
  23567. checkIsEnabled = this._activeMeshCandidateProvider.checksIsEnabled === false;
  23568. if (meshes !== undefined) {
  23569. len = meshes.length;
  23570. }
  23571. else {
  23572. len = 0;
  23573. }
  23574. }
  23575. else if (this._selectionOctree !== undefined) {
  23576. // Octree
  23577. var selection = this._selectionOctree.select(this._frustumPlanes);
  23578. meshes = selection.data;
  23579. len = selection.length;
  23580. }
  23581. else {
  23582. // Full scene traversal
  23583. len = this.meshes.length;
  23584. meshes = this.meshes;
  23585. }
  23586. // Check each mesh
  23587. for (var meshIndex = 0, mesh, meshLOD; meshIndex < len; meshIndex++) {
  23588. mesh = meshes[meshIndex];
  23589. if (mesh.isBlocked) {
  23590. continue;
  23591. }
  23592. this._totalVertices.addCount(mesh.getTotalVertices(), false);
  23593. if (!mesh.isReady() || (checkIsEnabled && !mesh.isEnabled())) {
  23594. continue;
  23595. }
  23596. mesh.computeWorldMatrix();
  23597. // Intersections
  23598. if (mesh.actionManager && mesh.actionManager.hasSpecificTriggers([BABYLON.ActionManager.OnIntersectionEnterTrigger, BABYLON.ActionManager.OnIntersectionExitTrigger])) {
  23599. this._meshesForIntersections.pushNoDuplicate(mesh);
  23600. }
  23601. // Switch to current LOD
  23602. meshLOD = mesh.getLOD(this.activeCamera);
  23603. if (meshLOD === undefined || meshLOD === null) {
  23604. continue;
  23605. }
  23606. mesh._preActivate();
  23607. if (mesh.alwaysSelectAsActiveMesh || mesh.isVisible && mesh.visibility > 0 && ((mesh.layerMask & this.activeCamera.layerMask) !== 0) && mesh.isInFrustum(this._frustumPlanes)) {
  23608. this._activeMeshes.push(mesh);
  23609. this.activeCamera._activeMeshes.push(mesh);
  23610. mesh._activate(this._renderId);
  23611. if (meshLOD !== mesh) {
  23612. meshLOD._activate(this._renderId);
  23613. }
  23614. this._activeMesh(mesh, meshLOD);
  23615. }
  23616. }
  23617. this.onAfterActiveMeshesEvaluationObservable.notifyObservers(this);
  23618. // Particle systems
  23619. if (this.particlesEnabled) {
  23620. this.onBeforeParticlesRenderingObservable.notifyObservers(this);
  23621. for (var particleIndex = 0; particleIndex < this.particleSystems.length; particleIndex++) {
  23622. var particleSystem = this.particleSystems[particleIndex];
  23623. if (!particleSystem.isStarted() || !particleSystem.emitter) {
  23624. continue;
  23625. }
  23626. var emitter = particleSystem.emitter;
  23627. if (!emitter.position || emitter.isEnabled()) {
  23628. this._activeParticleSystems.push(particleSystem);
  23629. particleSystem.animate();
  23630. this._renderingManager.dispatchParticles(particleSystem);
  23631. }
  23632. }
  23633. this.onAfterParticlesRenderingObservable.notifyObservers(this);
  23634. }
  23635. };
  23636. Scene.prototype._activeMesh = function (sourceMesh, mesh) {
  23637. if (this.skeletonsEnabled && mesh.skeleton !== null && mesh.skeleton !== undefined) {
  23638. if (this._activeSkeletons.pushNoDuplicate(mesh.skeleton)) {
  23639. mesh.skeleton.prepare();
  23640. }
  23641. if (!mesh.computeBonesUsingShaders) {
  23642. this._softwareSkinnedMeshes.pushNoDuplicate(mesh);
  23643. }
  23644. }
  23645. if (sourceMesh.showBoundingBox || this.forceShowBoundingBoxes) {
  23646. var boundingInfo = sourceMesh.getBoundingInfo();
  23647. this.getBoundingBoxRenderer().renderList.push(boundingInfo.boundingBox);
  23648. }
  23649. if (mesh !== undefined && mesh !== null
  23650. && mesh.subMeshes !== undefined && mesh.subMeshes !== null && mesh.subMeshes.length > 0) {
  23651. // Submeshes Octrees
  23652. var len;
  23653. var subMeshes;
  23654. if (mesh.useOctreeForRenderingSelection && mesh._submeshesOctree !== undefined && mesh._submeshesOctree !== null) {
  23655. var intersections = mesh._submeshesOctree.select(this._frustumPlanes);
  23656. len = intersections.length;
  23657. subMeshes = intersections.data;
  23658. }
  23659. else {
  23660. subMeshes = mesh.subMeshes;
  23661. len = subMeshes.length;
  23662. }
  23663. for (var subIndex = 0, subMesh; subIndex < len; subIndex++) {
  23664. subMesh = subMeshes[subIndex];
  23665. this._evaluateSubMesh(subMesh, mesh);
  23666. }
  23667. }
  23668. };
  23669. Scene.prototype.updateTransformMatrix = function (force) {
  23670. if (!this.activeCamera) {
  23671. return;
  23672. }
  23673. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(force));
  23674. };
  23675. Scene.prototype.updateAlternateTransformMatrix = function (alternateCamera) {
  23676. this._setAlternateTransformMatrix(alternateCamera.getViewMatrix(), alternateCamera.getProjectionMatrix());
  23677. };
  23678. Scene.prototype._renderForCamera = function (camera) {
  23679. if (camera && camera._skipRendering) {
  23680. return;
  23681. }
  23682. var engine = this._engine;
  23683. this.activeCamera = camera;
  23684. if (!this.activeCamera)
  23685. throw new Error("Active camera not set");
  23686. BABYLON.Tools.StartPerformanceCounter("Rendering camera " + this.activeCamera.name);
  23687. // Viewport
  23688. engine.setViewport(this.activeCamera.viewport);
  23689. // Camera
  23690. this.resetCachedMaterial();
  23691. this._renderId++;
  23692. this.activeCamera.update();
  23693. this.updateTransformMatrix();
  23694. if (camera._alternateCamera) {
  23695. this.updateAlternateTransformMatrix(camera._alternateCamera);
  23696. this._alternateRendering = true;
  23697. }
  23698. this.onBeforeCameraRenderObservable.notifyObservers(this.activeCamera);
  23699. // Meshes
  23700. this._evaluateActiveMeshes();
  23701. // Software skinning
  23702. for (var softwareSkinnedMeshIndex = 0; softwareSkinnedMeshIndex < this._softwareSkinnedMeshes.length; softwareSkinnedMeshIndex++) {
  23703. var mesh = this._softwareSkinnedMeshes.data[softwareSkinnedMeshIndex];
  23704. mesh.applySkeleton(mesh.skeleton);
  23705. }
  23706. // Render targets
  23707. this.OnBeforeRenderTargetsRenderObservable.notifyObservers(this);
  23708. var needsRestoreFrameBuffer = false;
  23709. if (camera.customRenderTargets && camera.customRenderTargets.length > 0) {
  23710. this._renderTargets.concatWithNoDuplicate(camera.customRenderTargets);
  23711. }
  23712. if (this.renderTargetsEnabled && this._renderTargets.length > 0) {
  23713. this._intermediateRendering = true;
  23714. BABYLON.Tools.StartPerformanceCounter("Render targets", this._renderTargets.length > 0);
  23715. for (var renderIndex = 0; renderIndex < this._renderTargets.length; renderIndex++) {
  23716. var renderTarget = this._renderTargets.data[renderIndex];
  23717. if (renderTarget._shouldRender()) {
  23718. this._renderId++;
  23719. var hasSpecialRenderTargetCamera = renderTarget.activeCamera && renderTarget.activeCamera !== this.activeCamera;
  23720. renderTarget.render(hasSpecialRenderTargetCamera, this.dumpNextRenderTargets);
  23721. }
  23722. }
  23723. BABYLON.Tools.EndPerformanceCounter("Render targets", this._renderTargets.length > 0);
  23724. this._intermediateRendering = false;
  23725. this._renderId++;
  23726. needsRestoreFrameBuffer = true; // Restore back buffer
  23727. }
  23728. // Render EffecttLayer Texture
  23729. var stencilState = this._engine.getStencilBuffer();
  23730. var renderEffects = false;
  23731. var needStencil = false;
  23732. if (this.renderTargetsEnabled && this.effectLayers && this.effectLayers.length > 0) {
  23733. this._intermediateRendering = true;
  23734. for (var i = 0; i < this.effectLayers.length; i++) {
  23735. var effectLayer = this.effectLayers[i];
  23736. if (effectLayer.shouldRender() &&
  23737. (!effectLayer.camera ||
  23738. (effectLayer.camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE && camera === effectLayer.camera) ||
  23739. (effectLayer.camera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE && effectLayer.camera._rigCameras.indexOf(camera) > -1))) {
  23740. renderEffects = true;
  23741. needStencil = needStencil || effectLayer.needStencil();
  23742. var renderTarget = effectLayer._mainTexture;
  23743. if (renderTarget._shouldRender()) {
  23744. this._renderId++;
  23745. renderTarget.render(false, false);
  23746. needsRestoreFrameBuffer = true;
  23747. }
  23748. }
  23749. }
  23750. this._intermediateRendering = false;
  23751. this._renderId++;
  23752. }
  23753. if (needsRestoreFrameBuffer) {
  23754. engine.restoreDefaultFramebuffer(); // Restore back buffer
  23755. }
  23756. this.OnAfterRenderTargetsRenderObservable.notifyObservers(this);
  23757. // Prepare Frame
  23758. this.postProcessManager._prepareFrame();
  23759. // Backgrounds
  23760. var layerIndex;
  23761. var layer;
  23762. if (this.layers.length) {
  23763. engine.setDepthBuffer(false);
  23764. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  23765. layer = this.layers[layerIndex];
  23766. if (layer.isBackground && ((layer.layerMask & this.activeCamera.layerMask) !== 0)) {
  23767. layer.render();
  23768. }
  23769. }
  23770. engine.setDepthBuffer(true);
  23771. }
  23772. // Activate effect Layer stencil
  23773. if (needStencil) {
  23774. this._engine.setStencilBuffer(true);
  23775. }
  23776. // Render
  23777. this.onBeforeDrawPhaseObservable.notifyObservers(this);
  23778. this._renderingManager.render(null, null, true, true);
  23779. this.onAfterDrawPhaseObservable.notifyObservers(this);
  23780. // Restore effect Layer stencil
  23781. if (needStencil) {
  23782. this._engine.setStencilBuffer(stencilState);
  23783. }
  23784. // Bounding boxes
  23785. if (this._boundingBoxRenderer) {
  23786. this._boundingBoxRenderer.render();
  23787. }
  23788. // Lens flares
  23789. if (this.lensFlaresEnabled) {
  23790. BABYLON.Tools.StartPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  23791. for (var lensFlareSystemIndex = 0; lensFlareSystemIndex < this.lensFlareSystems.length; lensFlareSystemIndex++) {
  23792. var lensFlareSystem = this.lensFlareSystems[lensFlareSystemIndex];
  23793. if ((camera.layerMask & lensFlareSystem.layerMask) !== 0) {
  23794. lensFlareSystem.render();
  23795. }
  23796. }
  23797. BABYLON.Tools.EndPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  23798. }
  23799. // Foregrounds
  23800. if (this.layers.length) {
  23801. engine.setDepthBuffer(false);
  23802. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  23803. layer = this.layers[layerIndex];
  23804. if (!layer.isBackground && ((layer.layerMask & this.activeCamera.layerMask) !== 0)) {
  23805. layer.render();
  23806. }
  23807. }
  23808. engine.setDepthBuffer(true);
  23809. }
  23810. // Effect Layer
  23811. if (renderEffects) {
  23812. engine.setDepthBuffer(false);
  23813. for (var i = 0; i < this.effectLayers.length; i++) {
  23814. if (this.effectLayers[i].shouldRender()) {
  23815. this.effectLayers[i].render();
  23816. }
  23817. }
  23818. engine.setDepthBuffer(true);
  23819. }
  23820. // Finalize frame
  23821. this.postProcessManager._finalizeFrame(camera.isIntermediate);
  23822. // Reset some special arrays
  23823. this._renderTargets.reset();
  23824. this._alternateRendering = false;
  23825. this.onAfterCameraRenderObservable.notifyObservers(this.activeCamera);
  23826. BABYLON.Tools.EndPerformanceCounter("Rendering camera " + this.activeCamera.name);
  23827. };
  23828. Scene.prototype._processSubCameras = function (camera) {
  23829. if (camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE) {
  23830. this._renderForCamera(camera);
  23831. return;
  23832. }
  23833. // Update camera
  23834. if (this.activeCamera) {
  23835. this.activeCamera.update();
  23836. }
  23837. // rig cameras
  23838. for (var index = 0; index < camera._rigCameras.length; index++) {
  23839. this._renderForCamera(camera._rigCameras[index]);
  23840. }
  23841. this.activeCamera = camera;
  23842. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  23843. };
  23844. Scene.prototype._checkIntersections = function () {
  23845. for (var index = 0; index < this._meshesForIntersections.length; index++) {
  23846. var sourceMesh = this._meshesForIntersections.data[index];
  23847. if (!sourceMesh.actionManager) {
  23848. continue;
  23849. }
  23850. for (var actionIndex = 0; actionIndex < sourceMesh.actionManager.actions.length; actionIndex++) {
  23851. var action = sourceMesh.actionManager.actions[actionIndex];
  23852. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  23853. var parameters = action.getTriggerParameter();
  23854. var otherMesh = parameters instanceof BABYLON.AbstractMesh ? parameters : parameters.mesh;
  23855. var areIntersecting = otherMesh.intersectsMesh(sourceMesh, parameters.usePreciseIntersection);
  23856. var currentIntersectionInProgress = sourceMesh._intersectionsInProgress.indexOf(otherMesh);
  23857. if (areIntersecting && currentIntersectionInProgress === -1) {
  23858. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger) {
  23859. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, undefined, otherMesh));
  23860. sourceMesh._intersectionsInProgress.push(otherMesh);
  23861. }
  23862. else if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  23863. sourceMesh._intersectionsInProgress.push(otherMesh);
  23864. }
  23865. }
  23866. else if (!areIntersecting && currentIntersectionInProgress > -1) {
  23867. //They intersected, and now they don't.
  23868. //is this trigger an exit trigger? execute an event.
  23869. if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  23870. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, undefined, otherMesh));
  23871. }
  23872. //if this is an exit trigger, or no exit trigger exists, remove the id from the intersection in progress array.
  23873. if (!sourceMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnIntersectionExitTrigger) || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  23874. sourceMesh._intersectionsInProgress.splice(currentIntersectionInProgress, 1);
  23875. }
  23876. }
  23877. }
  23878. }
  23879. }
  23880. };
  23881. Scene.prototype.render = function () {
  23882. if (this.isDisposed) {
  23883. return;
  23884. }
  23885. this._activeParticles.fetchNewFrame();
  23886. this._totalVertices.fetchNewFrame();
  23887. this._activeIndices.fetchNewFrame();
  23888. this._activeBones.fetchNewFrame();
  23889. this._meshesForIntersections.reset();
  23890. this.resetCachedMaterial();
  23891. this.onBeforeAnimationsObservable.notifyObservers(this);
  23892. // Actions
  23893. if (this.actionManager) {
  23894. this.actionManager.processTrigger(BABYLON.ActionManager.OnEveryFrameTrigger);
  23895. }
  23896. //Simplification Queue
  23897. if (this.simplificationQueue && !this.simplificationQueue.running) {
  23898. this.simplificationQueue.executeNext();
  23899. }
  23900. if (this._engine.isDeterministicLockStep()) {
  23901. var deltaTime = Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime)) + this._timeAccumulator;
  23902. var defaultFPS = (60.0 / 1000.0);
  23903. var defaultFrameTime = 1000 / 60; // frame time in MS
  23904. if (this._physicsEngine) {
  23905. defaultFrameTime = this._physicsEngine.getTimeStep() * 1000;
  23906. }
  23907. var stepsTaken = 0;
  23908. var maxSubSteps = this._engine.getLockstepMaxSteps();
  23909. var internalSteps = Math.floor(deltaTime / (1000 * defaultFPS));
  23910. internalSteps = Math.min(internalSteps, maxSubSteps);
  23911. do {
  23912. this.onBeforeStepObservable.notifyObservers(this);
  23913. // Animations
  23914. this._animationRatio = defaultFrameTime * defaultFPS;
  23915. this._animate();
  23916. this.onAfterAnimationsObservable.notifyObservers(this);
  23917. // Physics
  23918. if (this._physicsEngine) {
  23919. this.onBeforePhysicsObservable.notifyObservers(this);
  23920. this._physicsEngine._step(defaultFrameTime / 1000);
  23921. this.onAfterPhysicsObservable.notifyObservers(this);
  23922. }
  23923. this.onAfterStepObservable.notifyObservers(this);
  23924. this._currentStepId++;
  23925. stepsTaken++;
  23926. deltaTime -= defaultFrameTime;
  23927. } while (deltaTime > 0 && stepsTaken < internalSteps);
  23928. this._timeAccumulator = deltaTime < 0 ? 0 : deltaTime;
  23929. }
  23930. else {
  23931. // Animations
  23932. var deltaTime = this.useConstantAnimationDeltaTime ? 16 : Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime));
  23933. this._animationRatio = deltaTime * (60.0 / 1000.0);
  23934. this._animate();
  23935. this.onAfterAnimationsObservable.notifyObservers(this);
  23936. // Physics
  23937. if (this._physicsEngine) {
  23938. this.onBeforePhysicsObservable.notifyObservers(this);
  23939. this._physicsEngine._step(deltaTime / 1000.0);
  23940. this.onAfterPhysicsObservable.notifyObservers(this);
  23941. }
  23942. }
  23943. // update gamepad manager
  23944. if (this._gamepadManager && this._gamepadManager._isMonitoring) {
  23945. this._gamepadManager._checkGamepadsStatus();
  23946. }
  23947. // Before render
  23948. this.onBeforeRenderObservable.notifyObservers(this);
  23949. // Customs render targets
  23950. this.OnBeforeRenderTargetsRenderObservable.notifyObservers(this);
  23951. var engine = this.getEngine();
  23952. var currentActiveCamera = this.activeCamera;
  23953. if (this.renderTargetsEnabled) {
  23954. BABYLON.Tools.StartPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  23955. this._intermediateRendering = true;
  23956. for (var customIndex = 0; customIndex < this.customRenderTargets.length; customIndex++) {
  23957. var renderTarget = this.customRenderTargets[customIndex];
  23958. if (renderTarget._shouldRender()) {
  23959. this._renderId++;
  23960. this.activeCamera = renderTarget.activeCamera || this.activeCamera;
  23961. if (!this.activeCamera)
  23962. throw new Error("Active camera not set");
  23963. // Viewport
  23964. engine.setViewport(this.activeCamera.viewport);
  23965. // Camera
  23966. this.updateTransformMatrix();
  23967. renderTarget.render(currentActiveCamera !== this.activeCamera, this.dumpNextRenderTargets);
  23968. }
  23969. }
  23970. BABYLON.Tools.EndPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  23971. this._intermediateRendering = false;
  23972. this._renderId++;
  23973. }
  23974. // Restore back buffer
  23975. if (this.customRenderTargets.length > 0) {
  23976. engine.restoreDefaultFramebuffer();
  23977. }
  23978. this.OnAfterRenderTargetsRenderObservable.notifyObservers(this);
  23979. this.activeCamera = currentActiveCamera;
  23980. // Procedural textures
  23981. if (this.proceduralTexturesEnabled) {
  23982. BABYLON.Tools.StartPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  23983. for (var proceduralIndex = 0; proceduralIndex < this._proceduralTextures.length; proceduralIndex++) {
  23984. var proceduralTexture = this._proceduralTextures[proceduralIndex];
  23985. if (proceduralTexture._shouldRender()) {
  23986. proceduralTexture.render();
  23987. }
  23988. }
  23989. BABYLON.Tools.EndPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  23990. }
  23991. // Clear
  23992. if (this.autoClearDepthAndStencil || this.autoClear) {
  23993. this._engine.clear(this.clearColor, this.autoClear || this.forceWireframe || this.forcePointsCloud, this.autoClearDepthAndStencil, this.autoClearDepthAndStencil);
  23994. }
  23995. // Shadows
  23996. if (this.shadowsEnabled) {
  23997. for (var lightIndex = 0; lightIndex < this.lights.length; lightIndex++) {
  23998. var light = this.lights[lightIndex];
  23999. var shadowGenerator = light.getShadowGenerator();
  24000. if (light.isEnabled() && light.shadowEnabled && shadowGenerator) {
  24001. var shadowMap = (shadowGenerator.getShadowMap());
  24002. if (this.textures.indexOf(shadowMap) !== -1) {
  24003. this._renderTargets.push(shadowMap);
  24004. }
  24005. }
  24006. }
  24007. }
  24008. // Depth renderer
  24009. if (this._depthRenderer) {
  24010. this._renderTargets.push(this._depthRenderer.getDepthMap());
  24011. }
  24012. // Geometry renderer
  24013. if (this._geometryBufferRenderer) {
  24014. this._renderTargets.push(this._geometryBufferRenderer.getGBuffer());
  24015. }
  24016. // RenderPipeline
  24017. if (this._postProcessRenderPipelineManager) {
  24018. this._postProcessRenderPipelineManager.update();
  24019. }
  24020. // Multi-cameras?
  24021. if (this.activeCameras.length > 0) {
  24022. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  24023. if (cameraIndex > 0) {
  24024. this._engine.clear(null, false, true, true);
  24025. }
  24026. this._processSubCameras(this.activeCameras[cameraIndex]);
  24027. }
  24028. }
  24029. else {
  24030. if (!this.activeCamera) {
  24031. throw new Error("No camera defined");
  24032. }
  24033. this._processSubCameras(this.activeCamera);
  24034. }
  24035. // Intersection checks
  24036. this._checkIntersections();
  24037. // Update the audio listener attached to the camera
  24038. if (BABYLON.AudioEngine) {
  24039. this._updateAudioParameters();
  24040. }
  24041. // After render
  24042. if (this.afterRender) {
  24043. this.afterRender();
  24044. }
  24045. this.onAfterRenderObservable.notifyObservers(this);
  24046. // Cleaning
  24047. for (var index = 0; index < this._toBeDisposed.length; index++) {
  24048. var data = this._toBeDisposed.data[index];
  24049. if (data) {
  24050. data.dispose();
  24051. }
  24052. this._toBeDisposed[index] = null;
  24053. }
  24054. this._toBeDisposed.reset();
  24055. if (this.dumpNextRenderTargets) {
  24056. this.dumpNextRenderTargets = false;
  24057. }
  24058. this._activeBones.addCount(0, true);
  24059. this._activeIndices.addCount(0, true);
  24060. this._activeParticles.addCount(0, true);
  24061. };
  24062. Scene.prototype._updateAudioParameters = function () {
  24063. if (!this.audioEnabled || !this._mainSoundTrack || (this._mainSoundTrack.soundCollection.length === 0 && this.soundTracks.length === 1)) {
  24064. return;
  24065. }
  24066. var listeningCamera;
  24067. var audioEngine = BABYLON.Engine.audioEngine;
  24068. if (this.activeCameras.length > 0) {
  24069. listeningCamera = this.activeCameras[0];
  24070. }
  24071. else {
  24072. listeningCamera = this.activeCamera;
  24073. }
  24074. if (listeningCamera && audioEngine.canUseWebAudio && audioEngine.audioContext) {
  24075. audioEngine.audioContext.listener.setPosition(listeningCamera.position.x, listeningCamera.position.y, listeningCamera.position.z);
  24076. // for VR cameras
  24077. if (listeningCamera.rigCameras && listeningCamera.rigCameras.length > 0) {
  24078. listeningCamera = listeningCamera.rigCameras[0];
  24079. }
  24080. var mat = BABYLON.Matrix.Invert(listeningCamera.getViewMatrix());
  24081. var cameraDirection = BABYLON.Vector3.TransformNormal(new BABYLON.Vector3(0, 0, -1), mat);
  24082. cameraDirection.normalize();
  24083. // To avoid some errors on GearVR
  24084. if (!isNaN(cameraDirection.x) && !isNaN(cameraDirection.y) && !isNaN(cameraDirection.z)) {
  24085. audioEngine.audioContext.listener.setOrientation(cameraDirection.x, cameraDirection.y, cameraDirection.z, 0, 1, 0);
  24086. }
  24087. var i;
  24088. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  24089. var sound = this.mainSoundTrack.soundCollection[i];
  24090. if (sound.useCustomAttenuation) {
  24091. sound.updateDistanceFromListener();
  24092. }
  24093. }
  24094. for (i = 0; i < this.soundTracks.length; i++) {
  24095. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  24096. sound = this.soundTracks[i].soundCollection[j];
  24097. if (sound.useCustomAttenuation) {
  24098. sound.updateDistanceFromListener();
  24099. }
  24100. }
  24101. }
  24102. }
  24103. };
  24104. Object.defineProperty(Scene.prototype, "audioEnabled", {
  24105. // Audio
  24106. get: function () {
  24107. return this._audioEnabled;
  24108. },
  24109. set: function (value) {
  24110. this._audioEnabled = value;
  24111. if (BABYLON.AudioEngine) {
  24112. if (this._audioEnabled) {
  24113. this._enableAudio();
  24114. }
  24115. else {
  24116. this._disableAudio();
  24117. }
  24118. }
  24119. },
  24120. enumerable: true,
  24121. configurable: true
  24122. });
  24123. Scene.prototype._disableAudio = function () {
  24124. var i;
  24125. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  24126. this.mainSoundTrack.soundCollection[i].pause();
  24127. }
  24128. for (i = 0; i < this.soundTracks.length; i++) {
  24129. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  24130. this.soundTracks[i].soundCollection[j].pause();
  24131. }
  24132. }
  24133. };
  24134. Scene.prototype._enableAudio = function () {
  24135. var i;
  24136. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  24137. if (this.mainSoundTrack.soundCollection[i].isPaused) {
  24138. this.mainSoundTrack.soundCollection[i].play();
  24139. }
  24140. }
  24141. for (i = 0; i < this.soundTracks.length; i++) {
  24142. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  24143. if (this.soundTracks[i].soundCollection[j].isPaused) {
  24144. this.soundTracks[i].soundCollection[j].play();
  24145. }
  24146. }
  24147. }
  24148. };
  24149. Object.defineProperty(Scene.prototype, "headphone", {
  24150. get: function () {
  24151. return this._headphone;
  24152. },
  24153. set: function (value) {
  24154. this._headphone = value;
  24155. if (BABYLON.AudioEngine) {
  24156. if (this._headphone) {
  24157. this._switchAudioModeForHeadphones();
  24158. }
  24159. else {
  24160. this._switchAudioModeForNormalSpeakers();
  24161. }
  24162. }
  24163. },
  24164. enumerable: true,
  24165. configurable: true
  24166. });
  24167. Scene.prototype._switchAudioModeForHeadphones = function () {
  24168. this.mainSoundTrack.switchPanningModelToHRTF();
  24169. for (var i = 0; i < this.soundTracks.length; i++) {
  24170. this.soundTracks[i].switchPanningModelToHRTF();
  24171. }
  24172. };
  24173. Scene.prototype._switchAudioModeForNormalSpeakers = function () {
  24174. this.mainSoundTrack.switchPanningModelToEqualPower();
  24175. for (var i = 0; i < this.soundTracks.length; i++) {
  24176. this.soundTracks[i].switchPanningModelToEqualPower();
  24177. }
  24178. };
  24179. Scene.prototype.enableDepthRenderer = function () {
  24180. if (this._depthRenderer) {
  24181. return this._depthRenderer;
  24182. }
  24183. this._depthRenderer = new BABYLON.DepthRenderer(this);
  24184. return this._depthRenderer;
  24185. };
  24186. Scene.prototype.disableDepthRenderer = function () {
  24187. if (!this._depthRenderer) {
  24188. return;
  24189. }
  24190. this._depthRenderer.dispose();
  24191. this._depthRenderer = null;
  24192. };
  24193. Scene.prototype.enableGeometryBufferRenderer = function (ratio) {
  24194. if (ratio === void 0) { ratio = 1; }
  24195. if (this._geometryBufferRenderer) {
  24196. return this._geometryBufferRenderer;
  24197. }
  24198. this._geometryBufferRenderer = new BABYLON.GeometryBufferRenderer(this, ratio);
  24199. if (!this._geometryBufferRenderer.isSupported) {
  24200. this._geometryBufferRenderer = null;
  24201. }
  24202. return this._geometryBufferRenderer;
  24203. };
  24204. Scene.prototype.disableGeometryBufferRenderer = function () {
  24205. if (!this._geometryBufferRenderer) {
  24206. return;
  24207. }
  24208. this._geometryBufferRenderer.dispose();
  24209. this._geometryBufferRenderer = null;
  24210. };
  24211. Scene.prototype.freezeMaterials = function () {
  24212. for (var i = 0; i < this.materials.length; i++) {
  24213. this.materials[i].freeze();
  24214. }
  24215. };
  24216. Scene.prototype.unfreezeMaterials = function () {
  24217. for (var i = 0; i < this.materials.length; i++) {
  24218. this.materials[i].unfreeze();
  24219. }
  24220. };
  24221. Scene.prototype.dispose = function () {
  24222. this.beforeRender = null;
  24223. this.afterRender = null;
  24224. this.skeletons = [];
  24225. this.morphTargetManagers = [];
  24226. this.importedMeshesFiles = new Array();
  24227. this.stopAllAnimations();
  24228. this.resetCachedMaterial();
  24229. if (this._depthRenderer) {
  24230. this._depthRenderer.dispose();
  24231. }
  24232. if (this._gamepadManager) {
  24233. this._gamepadManager.dispose();
  24234. this._gamepadManager = null;
  24235. }
  24236. // Smart arrays
  24237. if (this.activeCamera) {
  24238. this.activeCamera._activeMeshes.dispose();
  24239. this.activeCamera = null;
  24240. }
  24241. this._activeMeshes.dispose();
  24242. this._renderingManager.dispose();
  24243. this._processedMaterials.dispose();
  24244. this._activeParticleSystems.dispose();
  24245. this._activeSkeletons.dispose();
  24246. this._softwareSkinnedMeshes.dispose();
  24247. this._renderTargets.dispose();
  24248. if (this._boundingBoxRenderer) {
  24249. this._boundingBoxRenderer.dispose();
  24250. }
  24251. this._meshesForIntersections.dispose();
  24252. this._toBeDisposed.dispose();
  24253. // Abort active requests
  24254. for (var _i = 0, _a = this._activeRequests; _i < _a.length; _i++) {
  24255. var request = _a[_i];
  24256. request.abort();
  24257. }
  24258. // Debug layer
  24259. if (this._debugLayer) {
  24260. this._debugLayer.hide();
  24261. }
  24262. // Events
  24263. this.onDisposeObservable.notifyObservers(this);
  24264. this.onDisposeObservable.clear();
  24265. this.onBeforeRenderObservable.clear();
  24266. this.onAfterRenderObservable.clear();
  24267. this.OnBeforeRenderTargetsRenderObservable.clear();
  24268. this.OnAfterRenderTargetsRenderObservable.clear();
  24269. this.onAfterStepObservable.clear();
  24270. this.onBeforeStepObservable.clear();
  24271. this.onBeforeActiveMeshesEvaluationObservable.clear();
  24272. this.onAfterActiveMeshesEvaluationObservable.clear();
  24273. this.onBeforeParticlesRenderingObservable.clear();
  24274. this.onAfterParticlesRenderingObservable.clear();
  24275. this.onBeforeSpritesRenderingObservable.clear();
  24276. this.onAfterSpritesRenderingObservable.clear();
  24277. this.onBeforeDrawPhaseObservable.clear();
  24278. this.onAfterDrawPhaseObservable.clear();
  24279. this.onBeforePhysicsObservable.clear();
  24280. this.onAfterPhysicsObservable.clear();
  24281. this.onBeforeAnimationsObservable.clear();
  24282. this.onAfterAnimationsObservable.clear();
  24283. this.onDataLoadedObservable.clear();
  24284. this.detachControl();
  24285. // Release sounds & sounds tracks
  24286. if (BABYLON.AudioEngine) {
  24287. this.disposeSounds();
  24288. }
  24289. // VR Helper
  24290. if (this.VRHelper) {
  24291. this.VRHelper.dispose();
  24292. }
  24293. // Detach cameras
  24294. var canvas = this._engine.getRenderingCanvas();
  24295. if (canvas) {
  24296. var index;
  24297. for (index = 0; index < this.cameras.length; index++) {
  24298. this.cameras[index].detachControl(canvas);
  24299. }
  24300. }
  24301. // Release animation groups
  24302. while (this.animationGroups.length) {
  24303. this.animationGroups[0].dispose();
  24304. }
  24305. // Release lights
  24306. while (this.lights.length) {
  24307. this.lights[0].dispose();
  24308. }
  24309. // Release meshes
  24310. while (this.meshes.length) {
  24311. this.meshes[0].dispose(true);
  24312. }
  24313. while (this.transformNodes.length) {
  24314. this.removeTransformNode(this.transformNodes[0]);
  24315. }
  24316. // Release cameras
  24317. while (this.cameras.length) {
  24318. this.cameras[0].dispose();
  24319. }
  24320. // Release materials
  24321. if (this.defaultMaterial) {
  24322. this.defaultMaterial.dispose();
  24323. }
  24324. while (this.multiMaterials.length) {
  24325. this.multiMaterials[0].dispose();
  24326. }
  24327. while (this.materials.length) {
  24328. this.materials[0].dispose();
  24329. }
  24330. // Release particles
  24331. while (this.particleSystems.length) {
  24332. this.particleSystems[0].dispose();
  24333. }
  24334. // Release sprites
  24335. while (this.spriteManagers.length) {
  24336. this.spriteManagers[0].dispose();
  24337. }
  24338. // Release postProcesses
  24339. while (this.postProcesses.length) {
  24340. this.postProcesses[0].dispose();
  24341. }
  24342. // Release layers
  24343. while (this.layers.length) {
  24344. this.layers[0].dispose();
  24345. }
  24346. while (this.effectLayers.length) {
  24347. this.effectLayers[0].dispose();
  24348. }
  24349. // Release textures
  24350. while (this.textures.length) {
  24351. this.textures[0].dispose();
  24352. }
  24353. // Release UBO
  24354. this._sceneUbo.dispose();
  24355. if (this._alternateSceneUbo) {
  24356. this._alternateSceneUbo.dispose();
  24357. }
  24358. // Post-processes
  24359. this.postProcessManager.dispose();
  24360. if (this._postProcessRenderPipelineManager) {
  24361. this._postProcessRenderPipelineManager.dispose();
  24362. }
  24363. // Physics
  24364. if (this._physicsEngine) {
  24365. this.disablePhysicsEngine();
  24366. }
  24367. // Remove from engine
  24368. index = this._engine.scenes.indexOf(this);
  24369. if (index > -1) {
  24370. this._engine.scenes.splice(index, 1);
  24371. }
  24372. this._engine.wipeCaches(true);
  24373. this._isDisposed = true;
  24374. };
  24375. Object.defineProperty(Scene.prototype, "isDisposed", {
  24376. get: function () {
  24377. return this._isDisposed;
  24378. },
  24379. enumerable: true,
  24380. configurable: true
  24381. });
  24382. // Release sounds & sounds tracks
  24383. Scene.prototype.disposeSounds = function () {
  24384. if (!this._mainSoundTrack) {
  24385. return;
  24386. }
  24387. this.mainSoundTrack.dispose();
  24388. for (var scIndex = 0; scIndex < this.soundTracks.length; scIndex++) {
  24389. this.soundTracks[scIndex].dispose();
  24390. }
  24391. };
  24392. // Octrees
  24393. Scene.prototype.getWorldExtends = function () {
  24394. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  24395. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  24396. for (var index = 0; index < this.meshes.length; index++) {
  24397. var mesh = this.meshes[index];
  24398. mesh.computeWorldMatrix(true);
  24399. if (!mesh.subMeshes || mesh.subMeshes.length === 0 || mesh.infiniteDistance) {
  24400. continue;
  24401. }
  24402. var boundingInfo = mesh.getBoundingInfo();
  24403. var minBox = boundingInfo.boundingBox.minimumWorld;
  24404. var maxBox = boundingInfo.boundingBox.maximumWorld;
  24405. BABYLON.Tools.CheckExtends(minBox, min, max);
  24406. BABYLON.Tools.CheckExtends(maxBox, min, max);
  24407. }
  24408. return {
  24409. min: min,
  24410. max: max
  24411. };
  24412. };
  24413. Scene.prototype.createOrUpdateSelectionOctree = function (maxCapacity, maxDepth) {
  24414. if (maxCapacity === void 0) { maxCapacity = 64; }
  24415. if (maxDepth === void 0) { maxDepth = 2; }
  24416. if (!this._selectionOctree) {
  24417. this._selectionOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForMeshes, maxCapacity, maxDepth);
  24418. }
  24419. var worldExtends = this.getWorldExtends();
  24420. // Update octree
  24421. this._selectionOctree.update(worldExtends.min, worldExtends.max, this.meshes);
  24422. return this._selectionOctree;
  24423. };
  24424. // Picking
  24425. Scene.prototype.createPickingRay = function (x, y, world, camera, cameraViewSpace) {
  24426. if (cameraViewSpace === void 0) { cameraViewSpace = false; }
  24427. var result = BABYLON.Ray.Zero();
  24428. this.createPickingRayToRef(x, y, world, result, camera, cameraViewSpace);
  24429. return result;
  24430. };
  24431. Scene.prototype.createPickingRayToRef = function (x, y, world, result, camera, cameraViewSpace) {
  24432. if (cameraViewSpace === void 0) { cameraViewSpace = false; }
  24433. var engine = this._engine;
  24434. if (!camera) {
  24435. if (!this.activeCamera)
  24436. throw new Error("Active camera not set");
  24437. camera = this.activeCamera;
  24438. }
  24439. var cameraViewport = camera.viewport;
  24440. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  24441. // Moving coordinates to local viewport world
  24442. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  24443. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  24444. result.update(x, y, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), cameraViewSpace ? BABYLON.Matrix.Identity() : camera.getViewMatrix(), camera.getProjectionMatrix());
  24445. return this;
  24446. };
  24447. Scene.prototype.createPickingRayInCameraSpace = function (x, y, camera) {
  24448. var result = BABYLON.Ray.Zero();
  24449. this.createPickingRayInCameraSpaceToRef(x, y, result, camera);
  24450. return result;
  24451. };
  24452. Scene.prototype.createPickingRayInCameraSpaceToRef = function (x, y, result, camera) {
  24453. if (!BABYLON.PickingInfo) {
  24454. return this;
  24455. }
  24456. var engine = this._engine;
  24457. if (!camera) {
  24458. if (!this.activeCamera)
  24459. throw new Error("Active camera not set");
  24460. camera = this.activeCamera;
  24461. }
  24462. var cameraViewport = camera.viewport;
  24463. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  24464. var identity = BABYLON.Matrix.Identity();
  24465. // Moving coordinates to local viewport world
  24466. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  24467. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  24468. result.update(x, y, viewport.width, viewport.height, identity, identity, camera.getProjectionMatrix());
  24469. return this;
  24470. };
  24471. Scene.prototype._internalPick = function (rayFunction, predicate, fastCheck) {
  24472. if (!BABYLON.PickingInfo) {
  24473. return null;
  24474. }
  24475. var pickingInfo = null;
  24476. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  24477. var mesh = this.meshes[meshIndex];
  24478. if (predicate) {
  24479. if (!predicate(mesh)) {
  24480. continue;
  24481. }
  24482. }
  24483. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  24484. continue;
  24485. }
  24486. var world = mesh.getWorldMatrix();
  24487. var ray = rayFunction(world);
  24488. var result = mesh.intersects(ray, fastCheck);
  24489. if (!result || !result.hit)
  24490. continue;
  24491. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  24492. continue;
  24493. pickingInfo = result;
  24494. if (fastCheck) {
  24495. break;
  24496. }
  24497. }
  24498. return pickingInfo || new BABYLON.PickingInfo();
  24499. };
  24500. Scene.prototype._internalMultiPick = function (rayFunction, predicate) {
  24501. if (!BABYLON.PickingInfo) {
  24502. return null;
  24503. }
  24504. var pickingInfos = new Array();
  24505. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  24506. var mesh = this.meshes[meshIndex];
  24507. if (predicate) {
  24508. if (!predicate(mesh)) {
  24509. continue;
  24510. }
  24511. }
  24512. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  24513. continue;
  24514. }
  24515. var world = mesh.getWorldMatrix();
  24516. var ray = rayFunction(world);
  24517. var result = mesh.intersects(ray, false);
  24518. if (!result || !result.hit)
  24519. continue;
  24520. pickingInfos.push(result);
  24521. }
  24522. return pickingInfos;
  24523. };
  24524. Scene.prototype._internalPickSprites = function (ray, predicate, fastCheck, camera) {
  24525. if (!BABYLON.PickingInfo) {
  24526. return null;
  24527. }
  24528. var pickingInfo = null;
  24529. if (!camera) {
  24530. if (!this.activeCamera) {
  24531. return null;
  24532. }
  24533. camera = this.activeCamera;
  24534. }
  24535. if (this.spriteManagers.length > 0) {
  24536. for (var spriteIndex = 0; spriteIndex < this.spriteManagers.length; spriteIndex++) {
  24537. var spriteManager = this.spriteManagers[spriteIndex];
  24538. if (!spriteManager.isPickable) {
  24539. continue;
  24540. }
  24541. var result = spriteManager.intersects(ray, camera, predicate, fastCheck);
  24542. if (!result || !result.hit)
  24543. continue;
  24544. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  24545. continue;
  24546. pickingInfo = result;
  24547. if (fastCheck) {
  24548. break;
  24549. }
  24550. }
  24551. }
  24552. return pickingInfo || new BABYLON.PickingInfo();
  24553. };
  24554. /** Launch a ray to try to pick a mesh in the scene
  24555. * @param x position on screen
  24556. * @param y position on screen
  24557. * @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
  24558. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null.
  24559. * @param camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  24560. */
  24561. Scene.prototype.pick = function (x, y, predicate, fastCheck, camera) {
  24562. var _this = this;
  24563. if (!BABYLON.PickingInfo) {
  24564. return null;
  24565. }
  24566. return this._internalPick(function (world) {
  24567. _this.createPickingRayToRef(x, y, world, _this._tempPickingRay, camera || null);
  24568. return _this._tempPickingRay;
  24569. }, predicate, fastCheck);
  24570. };
  24571. /** Launch a ray to try to pick a sprite in the scene
  24572. * @param x position on screen
  24573. * @param y position on screen
  24574. * @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
  24575. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null.
  24576. * @param camera camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  24577. */
  24578. Scene.prototype.pickSprite = function (x, y, predicate, fastCheck, camera) {
  24579. this.createPickingRayInCameraSpaceToRef(x, y, this._tempPickingRay, camera);
  24580. return this._internalPickSprites(this._tempPickingRay, predicate, fastCheck, camera);
  24581. };
  24582. /** Use the given ray to pick a mesh in the scene
  24583. * @param ray The ray to use to pick meshes
  24584. * @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
  24585. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null.
  24586. */
  24587. Scene.prototype.pickWithRay = function (ray, predicate, fastCheck) {
  24588. var _this = this;
  24589. return this._internalPick(function (world) {
  24590. if (!_this._pickWithRayInverseMatrix) {
  24591. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  24592. }
  24593. world.invertToRef(_this._pickWithRayInverseMatrix);
  24594. if (!_this._cachedRayForTransform) {
  24595. _this._cachedRayForTransform = BABYLON.Ray.Zero();
  24596. }
  24597. BABYLON.Ray.TransformToRef(ray, _this._pickWithRayInverseMatrix, _this._cachedRayForTransform);
  24598. return _this._cachedRayForTransform;
  24599. }, predicate, fastCheck);
  24600. };
  24601. /**
  24602. * Launch a ray to try to pick a mesh in the scene
  24603. * @param x X position on screen
  24604. * @param y Y position on screen
  24605. * @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
  24606. * @param camera camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  24607. */
  24608. Scene.prototype.multiPick = function (x, y, predicate, camera) {
  24609. var _this = this;
  24610. return this._internalMultiPick(function (world) { return _this.createPickingRay(x, y, world, camera || null); }, predicate);
  24611. };
  24612. /**
  24613. * Launch a ray to try to pick a mesh in the scene
  24614. * @param ray Ray to use
  24615. * @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
  24616. */
  24617. Scene.prototype.multiPickWithRay = function (ray, predicate) {
  24618. var _this = this;
  24619. return this._internalMultiPick(function (world) {
  24620. if (!_this._pickWithRayInverseMatrix) {
  24621. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  24622. }
  24623. world.invertToRef(_this._pickWithRayInverseMatrix);
  24624. if (!_this._cachedRayForTransform) {
  24625. _this._cachedRayForTransform = BABYLON.Ray.Zero();
  24626. }
  24627. BABYLON.Ray.TransformToRef(ray, _this._pickWithRayInverseMatrix, _this._cachedRayForTransform);
  24628. return _this._cachedRayForTransform;
  24629. }, predicate);
  24630. };
  24631. Scene.prototype.setPointerOverMesh = function (mesh) {
  24632. if (this._pointerOverMesh === mesh) {
  24633. return;
  24634. }
  24635. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  24636. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  24637. }
  24638. this._pointerOverMesh = mesh;
  24639. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  24640. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  24641. }
  24642. };
  24643. Scene.prototype.getPointerOverMesh = function () {
  24644. return this._pointerOverMesh;
  24645. };
  24646. Scene.prototype.setPointerOverSprite = function (sprite) {
  24647. if (this._pointerOverSprite === sprite) {
  24648. return;
  24649. }
  24650. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  24651. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  24652. }
  24653. this._pointerOverSprite = sprite;
  24654. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  24655. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  24656. }
  24657. };
  24658. Scene.prototype.getPointerOverSprite = function () {
  24659. return this._pointerOverSprite;
  24660. };
  24661. // Physics
  24662. Scene.prototype.getPhysicsEngine = function () {
  24663. return this._physicsEngine;
  24664. };
  24665. /**
  24666. * Enables physics to the current scene
  24667. * @param {BABYLON.Vector3} [gravity] - the scene's gravity for the physics engine
  24668. * @param {BABYLON.IPhysicsEnginePlugin} [plugin] - The physics engine to be used. defaults to OimoJS.
  24669. * @return {boolean} was the physics engine initialized
  24670. */
  24671. Scene.prototype.enablePhysics = function (gravity, plugin) {
  24672. if (gravity === void 0) { gravity = null; }
  24673. if (this._physicsEngine) {
  24674. return true;
  24675. }
  24676. try {
  24677. this._physicsEngine = new BABYLON.PhysicsEngine(gravity, plugin);
  24678. return true;
  24679. }
  24680. catch (e) {
  24681. BABYLON.Tools.Error(e.message);
  24682. return false;
  24683. }
  24684. };
  24685. Scene.prototype.disablePhysicsEngine = function () {
  24686. if (!this._physicsEngine) {
  24687. return;
  24688. }
  24689. this._physicsEngine.dispose();
  24690. this._physicsEngine = null;
  24691. };
  24692. Scene.prototype.isPhysicsEnabled = function () {
  24693. return this._physicsEngine !== undefined;
  24694. };
  24695. Scene.prototype.deleteCompoundImpostor = function (compound) {
  24696. var mesh = compound.parts[0].mesh;
  24697. if (mesh.physicsImpostor) {
  24698. mesh.physicsImpostor.dispose();
  24699. mesh.physicsImpostor = null;
  24700. }
  24701. };
  24702. // Misc.
  24703. Scene.prototype._rebuildGeometries = function () {
  24704. for (var _i = 0, _a = this._geometries; _i < _a.length; _i++) {
  24705. var geometry = _a[_i];
  24706. geometry._rebuild();
  24707. }
  24708. for (var _b = 0, _c = this.meshes; _b < _c.length; _b++) {
  24709. var mesh = _c[_b];
  24710. mesh._rebuild();
  24711. }
  24712. if (this.postProcessManager) {
  24713. this.postProcessManager._rebuild();
  24714. }
  24715. for (var _d = 0, _e = this.layers; _d < _e.length; _d++) {
  24716. var layer = _e[_d];
  24717. layer._rebuild();
  24718. }
  24719. for (var _f = 0, _g = this.effectLayers; _f < _g.length; _f++) {
  24720. var effectLayer = _g[_f];
  24721. effectLayer._rebuild();
  24722. }
  24723. if (this._boundingBoxRenderer) {
  24724. this._boundingBoxRenderer._rebuild();
  24725. }
  24726. for (var _h = 0, _j = this.particleSystems; _h < _j.length; _h++) {
  24727. var system = _j[_h];
  24728. system.rebuild();
  24729. }
  24730. if (this._postProcessRenderPipelineManager) {
  24731. this._postProcessRenderPipelineManager._rebuild();
  24732. }
  24733. };
  24734. Scene.prototype._rebuildTextures = function () {
  24735. for (var _i = 0, _a = this.textures; _i < _a.length; _i++) {
  24736. var texture = _a[_i];
  24737. texture._rebuild();
  24738. }
  24739. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  24740. };
  24741. /**
  24742. * Creates a default light for the scene.
  24743. * @param replace Whether to replace the existing lights in the scene.
  24744. */
  24745. Scene.prototype.createDefaultLight = function (replace) {
  24746. if (replace === void 0) { replace = false; }
  24747. // Dispose existing light in replace mode.
  24748. if (replace) {
  24749. if (this.lights) {
  24750. for (var i = 0; i < this.lights.length; i++) {
  24751. this.lights[i].dispose();
  24752. }
  24753. }
  24754. }
  24755. // Light
  24756. if (this.lights.length === 0) {
  24757. new BABYLON.HemisphericLight("default light", BABYLON.Vector3.Up(), this);
  24758. }
  24759. };
  24760. /**
  24761. * Creates a default camera for the scene.
  24762. * @param createArcRotateCamera Whether to create an arc rotate or a free camera.
  24763. * @param replace Whether to replace the existing active camera in the scene.
  24764. * @param attachCameraControls Whether to attach camera controls to the canvas.
  24765. */
  24766. Scene.prototype.createDefaultCamera = function (createArcRotateCamera, replace, attachCameraControls) {
  24767. if (createArcRotateCamera === void 0) { createArcRotateCamera = false; }
  24768. if (replace === void 0) { replace = false; }
  24769. if (attachCameraControls === void 0) { attachCameraControls = false; }
  24770. // Dispose existing camera in replace mode.
  24771. if (replace) {
  24772. if (this.activeCamera) {
  24773. this.activeCamera.dispose();
  24774. this.activeCamera = null;
  24775. }
  24776. }
  24777. // Camera
  24778. if (!this.activeCamera) {
  24779. var worldExtends = this.getWorldExtends();
  24780. var worldSize = worldExtends.max.subtract(worldExtends.min);
  24781. var worldCenter = worldExtends.min.add(worldSize.scale(0.5));
  24782. var camera;
  24783. var radius = worldSize.length() * 1.5;
  24784. // empty scene scenario!
  24785. if (!isFinite(radius)) {
  24786. radius = 1;
  24787. worldCenter.copyFromFloats(0, 0, 0);
  24788. }
  24789. if (createArcRotateCamera) {
  24790. var arcRotateCamera = new BABYLON.ArcRotateCamera("default camera", -(Math.PI / 2), Math.PI / 2, radius, worldCenter, this);
  24791. arcRotateCamera.lowerRadiusLimit = radius * 0.01;
  24792. arcRotateCamera.wheelPrecision = 100 / radius;
  24793. camera = arcRotateCamera;
  24794. }
  24795. else {
  24796. var freeCamera = new BABYLON.FreeCamera("default camera", new BABYLON.Vector3(worldCenter.x, worldCenter.y, -radius), this);
  24797. freeCamera.setTarget(worldCenter);
  24798. camera = freeCamera;
  24799. }
  24800. camera.minZ = radius * 0.01;
  24801. camera.maxZ = radius * 1000;
  24802. camera.speed = radius * 0.2;
  24803. this.activeCamera = camera;
  24804. var canvas = this.getEngine().getRenderingCanvas();
  24805. if (attachCameraControls && canvas) {
  24806. camera.attachControl(canvas);
  24807. }
  24808. }
  24809. };
  24810. Scene.prototype.createDefaultCameraOrLight = function (createArcRotateCamera, replace, attachCameraControls) {
  24811. if (createArcRotateCamera === void 0) { createArcRotateCamera = false; }
  24812. if (replace === void 0) { replace = false; }
  24813. if (attachCameraControls === void 0) { attachCameraControls = false; }
  24814. this.createDefaultLight(replace);
  24815. this.createDefaultCamera(createArcRotateCamera, replace, attachCameraControls);
  24816. };
  24817. Scene.prototype.createDefaultSkybox = function (environmentTexture, pbr, scale, blur) {
  24818. if (pbr === void 0) { pbr = false; }
  24819. if (scale === void 0) { scale = 1000; }
  24820. if (blur === void 0) { blur = 0; }
  24821. if (environmentTexture) {
  24822. this.environmentTexture = environmentTexture;
  24823. }
  24824. if (!this.environmentTexture) {
  24825. BABYLON.Tools.Warn("Can not create default skybox without environment texture.");
  24826. return null;
  24827. }
  24828. // Skybox
  24829. var hdrSkybox = BABYLON.Mesh.CreateBox("hdrSkyBox", scale, this);
  24830. if (pbr) {
  24831. var hdrSkyboxMaterial = new BABYLON.PBRMaterial("skyBox", this);
  24832. hdrSkyboxMaterial.backFaceCulling = false;
  24833. hdrSkyboxMaterial.reflectionTexture = this.environmentTexture.clone();
  24834. if (hdrSkyboxMaterial.reflectionTexture) {
  24835. hdrSkyboxMaterial.reflectionTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  24836. }
  24837. hdrSkyboxMaterial.microSurface = 1.0 - blur;
  24838. hdrSkyboxMaterial.disableLighting = true;
  24839. hdrSkyboxMaterial.twoSidedLighting = true;
  24840. hdrSkybox.infiniteDistance = true;
  24841. hdrSkybox.material = hdrSkyboxMaterial;
  24842. }
  24843. else {
  24844. var skyboxMaterial = new BABYLON.StandardMaterial("skyBox", this);
  24845. skyboxMaterial.backFaceCulling = false;
  24846. skyboxMaterial.reflectionTexture = this.environmentTexture.clone();
  24847. if (skyboxMaterial.reflectionTexture) {
  24848. skyboxMaterial.reflectionTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  24849. }
  24850. skyboxMaterial.disableLighting = true;
  24851. hdrSkybox.infiniteDistance = true;
  24852. hdrSkybox.material = skyboxMaterial;
  24853. }
  24854. return hdrSkybox;
  24855. };
  24856. Scene.prototype.createDefaultEnvironment = function (options) {
  24857. if (BABYLON.EnvironmentHelper) {
  24858. return new BABYLON.EnvironmentHelper(options, this);
  24859. }
  24860. return null;
  24861. };
  24862. Scene.prototype.createDefaultVRExperience = function (webVROptions) {
  24863. if (webVROptions === void 0) { webVROptions = {}; }
  24864. return new BABYLON.VRExperienceHelper(this, webVROptions);
  24865. };
  24866. // Tags
  24867. Scene.prototype._getByTags = function (list, tagsQuery, forEach) {
  24868. if (tagsQuery === undefined) {
  24869. // returns the complete list (could be done with BABYLON.Tags.MatchesQuery but no need to have a for-loop here)
  24870. return list;
  24871. }
  24872. var listByTags = [];
  24873. forEach = forEach || (function (item) { return; });
  24874. for (var i in list) {
  24875. var item = list[i];
  24876. if (BABYLON.Tags && BABYLON.Tags.MatchesQuery(item, tagsQuery)) {
  24877. listByTags.push(item);
  24878. forEach(item);
  24879. }
  24880. }
  24881. return listByTags;
  24882. };
  24883. Scene.prototype.getMeshesByTags = function (tagsQuery, forEach) {
  24884. return this._getByTags(this.meshes, tagsQuery, forEach);
  24885. };
  24886. Scene.prototype.getCamerasByTags = function (tagsQuery, forEach) {
  24887. return this._getByTags(this.cameras, tagsQuery, forEach);
  24888. };
  24889. Scene.prototype.getLightsByTags = function (tagsQuery, forEach) {
  24890. return this._getByTags(this.lights, tagsQuery, forEach);
  24891. };
  24892. Scene.prototype.getMaterialByTags = function (tagsQuery, forEach) {
  24893. return this._getByTags(this.materials, tagsQuery, forEach).concat(this._getByTags(this.multiMaterials, tagsQuery, forEach));
  24894. };
  24895. /**
  24896. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  24897. * This allowed control for front to back rendering or reversly depending of the special needs.
  24898. *
  24899. * @param renderingGroupId The rendering group id corresponding to its index
  24900. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  24901. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  24902. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  24903. */
  24904. Scene.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  24905. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  24906. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  24907. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  24908. this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
  24909. };
  24910. /**
  24911. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  24912. *
  24913. * @param renderingGroupId The rendering group id corresponding to its index
  24914. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  24915. * @param depth Automatically clears depth between groups if true and autoClear is true.
  24916. * @param stencil Automatically clears stencil between groups if true and autoClear is true.
  24917. */
  24918. Scene.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil, depth, stencil) {
  24919. if (depth === void 0) { depth = true; }
  24920. if (stencil === void 0) { stencil = true; }
  24921. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil, depth, stencil);
  24922. };
  24923. /**
  24924. * Will flag all materials as dirty to trigger new shader compilation
  24925. * @param predicate If not null, it will be used to specifiy if a material has to be marked as dirty
  24926. */
  24927. Scene.prototype.markAllMaterialsAsDirty = function (flag, predicate) {
  24928. for (var _i = 0, _a = this.materials; _i < _a.length; _i++) {
  24929. var material = _a[_i];
  24930. if (predicate && !predicate(material)) {
  24931. continue;
  24932. }
  24933. material.markAsDirty(flag);
  24934. }
  24935. };
  24936. Scene.prototype._loadFile = function (url, onSuccess, onProgress, useDatabase, useArrayBuffer, onError) {
  24937. var _this = this;
  24938. var request = BABYLON.Tools.LoadFile(url, onSuccess, onProgress, useDatabase ? this.database : undefined, useArrayBuffer, onError);
  24939. this._activeRequests.push(request);
  24940. request.onCompleteObservable.add(function (request) {
  24941. _this._activeRequests.splice(_this._activeRequests.indexOf(request), 1);
  24942. });
  24943. return request;
  24944. };
  24945. /** @ignore */
  24946. Scene.prototype._loadFileAsync = function (url, useDatabase, useArrayBuffer) {
  24947. var _this = this;
  24948. return new Promise(function (resolve, reject) {
  24949. _this._loadFile(url, function (data) {
  24950. resolve(data);
  24951. }, undefined, useDatabase, useArrayBuffer, function (request, exception) {
  24952. reject(exception);
  24953. });
  24954. });
  24955. };
  24956. // Statics
  24957. Scene._FOGMODE_NONE = 0;
  24958. Scene._FOGMODE_EXP = 1;
  24959. Scene._FOGMODE_EXP2 = 2;
  24960. Scene._FOGMODE_LINEAR = 3;
  24961. Scene._uniqueIdCounter = 0;
  24962. Scene.MinDeltaTime = 1.0;
  24963. Scene.MaxDeltaTime = 1000.0;
  24964. /** The distance in pixel that you have to move to prevent some events */
  24965. Scene.DragMovementThreshold = 10; // in pixels
  24966. /** Time in milliseconds to wait to raise long press events if button is still pressed */
  24967. Scene.LongPressDelay = 500; // in milliseconds
  24968. /** Time in milliseconds with two consecutive clicks will be considered as a double click */
  24969. Scene.DoubleClickDelay = 300; // in milliseconds
  24970. /** If you need to check double click without raising a single click at first click, enable this flag */
  24971. Scene.ExclusiveDoubleClickMode = false;
  24972. return Scene;
  24973. }());
  24974. BABYLON.Scene = Scene;
  24975. })(BABYLON || (BABYLON = {}));
  24976. //# sourceMappingURL=babylon.scene.js.map
  24977. var BABYLON;
  24978. (function (BABYLON) {
  24979. /**
  24980. * Set of assets to keep when moving a scene into an asset container.
  24981. */
  24982. var KeepAssets = /** @class */ (function () {
  24983. function KeepAssets() {
  24984. /**
  24985. * Cameras to keep.
  24986. */
  24987. this.cameras = new Array();
  24988. /**
  24989. * Lights to keep.
  24990. */
  24991. this.lights = new Array();
  24992. /**
  24993. * Meshes to keep.
  24994. */
  24995. this.meshes = new Array();
  24996. /**
  24997. * Skeletons to keep.
  24998. */
  24999. this.skeletons = new Array();
  25000. /**
  25001. * ParticleSystems to keep.
  25002. */
  25003. this.particleSystems = new Array();
  25004. /**
  25005. * Animations to keep.
  25006. */
  25007. this.animations = new Array();
  25008. /**
  25009. * MultiMaterials to keep.
  25010. */
  25011. this.multiMaterials = new Array();
  25012. /**
  25013. * Materials to keep.
  25014. */
  25015. this.materials = new Array();
  25016. /**
  25017. * MorphTargetManagers to keep.
  25018. */
  25019. this.morphTargetManagers = new Array();
  25020. /**
  25021. * Geometries to keep.
  25022. */
  25023. this.geometries = new Array();
  25024. /**
  25025. * TransformNodes to keep.
  25026. */
  25027. this.transformNodes = new Array();
  25028. /**
  25029. * LensFlareSystems to keep.
  25030. */
  25031. this.lensFlareSystems = new Array();
  25032. /**
  25033. * ShadowGenerators to keep.
  25034. */
  25035. this.shadowGenerators = new Array();
  25036. /**
  25037. * ActionManagers to keep.
  25038. */
  25039. this.actionManagers = new Array();
  25040. /**
  25041. * Sounds to keep.
  25042. */
  25043. this.sounds = new Array();
  25044. }
  25045. return KeepAssets;
  25046. }());
  25047. BABYLON.KeepAssets = KeepAssets;
  25048. /**
  25049. * Container with a set of assets that can be added or removed from a scene.
  25050. */
  25051. var AssetContainer = /** @class */ (function () {
  25052. /**
  25053. * Instantiates an AssetContainer.
  25054. * @param scene The scene the AssetContainer belongs to.
  25055. */
  25056. function AssetContainer(scene) {
  25057. // Objects
  25058. /**
  25059. * Cameras populated in the container.
  25060. */
  25061. this.cameras = new Array();
  25062. /**
  25063. * Lights populated in the container.
  25064. */
  25065. this.lights = new Array();
  25066. /**
  25067. * Meshes populated in the container.
  25068. */
  25069. this.meshes = new Array();
  25070. /**
  25071. * Skeletons populated in the container.
  25072. */
  25073. this.skeletons = new Array();
  25074. /**
  25075. * ParticleSystems populated in the container.
  25076. */
  25077. this.particleSystems = new Array();
  25078. /**
  25079. * Animations populated in the container.
  25080. */
  25081. this.animations = new Array();
  25082. /**
  25083. * MultiMaterials populated in the container.
  25084. */
  25085. this.multiMaterials = new Array();
  25086. /**
  25087. * Materials populated in the container.
  25088. */
  25089. this.materials = new Array();
  25090. /**
  25091. * MorphTargetManagers populated in the container.
  25092. */
  25093. this.morphTargetManagers = new Array();
  25094. /**
  25095. * Geometries populated in the container.
  25096. */
  25097. this.geometries = new Array();
  25098. /**
  25099. * TransformNodes populated in the container.
  25100. */
  25101. this.transformNodes = new Array();
  25102. /**
  25103. * LensFlareSystems populated in the container.
  25104. */
  25105. this.lensFlareSystems = new Array();
  25106. /**
  25107. * ShadowGenerators populated in the container.
  25108. */
  25109. this.shadowGenerators = new Array();
  25110. /**
  25111. * ActionManagers populated in the container.
  25112. */
  25113. this.actionManagers = new Array();
  25114. /**
  25115. * Sounds populated in the container.
  25116. */
  25117. this.sounds = new Array();
  25118. this.scene = scene;
  25119. }
  25120. /**
  25121. * Adds all the assets from the container to the scene.
  25122. */
  25123. AssetContainer.prototype.addAllToScene = function () {
  25124. var _this = this;
  25125. this.cameras.forEach(function (o) {
  25126. _this.scene.addCamera(o);
  25127. });
  25128. this.lights.forEach(function (o) {
  25129. _this.scene.addLight(o);
  25130. });
  25131. this.meshes.forEach(function (o) {
  25132. _this.scene.addMesh(o);
  25133. });
  25134. this.skeletons.forEach(function (o) {
  25135. _this.scene.addSkeleton(o);
  25136. });
  25137. this.particleSystems.forEach(function (o) {
  25138. _this.scene.addParticleSystem(o);
  25139. });
  25140. this.animations.forEach(function (o) {
  25141. _this.scene.addAnimation(o);
  25142. });
  25143. this.multiMaterials.forEach(function (o) {
  25144. _this.scene.addMultiMaterial(o);
  25145. });
  25146. this.materials.forEach(function (o) {
  25147. _this.scene.addMaterial(o);
  25148. });
  25149. this.morphTargetManagers.forEach(function (o) {
  25150. _this.scene.addMorphTargetManager(o);
  25151. });
  25152. this.geometries.forEach(function (o) {
  25153. _this.scene.addGeometry(o);
  25154. });
  25155. this.transformNodes.forEach(function (o) {
  25156. _this.scene.addTransformNode(o);
  25157. });
  25158. this.lensFlareSystems.forEach(function (o) {
  25159. _this.scene.addLensFlareSystem(o);
  25160. });
  25161. this.actionManagers.forEach(function (o) {
  25162. _this.scene.addActionManager(o);
  25163. });
  25164. this.sounds.forEach(function (o) {
  25165. o.play();
  25166. o.autoplay = true;
  25167. _this.scene.mainSoundTrack.AddSound(o);
  25168. });
  25169. };
  25170. /**
  25171. * Removes all the assets in the container from the scene
  25172. */
  25173. AssetContainer.prototype.removeAllFromScene = function () {
  25174. var _this = this;
  25175. this.cameras.forEach(function (o) {
  25176. _this.scene.removeCamera(o);
  25177. });
  25178. this.lights.forEach(function (o) {
  25179. _this.scene.removeLight(o);
  25180. });
  25181. this.meshes.forEach(function (o) {
  25182. _this.scene.removeMesh(o);
  25183. });
  25184. this.skeletons.forEach(function (o) {
  25185. _this.scene.removeSkeleton(o);
  25186. });
  25187. this.particleSystems.forEach(function (o) {
  25188. _this.scene.removeParticleSystem(o);
  25189. });
  25190. this.animations.forEach(function (o) {
  25191. _this.scene.removeAnimation(o);
  25192. });
  25193. this.multiMaterials.forEach(function (o) {
  25194. _this.scene.removeMultiMaterial(o);
  25195. });
  25196. this.materials.forEach(function (o) {
  25197. _this.scene.removeMaterial(o);
  25198. });
  25199. this.morphTargetManagers.forEach(function (o) {
  25200. _this.scene.removeMorphTargetManager(o);
  25201. });
  25202. this.geometries.forEach(function (o) {
  25203. _this.scene.removeGeometry(o);
  25204. });
  25205. this.transformNodes.forEach(function (o) {
  25206. _this.scene.removeTransformNode(o);
  25207. });
  25208. this.lensFlareSystems.forEach(function (o) {
  25209. _this.scene.removeLensFlareSystem(o);
  25210. });
  25211. this.actionManagers.forEach(function (o) {
  25212. _this.scene.removeActionManager(o);
  25213. });
  25214. this.sounds.forEach(function (o) {
  25215. o.stop();
  25216. o.autoplay = false;
  25217. _this.scene.mainSoundTrack.RemoveSound(o);
  25218. });
  25219. };
  25220. AssetContainer.prototype._moveAssets = function (sourceAssets, targetAssets, keepAssets) {
  25221. for (var _i = 0, sourceAssets_1 = sourceAssets; _i < sourceAssets_1.length; _i++) {
  25222. var asset = sourceAssets_1[_i];
  25223. var move = true;
  25224. for (var _a = 0, keepAssets_1 = keepAssets; _a < keepAssets_1.length; _a++) {
  25225. var keepAsset = keepAssets_1[_a];
  25226. if (asset === keepAsset) {
  25227. move = false;
  25228. break;
  25229. }
  25230. }
  25231. if (move) {
  25232. targetAssets.push(asset);
  25233. }
  25234. }
  25235. };
  25236. /**
  25237. * Removes all the assets contained in the scene and adds them to the container.
  25238. * @param keepAssets Set of assets to keep in the scene. (default: empty)
  25239. */
  25240. AssetContainer.prototype.moveAllFromScene = function (keepAssets) {
  25241. if (keepAssets === undefined) {
  25242. keepAssets = new KeepAssets();
  25243. }
  25244. this._moveAssets(this.scene.cameras, this.cameras, keepAssets.cameras);
  25245. this._moveAssets(this.scene.meshes, this.meshes, keepAssets.meshes);
  25246. this._moveAssets(this.scene.getGeometries(), this.geometries, keepAssets.geometries);
  25247. this._moveAssets(this.scene.materials, this.materials, keepAssets.materials);
  25248. this._moveAssets(this.scene._actionManagers, this.actionManagers, keepAssets.actionManagers);
  25249. this._moveAssets(this.scene.animations, this.animations, keepAssets.animations);
  25250. this._moveAssets(this.scene.lensFlareSystems, this.lensFlareSystems, keepAssets.lensFlareSystems);
  25251. this._moveAssets(this.scene.lights, this.lights, keepAssets.lights);
  25252. this._moveAssets(this.scene.morphTargetManagers, this.morphTargetManagers, keepAssets.morphTargetManagers);
  25253. this._moveAssets(this.scene.multiMaterials, this.multiMaterials, keepAssets.multiMaterials);
  25254. this._moveAssets(this.scene.skeletons, this.skeletons, keepAssets.skeletons);
  25255. this._moveAssets(this.scene.particleSystems, this.particleSystems, keepAssets.particleSystems);
  25256. this._moveAssets(this.scene.mainSoundTrack.soundCollection, this.sounds, keepAssets.sounds);
  25257. this._moveAssets(this.scene.transformNodes, this.transformNodes, keepAssets.transformNodes);
  25258. this.removeAllFromScene();
  25259. };
  25260. return AssetContainer;
  25261. }());
  25262. BABYLON.AssetContainer = AssetContainer;
  25263. })(BABYLON || (BABYLON = {}));
  25264. //# sourceMappingURL=babylon.assetContainer.js.map
  25265. var BABYLON;
  25266. (function (BABYLON) {
  25267. var Buffer = /** @class */ (function () {
  25268. function Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced) {
  25269. if (instanced === void 0) { instanced = false; }
  25270. if (engine instanceof BABYLON.Mesh) {
  25271. this._engine = engine.getScene().getEngine();
  25272. }
  25273. else {
  25274. this._engine = engine;
  25275. }
  25276. this._updatable = updatable;
  25277. this._instanced = instanced;
  25278. this._data = data;
  25279. this._strideSize = stride;
  25280. if (!postponeInternalCreation) {
  25281. this.create();
  25282. }
  25283. }
  25284. /**
  25285. * Create a new {BABYLON.VertexBuffer} based on the current buffer
  25286. * @param kind defines the vertex buffer kind (position, normal, etc.)
  25287. * @param offset defines offset in the buffer (0 by default)
  25288. * @param size defines the size in floats of attributes (position is 3 for instance)
  25289. * @param stride defines the stride size in floats in the buffer (the offset to apply to reach next value when data is interleaved)
  25290. * @param instanced defines if the vertex buffer contains indexed data
  25291. * @returns the new vertex buffer
  25292. */
  25293. Buffer.prototype.createVertexBuffer = function (kind, offset, size, stride, instanced) {
  25294. // a lot of these parameters are ignored as they are overriden by the buffer
  25295. return new BABYLON.VertexBuffer(this._engine, this, kind, this._updatable, true, stride ? stride : this._strideSize, instanced === undefined ? this._instanced : instanced, offset, size);
  25296. };
  25297. // Properties
  25298. Buffer.prototype.isUpdatable = function () {
  25299. return this._updatable;
  25300. };
  25301. Buffer.prototype.getData = function () {
  25302. return this._data;
  25303. };
  25304. Buffer.prototype.getBuffer = function () {
  25305. return this._buffer;
  25306. };
  25307. Buffer.prototype.getStrideSize = function () {
  25308. return this._strideSize;
  25309. };
  25310. // public getIsInstanced(): boolean {
  25311. // return this._instanced;
  25312. // }
  25313. // public get instanceDivisor(): number {
  25314. // return this._instanceDivisor;
  25315. // }
  25316. // public set instanceDivisor(value: number) {
  25317. // this._instanceDivisor = value;
  25318. // if (value == 0) {
  25319. // this._instanced = false;
  25320. // } else {
  25321. // this._instanced = true;
  25322. // }
  25323. // }
  25324. // Methods
  25325. Buffer.prototype.create = function (data) {
  25326. if (data === void 0) { data = null; }
  25327. if (!data && this._buffer) {
  25328. return; // nothing to do
  25329. }
  25330. data = data || this._data;
  25331. if (!data) {
  25332. return;
  25333. }
  25334. if (!this._buffer) {
  25335. if (this._updatable) {
  25336. this._buffer = this._engine.createDynamicVertexBuffer(data);
  25337. this._data = data;
  25338. }
  25339. else {
  25340. this._buffer = this._engine.createVertexBuffer(data);
  25341. }
  25342. }
  25343. else if (this._updatable) {
  25344. this._engine.updateDynamicVertexBuffer(this._buffer, data);
  25345. this._data = data;
  25346. }
  25347. };
  25348. Buffer.prototype._rebuild = function () {
  25349. this._buffer = null;
  25350. this.create(this._data);
  25351. };
  25352. Buffer.prototype.update = function (data) {
  25353. this.create(data);
  25354. };
  25355. Buffer.prototype.updateDirectly = function (data, offset, vertexCount) {
  25356. if (!this._buffer) {
  25357. return;
  25358. }
  25359. if (this._updatable) {
  25360. this._engine.updateDynamicVertexBuffer(this._buffer, data, offset, (vertexCount ? vertexCount * this.getStrideSize() : undefined));
  25361. this._data = null;
  25362. }
  25363. };
  25364. Buffer.prototype.dispose = function () {
  25365. if (!this._buffer) {
  25366. return;
  25367. }
  25368. if (this._engine._releaseBuffer(this._buffer)) {
  25369. this._buffer = null;
  25370. }
  25371. };
  25372. return Buffer;
  25373. }());
  25374. BABYLON.Buffer = Buffer;
  25375. })(BABYLON || (BABYLON = {}));
  25376. //# sourceMappingURL=babylon.buffer.js.map
  25377. var BABYLON;
  25378. (function (BABYLON) {
  25379. var VertexBuffer = /** @class */ (function () {
  25380. function VertexBuffer(engine, data, kind, updatable, postponeInternalCreation, stride, instanced, offset, size) {
  25381. if (data instanceof BABYLON.Buffer) {
  25382. if (!stride) {
  25383. stride = data.getStrideSize();
  25384. }
  25385. this._buffer = data;
  25386. this._ownsBuffer = false;
  25387. }
  25388. else {
  25389. if (!stride) {
  25390. stride = VertexBuffer.DeduceStride(kind);
  25391. }
  25392. this._buffer = new BABYLON.Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced);
  25393. this._ownsBuffer = true;
  25394. }
  25395. this._stride = stride;
  25396. this._instanced = instanced !== undefined ? instanced : false;
  25397. this._instanceDivisor = instanced ? 1 : 0;
  25398. this._offset = offset ? offset : 0;
  25399. this._size = size ? size : stride;
  25400. this._kind = kind;
  25401. }
  25402. Object.defineProperty(VertexBuffer.prototype, "instanceDivisor", {
  25403. /**
  25404. * Gets or sets the instance divisor when in instanced mode
  25405. */
  25406. get: function () {
  25407. return this._instanceDivisor;
  25408. },
  25409. set: function (value) {
  25410. this._instanceDivisor = value;
  25411. if (value == 0) {
  25412. this._instanced = false;
  25413. }
  25414. else {
  25415. this._instanced = true;
  25416. }
  25417. },
  25418. enumerable: true,
  25419. configurable: true
  25420. });
  25421. VertexBuffer.prototype._rebuild = function () {
  25422. if (!this._buffer) {
  25423. return;
  25424. }
  25425. this._buffer._rebuild();
  25426. };
  25427. /**
  25428. * Returns the kind of the VertexBuffer (string).
  25429. */
  25430. VertexBuffer.prototype.getKind = function () {
  25431. return this._kind;
  25432. };
  25433. // Properties
  25434. /**
  25435. * Boolean : is the VertexBuffer updatable ?
  25436. */
  25437. VertexBuffer.prototype.isUpdatable = function () {
  25438. return this._buffer.isUpdatable();
  25439. };
  25440. /**
  25441. * Returns an array of numbers or a Float32Array containing the VertexBuffer data.
  25442. */
  25443. VertexBuffer.prototype.getData = function () {
  25444. return this._buffer.getData();
  25445. };
  25446. /**
  25447. * Returns the WebGLBuffer associated to the VertexBuffer.
  25448. */
  25449. VertexBuffer.prototype.getBuffer = function () {
  25450. return this._buffer.getBuffer();
  25451. };
  25452. /**
  25453. * Returns the stride of the VertexBuffer (integer).
  25454. */
  25455. VertexBuffer.prototype.getStrideSize = function () {
  25456. return this._stride;
  25457. };
  25458. /**
  25459. * Returns the offset (integer).
  25460. */
  25461. VertexBuffer.prototype.getOffset = function () {
  25462. return this._offset;
  25463. };
  25464. /**
  25465. * Returns the VertexBuffer total size (integer).
  25466. */
  25467. VertexBuffer.prototype.getSize = function () {
  25468. return this._size;
  25469. };
  25470. /**
  25471. * Boolean : is the WebGLBuffer of the VertexBuffer instanced now ?
  25472. */
  25473. VertexBuffer.prototype.getIsInstanced = function () {
  25474. return this._instanced;
  25475. };
  25476. /**
  25477. * Returns the instancing divisor, zero for non-instanced (integer).
  25478. */
  25479. VertexBuffer.prototype.getInstanceDivisor = function () {
  25480. return this._instanceDivisor;
  25481. };
  25482. // Methods
  25483. /**
  25484. * Creates the underlying WebGLBuffer from the passed numeric array or Float32Array.
  25485. * Returns the created WebGLBuffer.
  25486. */
  25487. VertexBuffer.prototype.create = function (data) {
  25488. return this._buffer.create(data);
  25489. };
  25490. /**
  25491. * Updates the underlying WebGLBuffer according to the passed numeric array or Float32Array.
  25492. * This function will create a new buffer if the current one is not updatable
  25493. * Returns the updated WebGLBuffer.
  25494. */
  25495. VertexBuffer.prototype.update = function (data) {
  25496. return this._buffer.update(data);
  25497. };
  25498. /**
  25499. * Updates directly the underlying WebGLBuffer according to the passed numeric array or Float32Array.
  25500. * Returns the directly updated WebGLBuffer.
  25501. */
  25502. VertexBuffer.prototype.updateDirectly = function (data, offset) {
  25503. return this._buffer.updateDirectly(data, offset);
  25504. };
  25505. /**
  25506. * Disposes the VertexBuffer and the underlying WebGLBuffer.
  25507. */
  25508. VertexBuffer.prototype.dispose = function () {
  25509. if (this._ownsBuffer) {
  25510. this._buffer.dispose();
  25511. }
  25512. };
  25513. Object.defineProperty(VertexBuffer, "PositionKind", {
  25514. get: function () {
  25515. return VertexBuffer._PositionKind;
  25516. },
  25517. enumerable: true,
  25518. configurable: true
  25519. });
  25520. Object.defineProperty(VertexBuffer, "NormalKind", {
  25521. get: function () {
  25522. return VertexBuffer._NormalKind;
  25523. },
  25524. enumerable: true,
  25525. configurable: true
  25526. });
  25527. Object.defineProperty(VertexBuffer, "TangentKind", {
  25528. get: function () {
  25529. return VertexBuffer._TangentKind;
  25530. },
  25531. enumerable: true,
  25532. configurable: true
  25533. });
  25534. Object.defineProperty(VertexBuffer, "UVKind", {
  25535. get: function () {
  25536. return VertexBuffer._UVKind;
  25537. },
  25538. enumerable: true,
  25539. configurable: true
  25540. });
  25541. Object.defineProperty(VertexBuffer, "UV2Kind", {
  25542. get: function () {
  25543. return VertexBuffer._UV2Kind;
  25544. },
  25545. enumerable: true,
  25546. configurable: true
  25547. });
  25548. Object.defineProperty(VertexBuffer, "UV3Kind", {
  25549. get: function () {
  25550. return VertexBuffer._UV3Kind;
  25551. },
  25552. enumerable: true,
  25553. configurable: true
  25554. });
  25555. Object.defineProperty(VertexBuffer, "UV4Kind", {
  25556. get: function () {
  25557. return VertexBuffer._UV4Kind;
  25558. },
  25559. enumerable: true,
  25560. configurable: true
  25561. });
  25562. Object.defineProperty(VertexBuffer, "UV5Kind", {
  25563. get: function () {
  25564. return VertexBuffer._UV5Kind;
  25565. },
  25566. enumerable: true,
  25567. configurable: true
  25568. });
  25569. Object.defineProperty(VertexBuffer, "UV6Kind", {
  25570. get: function () {
  25571. return VertexBuffer._UV6Kind;
  25572. },
  25573. enumerable: true,
  25574. configurable: true
  25575. });
  25576. Object.defineProperty(VertexBuffer, "ColorKind", {
  25577. get: function () {
  25578. return VertexBuffer._ColorKind;
  25579. },
  25580. enumerable: true,
  25581. configurable: true
  25582. });
  25583. Object.defineProperty(VertexBuffer, "MatricesIndicesKind", {
  25584. get: function () {
  25585. return VertexBuffer._MatricesIndicesKind;
  25586. },
  25587. enumerable: true,
  25588. configurable: true
  25589. });
  25590. Object.defineProperty(VertexBuffer, "MatricesWeightsKind", {
  25591. get: function () {
  25592. return VertexBuffer._MatricesWeightsKind;
  25593. },
  25594. enumerable: true,
  25595. configurable: true
  25596. });
  25597. Object.defineProperty(VertexBuffer, "MatricesIndicesExtraKind", {
  25598. get: function () {
  25599. return VertexBuffer._MatricesIndicesExtraKind;
  25600. },
  25601. enumerable: true,
  25602. configurable: true
  25603. });
  25604. Object.defineProperty(VertexBuffer, "MatricesWeightsExtraKind", {
  25605. get: function () {
  25606. return VertexBuffer._MatricesWeightsExtraKind;
  25607. },
  25608. enumerable: true,
  25609. configurable: true
  25610. });
  25611. /**
  25612. * Deduces the stride given a kind.
  25613. * @param kind The kind string to deduce
  25614. * @returns The deduced stride
  25615. */
  25616. VertexBuffer.DeduceStride = function (kind) {
  25617. switch (kind) {
  25618. case VertexBuffer.PositionKind:
  25619. return 3;
  25620. case VertexBuffer.NormalKind:
  25621. return 3;
  25622. case VertexBuffer.UVKind:
  25623. case VertexBuffer.UV2Kind:
  25624. case VertexBuffer.UV3Kind:
  25625. case VertexBuffer.UV4Kind:
  25626. case VertexBuffer.UV5Kind:
  25627. case VertexBuffer.UV6Kind:
  25628. return 2;
  25629. case VertexBuffer.TangentKind:
  25630. case VertexBuffer.ColorKind:
  25631. return 4;
  25632. case VertexBuffer.MatricesIndicesKind:
  25633. case VertexBuffer.MatricesIndicesExtraKind:
  25634. return 4;
  25635. case VertexBuffer.MatricesWeightsKind:
  25636. case VertexBuffer.MatricesWeightsExtraKind:
  25637. return 4;
  25638. default:
  25639. throw new Error("Invalid kind '" + kind + "'");
  25640. }
  25641. };
  25642. // Enums
  25643. VertexBuffer._PositionKind = "position";
  25644. VertexBuffer._NormalKind = "normal";
  25645. VertexBuffer._TangentKind = "tangent";
  25646. VertexBuffer._UVKind = "uv";
  25647. VertexBuffer._UV2Kind = "uv2";
  25648. VertexBuffer._UV3Kind = "uv3";
  25649. VertexBuffer._UV4Kind = "uv4";
  25650. VertexBuffer._UV5Kind = "uv5";
  25651. VertexBuffer._UV6Kind = "uv6";
  25652. VertexBuffer._ColorKind = "color";
  25653. VertexBuffer._MatricesIndicesKind = "matricesIndices";
  25654. VertexBuffer._MatricesWeightsKind = "matricesWeights";
  25655. VertexBuffer._MatricesIndicesExtraKind = "matricesIndicesExtra";
  25656. VertexBuffer._MatricesWeightsExtraKind = "matricesWeightsExtra";
  25657. return VertexBuffer;
  25658. }());
  25659. BABYLON.VertexBuffer = VertexBuffer;
  25660. })(BABYLON || (BABYLON = {}));
  25661. //# sourceMappingURL=babylon.vertexBuffer.js.map
  25662. var BABYLON;
  25663. (function (BABYLON) {
  25664. /**
  25665. * Internal class used by the engine to get list of {BABYLON.InternalTexture} already bound to the GL context
  25666. */
  25667. var DummyInternalTextureTracker = /** @class */ (function () {
  25668. function DummyInternalTextureTracker() {
  25669. /**
  25670. * Gets or set the previous tracker in the list
  25671. */
  25672. this.previous = null;
  25673. /**
  25674. * Gets or set the next tracker in the list
  25675. */
  25676. this.next = null;
  25677. }
  25678. return DummyInternalTextureTracker;
  25679. }());
  25680. BABYLON.DummyInternalTextureTracker = DummyInternalTextureTracker;
  25681. })(BABYLON || (BABYLON = {}));
  25682. //# sourceMappingURL=babylon.internalTextureTracker.js.map
  25683. var BABYLON;
  25684. (function (BABYLON) {
  25685. /**
  25686. * Class used to store data associated with WebGL texture data for the engine
  25687. * This class should not be used directly
  25688. */
  25689. var InternalTexture = /** @class */ (function () {
  25690. /**
  25691. * Creates a new InternalTexture
  25692. * @param engine defines the engine to use
  25693. * @param dataSource defines the type of data that will be used
  25694. */
  25695. function InternalTexture(engine, dataSource) {
  25696. /**
  25697. * Observable called when the texture is loaded
  25698. */
  25699. this.onLoadedObservable = new BABYLON.Observable();
  25700. /**
  25701. * Gets or set the previous tracker in the list
  25702. */
  25703. this.previous = null;
  25704. /**
  25705. * Gets or set the next tracker in the list
  25706. */
  25707. this.next = null;
  25708. // Private
  25709. /** @ignore */
  25710. this._initialSlot = -1;
  25711. /** @ignore */
  25712. this._designatedSlot = -1;
  25713. /** @ignore */
  25714. this._dataSource = InternalTexture.DATASOURCE_UNKNOWN;
  25715. /** @ignore */
  25716. this._references = 1;
  25717. this._engine = engine;
  25718. this._dataSource = dataSource;
  25719. this._webGLTexture = engine._createTexture();
  25720. }
  25721. Object.defineProperty(InternalTexture.prototype, "dataSource", {
  25722. /**
  25723. * Gets the data source type of the texture (can be one of the BABYLON.InternalTexture.DATASOURCE_XXXX)
  25724. */
  25725. get: function () {
  25726. return this._dataSource;
  25727. },
  25728. enumerable: true,
  25729. configurable: true
  25730. });
  25731. /**
  25732. * Increments the number of references (ie. the number of {BABYLON.Texture} that point to it)
  25733. */
  25734. InternalTexture.prototype.incrementReferences = function () {
  25735. this._references++;
  25736. };
  25737. /**
  25738. * Change the size of the texture (not the size of the content)
  25739. * @param width defines the new width
  25740. * @param height defines the new height
  25741. * @param depth defines the new depth (1 by default)
  25742. */
  25743. InternalTexture.prototype.updateSize = function (width, height, depth) {
  25744. if (depth === void 0) { depth = 1; }
  25745. this.width = width;
  25746. this.height = height;
  25747. this.depth = depth;
  25748. this.baseWidth = width;
  25749. this.baseHeight = height;
  25750. this.baseDepth = depth;
  25751. this._size = width * height * depth;
  25752. };
  25753. /** @ignore */
  25754. InternalTexture.prototype._rebuild = function () {
  25755. var _this = this;
  25756. var proxy;
  25757. this.isReady = false;
  25758. this._cachedCoordinatesMode = null;
  25759. this._cachedWrapU = null;
  25760. this._cachedWrapV = null;
  25761. this._cachedAnisotropicFilteringLevel = null;
  25762. switch (this._dataSource) {
  25763. case InternalTexture.DATASOURCE_TEMP:
  25764. return;
  25765. case InternalTexture.DATASOURCE_URL:
  25766. proxy = this._engine.createTexture(this.url, !this.generateMipMaps, this.invertY, null, this.samplingMode, function () {
  25767. _this.isReady = true;
  25768. }, null, this._buffer, undefined, this.format);
  25769. proxy._swapAndDie(this);
  25770. return;
  25771. case InternalTexture.DATASOURCE_RAW:
  25772. proxy = this._engine.createRawTexture(this._bufferView, this.baseWidth, this.baseHeight, this.format, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  25773. proxy._swapAndDie(this);
  25774. this.isReady = true;
  25775. return;
  25776. case InternalTexture.DATASOURCE_RAW3D:
  25777. proxy = this._engine.createRawTexture3D(this._bufferView, this.baseWidth, this.baseHeight, this.baseDepth, this.format, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  25778. proxy._swapAndDie(this);
  25779. this.isReady = true;
  25780. return;
  25781. case InternalTexture.DATASOURCE_DYNAMIC:
  25782. proxy = this._engine.createDynamicTexture(this.baseWidth, this.baseHeight, this.generateMipMaps, this.samplingMode);
  25783. proxy._swapAndDie(this);
  25784. // The engine will make sure to update content so no need to flag it as isReady = true
  25785. return;
  25786. case InternalTexture.DATASOURCE_RENDERTARGET:
  25787. var options = new BABYLON.RenderTargetCreationOptions();
  25788. options.generateDepthBuffer = this._generateDepthBuffer;
  25789. options.generateMipMaps = this.generateMipMaps;
  25790. options.generateStencilBuffer = this._generateStencilBuffer;
  25791. options.samplingMode = this.samplingMode;
  25792. options.type = this.type;
  25793. if (this.isCube) {
  25794. proxy = this._engine.createRenderTargetCubeTexture(this.width, options);
  25795. }
  25796. else {
  25797. var size = {
  25798. width: this.width,
  25799. height: this.height
  25800. };
  25801. proxy = this._engine.createRenderTargetTexture(size, options);
  25802. }
  25803. proxy._swapAndDie(this);
  25804. this.isReady = true;
  25805. return;
  25806. case InternalTexture.DATASOURCE_CUBE:
  25807. proxy = this._engine.createCubeTexture(this.url, null, this._files, !this.generateMipMaps, function () {
  25808. _this.isReady = true;
  25809. }, null, this.format, this._extension);
  25810. proxy._swapAndDie(this);
  25811. return;
  25812. case InternalTexture.DATASOURCE_CUBERAW:
  25813. proxy = this._engine.createRawCubeTexture(this._bufferViewArray, this.width, this.format, this.type, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  25814. proxy._swapAndDie(this);
  25815. this.isReady = true;
  25816. return;
  25817. case InternalTexture.DATASOURCE_CUBEPREFILTERED:
  25818. proxy = this._engine.createPrefilteredCubeTexture(this.url, null, this._lodGenerationScale, this._lodGenerationOffset, function (proxy) {
  25819. if (proxy) {
  25820. proxy._swapAndDie(_this);
  25821. }
  25822. _this.isReady = true;
  25823. }, null, this.format, this._extension);
  25824. return;
  25825. }
  25826. };
  25827. InternalTexture.prototype._swapAndDie = function (target) {
  25828. target._webGLTexture = this._webGLTexture;
  25829. if (this._framebuffer) {
  25830. target._framebuffer = this._framebuffer;
  25831. }
  25832. if (this._depthStencilBuffer) {
  25833. target._depthStencilBuffer = this._depthStencilBuffer;
  25834. }
  25835. if (this._lodTextureHigh) {
  25836. if (target._lodTextureHigh) {
  25837. target._lodTextureHigh.dispose();
  25838. }
  25839. target._lodTextureHigh = this._lodTextureHigh;
  25840. }
  25841. if (this._lodTextureMid) {
  25842. if (target._lodTextureMid) {
  25843. target._lodTextureMid.dispose();
  25844. }
  25845. target._lodTextureMid = this._lodTextureMid;
  25846. }
  25847. if (this._lodTextureLow) {
  25848. if (target._lodTextureLow) {
  25849. target._lodTextureLow.dispose();
  25850. }
  25851. target._lodTextureLow = this._lodTextureLow;
  25852. }
  25853. var cache = this._engine.getLoadedTexturesCache();
  25854. var index = cache.indexOf(this);
  25855. if (index !== -1) {
  25856. cache.splice(index, 1);
  25857. }
  25858. };
  25859. /**
  25860. * Dispose the current allocated resources
  25861. */
  25862. InternalTexture.prototype.dispose = function () {
  25863. if (!this._webGLTexture) {
  25864. return;
  25865. }
  25866. this._references--;
  25867. if (this._references === 0) {
  25868. this._engine._releaseTexture(this);
  25869. this._webGLTexture = null;
  25870. this.previous = null;
  25871. this.next = null;
  25872. }
  25873. };
  25874. /**
  25875. * The source of the texture data is unknown
  25876. */
  25877. InternalTexture.DATASOURCE_UNKNOWN = 0;
  25878. /**
  25879. * Texture data comes from an URL
  25880. */
  25881. InternalTexture.DATASOURCE_URL = 1;
  25882. /**
  25883. * Texture data is only used for temporary storage
  25884. */
  25885. InternalTexture.DATASOURCE_TEMP = 2;
  25886. /**
  25887. * Texture data comes from raw data (ArrayBuffer)
  25888. */
  25889. InternalTexture.DATASOURCE_RAW = 3;
  25890. /**
  25891. * Texture content is dynamic (video or dynamic texture)
  25892. */
  25893. InternalTexture.DATASOURCE_DYNAMIC = 4;
  25894. /**
  25895. * Texture content is generated by rendering to it
  25896. */
  25897. InternalTexture.DATASOURCE_RENDERTARGET = 5;
  25898. /**
  25899. * Texture content is part of a multi render target process
  25900. */
  25901. InternalTexture.DATASOURCE_MULTIRENDERTARGET = 6;
  25902. /**
  25903. * Texture data comes from a cube data file
  25904. */
  25905. InternalTexture.DATASOURCE_CUBE = 7;
  25906. /**
  25907. * Texture data comes from a raw cube data
  25908. */
  25909. InternalTexture.DATASOURCE_CUBERAW = 8;
  25910. /**
  25911. * Texture data come from a prefiltered cube data file
  25912. */
  25913. InternalTexture.DATASOURCE_CUBEPREFILTERED = 9;
  25914. /**
  25915. * Texture content is raw 3D data
  25916. */
  25917. InternalTexture.DATASOURCE_RAW3D = 10;
  25918. return InternalTexture;
  25919. }());
  25920. BABYLON.InternalTexture = InternalTexture;
  25921. })(BABYLON || (BABYLON = {}));
  25922. //# sourceMappingURL=babylon.internalTexture.js.map
  25923. var BABYLON;
  25924. (function (BABYLON) {
  25925. var BaseTexture = /** @class */ (function () {
  25926. function BaseTexture(scene) {
  25927. this._hasAlpha = false;
  25928. this.getAlphaFromRGB = false;
  25929. this.level = 1;
  25930. this.coordinatesIndex = 0;
  25931. this._coordinatesMode = BABYLON.Texture.EXPLICIT_MODE;
  25932. /**
  25933. * | Value | Type | Description |
  25934. * | ----- | ------------------ | ----------- |
  25935. * | 0 | CLAMP_ADDRESSMODE | |
  25936. * | 1 | WRAP_ADDRESSMODE | |
  25937. * | 2 | MIRROR_ADDRESSMODE | |
  25938. */
  25939. this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  25940. /**
  25941. * | Value | Type | Description |
  25942. * | ----- | ------------------ | ----------- |
  25943. * | 0 | CLAMP_ADDRESSMODE | |
  25944. * | 1 | WRAP_ADDRESSMODE | |
  25945. * | 2 | MIRROR_ADDRESSMODE | |
  25946. */
  25947. this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  25948. /**
  25949. * | Value | Type | Description |
  25950. * | ----- | ------------------ | ----------- |
  25951. * | 0 | CLAMP_ADDRESSMODE | |
  25952. * | 1 | WRAP_ADDRESSMODE | |
  25953. * | 2 | MIRROR_ADDRESSMODE | |
  25954. */
  25955. this.wrapR = BABYLON.Texture.WRAP_ADDRESSMODE;
  25956. this.anisotropicFilteringLevel = BaseTexture.DEFAULT_ANISOTROPIC_FILTERING_LEVEL;
  25957. this.isCube = false;
  25958. this.is3D = false;
  25959. this.gammaSpace = true;
  25960. this.invertZ = false;
  25961. this.lodLevelInAlpha = false;
  25962. this.lodGenerationOffset = 0.0;
  25963. this.lodGenerationScale = 0.8;
  25964. this.isRenderTarget = false;
  25965. this.animations = new Array();
  25966. /**
  25967. * An event triggered when the texture is disposed.
  25968. * @type {BABYLON.Observable}
  25969. */
  25970. this.onDisposeObservable = new BABYLON.Observable();
  25971. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  25972. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  25973. if (this._scene) {
  25974. this._scene.textures.push(this);
  25975. }
  25976. this._uid = null;
  25977. }
  25978. Object.defineProperty(BaseTexture.prototype, "hasAlpha", {
  25979. get: function () {
  25980. return this._hasAlpha;
  25981. },
  25982. set: function (value) {
  25983. if (this._hasAlpha === value) {
  25984. return;
  25985. }
  25986. this._hasAlpha = value;
  25987. if (this._scene) {
  25988. this._scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag | BABYLON.Material.MiscDirtyFlag);
  25989. }
  25990. },
  25991. enumerable: true,
  25992. configurable: true
  25993. });
  25994. Object.defineProperty(BaseTexture.prototype, "coordinatesMode", {
  25995. get: function () {
  25996. return this._coordinatesMode;
  25997. },
  25998. /**
  25999. * How a texture is mapped.
  26000. *
  26001. * | Value | Type | Description |
  26002. * | ----- | ----------------------------------- | ----------- |
  26003. * | 0 | EXPLICIT_MODE | |
  26004. * | 1 | SPHERICAL_MODE | |
  26005. * | 2 | PLANAR_MODE | |
  26006. * | 3 | CUBIC_MODE | |
  26007. * | 4 | PROJECTION_MODE | |
  26008. * | 5 | SKYBOX_MODE | |
  26009. * | 6 | INVCUBIC_MODE | |
  26010. * | 7 | EQUIRECTANGULAR_MODE | |
  26011. * | 8 | FIXED_EQUIRECTANGULAR_MODE | |
  26012. * | 9 | FIXED_EQUIRECTANGULAR_MIRRORED_MODE | |
  26013. */
  26014. set: function (value) {
  26015. if (this._coordinatesMode === value) {
  26016. return;
  26017. }
  26018. this._coordinatesMode = value;
  26019. if (this._scene) {
  26020. this._scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  26021. }
  26022. },
  26023. enumerable: true,
  26024. configurable: true
  26025. });
  26026. Object.defineProperty(BaseTexture.prototype, "uid", {
  26027. get: function () {
  26028. if (!this._uid) {
  26029. this._uid = BABYLON.Tools.RandomId();
  26030. }
  26031. return this._uid;
  26032. },
  26033. enumerable: true,
  26034. configurable: true
  26035. });
  26036. BaseTexture.prototype.toString = function () {
  26037. return this.name;
  26038. };
  26039. BaseTexture.prototype.getClassName = function () {
  26040. return "BaseTexture";
  26041. };
  26042. Object.defineProperty(BaseTexture.prototype, "onDispose", {
  26043. set: function (callback) {
  26044. if (this._onDisposeObserver) {
  26045. this.onDisposeObservable.remove(this._onDisposeObserver);
  26046. }
  26047. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  26048. },
  26049. enumerable: true,
  26050. configurable: true
  26051. });
  26052. Object.defineProperty(BaseTexture.prototype, "isBlocking", {
  26053. get: function () {
  26054. return true;
  26055. },
  26056. enumerable: true,
  26057. configurable: true
  26058. });
  26059. BaseTexture.prototype.getScene = function () {
  26060. return this._scene;
  26061. };
  26062. BaseTexture.prototype.getTextureMatrix = function () {
  26063. return BABYLON.Matrix.IdentityReadOnly;
  26064. };
  26065. BaseTexture.prototype.getReflectionTextureMatrix = function () {
  26066. return BABYLON.Matrix.IdentityReadOnly;
  26067. };
  26068. BaseTexture.prototype.getInternalTexture = function () {
  26069. return this._texture;
  26070. };
  26071. BaseTexture.prototype.isReadyOrNotBlocking = function () {
  26072. return !this.isBlocking || this.isReady();
  26073. };
  26074. BaseTexture.prototype.isReady = function () {
  26075. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  26076. this.delayLoad();
  26077. return false;
  26078. }
  26079. if (this._texture) {
  26080. return this._texture.isReady;
  26081. }
  26082. return false;
  26083. };
  26084. BaseTexture.prototype.getSize = function () {
  26085. if (this._texture && this._texture.width) {
  26086. return new BABYLON.Size(this._texture.width, this._texture.height);
  26087. }
  26088. if (this._texture && this._texture._size) {
  26089. return new BABYLON.Size(this._texture._size, this._texture._size);
  26090. }
  26091. return BABYLON.Size.Zero();
  26092. };
  26093. BaseTexture.prototype.getBaseSize = function () {
  26094. if (!this.isReady() || !this._texture)
  26095. return BABYLON.Size.Zero();
  26096. if (this._texture._size) {
  26097. return new BABYLON.Size(this._texture._size, this._texture._size);
  26098. }
  26099. return new BABYLON.Size(this._texture.baseWidth, this._texture.baseHeight);
  26100. };
  26101. BaseTexture.prototype.scale = function (ratio) {
  26102. };
  26103. Object.defineProperty(BaseTexture.prototype, "canRescale", {
  26104. get: function () {
  26105. return false;
  26106. },
  26107. enumerable: true,
  26108. configurable: true
  26109. });
  26110. BaseTexture.prototype._getFromCache = function (url, noMipmap, sampling) {
  26111. if (!this._scene) {
  26112. return null;
  26113. }
  26114. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  26115. for (var index = 0; index < texturesCache.length; index++) {
  26116. var texturesCacheEntry = texturesCache[index];
  26117. if (texturesCacheEntry.url === url && texturesCacheEntry.generateMipMaps === !noMipmap) {
  26118. if (!sampling || sampling === texturesCacheEntry.samplingMode) {
  26119. texturesCacheEntry.incrementReferences();
  26120. return texturesCacheEntry;
  26121. }
  26122. }
  26123. }
  26124. return null;
  26125. };
  26126. BaseTexture.prototype._rebuild = function () {
  26127. };
  26128. BaseTexture.prototype.delayLoad = function () {
  26129. };
  26130. BaseTexture.prototype.clone = function () {
  26131. return null;
  26132. };
  26133. Object.defineProperty(BaseTexture.prototype, "textureType", {
  26134. get: function () {
  26135. if (!this._texture) {
  26136. return BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  26137. }
  26138. return (this._texture.type !== undefined) ? this._texture.type : BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  26139. },
  26140. enumerable: true,
  26141. configurable: true
  26142. });
  26143. Object.defineProperty(BaseTexture.prototype, "textureFormat", {
  26144. get: function () {
  26145. if (!this._texture) {
  26146. return BABYLON.Engine.TEXTUREFORMAT_RGBA;
  26147. }
  26148. return (this._texture.format !== undefined) ? this._texture.format : BABYLON.Engine.TEXTUREFORMAT_RGBA;
  26149. },
  26150. enumerable: true,
  26151. configurable: true
  26152. });
  26153. BaseTexture.prototype.readPixels = function (faceIndex) {
  26154. if (faceIndex === void 0) { faceIndex = 0; }
  26155. if (!this._texture) {
  26156. return null;
  26157. }
  26158. var size = this.getSize();
  26159. var scene = this.getScene();
  26160. if (!scene) {
  26161. return null;
  26162. }
  26163. var engine = scene.getEngine();
  26164. if (this._texture.isCube) {
  26165. return engine._readTexturePixels(this._texture, size.width, size.height, faceIndex);
  26166. }
  26167. return engine._readTexturePixels(this._texture, size.width, size.height, -1);
  26168. };
  26169. BaseTexture.prototype.releaseInternalTexture = function () {
  26170. if (this._texture) {
  26171. this._texture.dispose();
  26172. this._texture = null;
  26173. }
  26174. };
  26175. Object.defineProperty(BaseTexture.prototype, "sphericalPolynomial", {
  26176. get: function () {
  26177. if (!this._texture || !BABYLON.CubeMapToSphericalPolynomialTools || !this.isReady()) {
  26178. return null;
  26179. }
  26180. if (!this._texture._sphericalPolynomial) {
  26181. this._texture._sphericalPolynomial =
  26182. BABYLON.CubeMapToSphericalPolynomialTools.ConvertCubeMapTextureToSphericalPolynomial(this);
  26183. }
  26184. return this._texture._sphericalPolynomial;
  26185. },
  26186. set: function (value) {
  26187. if (this._texture) {
  26188. this._texture._sphericalPolynomial = value;
  26189. }
  26190. },
  26191. enumerable: true,
  26192. configurable: true
  26193. });
  26194. Object.defineProperty(BaseTexture.prototype, "_lodTextureHigh", {
  26195. get: function () {
  26196. if (this._texture) {
  26197. return this._texture._lodTextureHigh;
  26198. }
  26199. return null;
  26200. },
  26201. enumerable: true,
  26202. configurable: true
  26203. });
  26204. Object.defineProperty(BaseTexture.prototype, "_lodTextureMid", {
  26205. get: function () {
  26206. if (this._texture) {
  26207. return this._texture._lodTextureMid;
  26208. }
  26209. return null;
  26210. },
  26211. enumerable: true,
  26212. configurable: true
  26213. });
  26214. Object.defineProperty(BaseTexture.prototype, "_lodTextureLow", {
  26215. get: function () {
  26216. if (this._texture) {
  26217. return this._texture._lodTextureLow;
  26218. }
  26219. return null;
  26220. },
  26221. enumerable: true,
  26222. configurable: true
  26223. });
  26224. BaseTexture.prototype.dispose = function () {
  26225. if (!this._scene) {
  26226. return;
  26227. }
  26228. // Animations
  26229. this._scene.stopAnimation(this);
  26230. // Remove from scene
  26231. this._scene._removePendingData(this);
  26232. var index = this._scene.textures.indexOf(this);
  26233. if (index >= 0) {
  26234. this._scene.textures.splice(index, 1);
  26235. }
  26236. if (this._texture === undefined) {
  26237. return;
  26238. }
  26239. // Release
  26240. this.releaseInternalTexture();
  26241. // Callback
  26242. this.onDisposeObservable.notifyObservers(this);
  26243. this.onDisposeObservable.clear();
  26244. };
  26245. BaseTexture.prototype.serialize = function () {
  26246. if (!this.name) {
  26247. return null;
  26248. }
  26249. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  26250. // Animations
  26251. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  26252. return serializationObject;
  26253. };
  26254. BaseTexture.WhenAllReady = function (textures, callback) {
  26255. var numRemaining = textures.length;
  26256. if (numRemaining === 0) {
  26257. callback();
  26258. return;
  26259. }
  26260. var _loop_1 = function () {
  26261. texture = textures[i];
  26262. if (texture.isReady()) {
  26263. if (--numRemaining === 0) {
  26264. callback();
  26265. }
  26266. }
  26267. else {
  26268. onLoadObservable = texture.onLoadObservable;
  26269. var onLoadCallback_1 = function () {
  26270. onLoadObservable.removeCallback(onLoadCallback_1);
  26271. if (--numRemaining === 0) {
  26272. callback();
  26273. }
  26274. };
  26275. onLoadObservable.add(onLoadCallback_1);
  26276. }
  26277. };
  26278. var texture, onLoadObservable;
  26279. for (var i = 0; i < textures.length; i++) {
  26280. _loop_1();
  26281. }
  26282. };
  26283. BaseTexture.DEFAULT_ANISOTROPIC_FILTERING_LEVEL = 4;
  26284. __decorate([
  26285. BABYLON.serialize()
  26286. ], BaseTexture.prototype, "name", void 0);
  26287. __decorate([
  26288. BABYLON.serialize("hasAlpha")
  26289. ], BaseTexture.prototype, "_hasAlpha", void 0);
  26290. __decorate([
  26291. BABYLON.serialize()
  26292. ], BaseTexture.prototype, "getAlphaFromRGB", void 0);
  26293. __decorate([
  26294. BABYLON.serialize()
  26295. ], BaseTexture.prototype, "level", void 0);
  26296. __decorate([
  26297. BABYLON.serialize()
  26298. ], BaseTexture.prototype, "coordinatesIndex", void 0);
  26299. __decorate([
  26300. BABYLON.serialize("coordinatesMode")
  26301. ], BaseTexture.prototype, "_coordinatesMode", void 0);
  26302. __decorate([
  26303. BABYLON.serialize()
  26304. ], BaseTexture.prototype, "wrapU", void 0);
  26305. __decorate([
  26306. BABYLON.serialize()
  26307. ], BaseTexture.prototype, "wrapV", void 0);
  26308. __decorate([
  26309. BABYLON.serialize()
  26310. ], BaseTexture.prototype, "wrapR", void 0);
  26311. __decorate([
  26312. BABYLON.serialize()
  26313. ], BaseTexture.prototype, "anisotropicFilteringLevel", void 0);
  26314. __decorate([
  26315. BABYLON.serialize()
  26316. ], BaseTexture.prototype, "isCube", void 0);
  26317. __decorate([
  26318. BABYLON.serialize()
  26319. ], BaseTexture.prototype, "is3D", void 0);
  26320. __decorate([
  26321. BABYLON.serialize()
  26322. ], BaseTexture.prototype, "gammaSpace", void 0);
  26323. __decorate([
  26324. BABYLON.serialize()
  26325. ], BaseTexture.prototype, "invertZ", void 0);
  26326. __decorate([
  26327. BABYLON.serialize()
  26328. ], BaseTexture.prototype, "lodLevelInAlpha", void 0);
  26329. __decorate([
  26330. BABYLON.serialize()
  26331. ], BaseTexture.prototype, "lodGenerationOffset", void 0);
  26332. __decorate([
  26333. BABYLON.serialize()
  26334. ], BaseTexture.prototype, "lodGenerationScale", void 0);
  26335. __decorate([
  26336. BABYLON.serialize()
  26337. ], BaseTexture.prototype, "isRenderTarget", void 0);
  26338. return BaseTexture;
  26339. }());
  26340. BABYLON.BaseTexture = BaseTexture;
  26341. })(BABYLON || (BABYLON = {}));
  26342. //# sourceMappingURL=babylon.baseTexture.js.map
  26343. var BABYLON;
  26344. (function (BABYLON) {
  26345. var Texture = /** @class */ (function (_super) {
  26346. __extends(Texture, _super);
  26347. function Texture(url, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer, format) {
  26348. if (noMipmap === void 0) { noMipmap = false; }
  26349. if (invertY === void 0) { invertY = true; }
  26350. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  26351. if (onLoad === void 0) { onLoad = null; }
  26352. if (onError === void 0) { onError = null; }
  26353. if (buffer === void 0) { buffer = null; }
  26354. if (deleteBuffer === void 0) { deleteBuffer = false; }
  26355. var _this = _super.call(this, scene) || this;
  26356. _this.uOffset = 0;
  26357. _this.vOffset = 0;
  26358. _this.uScale = 1.0;
  26359. _this.vScale = 1.0;
  26360. _this.uAng = 0;
  26361. _this.vAng = 0;
  26362. _this.wAng = 0;
  26363. _this._isBlocking = true;
  26364. _this.name = url || "";
  26365. _this.url = url;
  26366. _this._noMipmap = noMipmap;
  26367. _this._invertY = invertY;
  26368. _this._samplingMode = samplingMode;
  26369. _this._buffer = buffer;
  26370. _this._deleteBuffer = deleteBuffer;
  26371. if (format) {
  26372. _this._format = format;
  26373. }
  26374. scene = _this.getScene();
  26375. if (!scene) {
  26376. return _this;
  26377. }
  26378. scene.getEngine().onBeforeTextureInitObservable.notifyObservers(_this);
  26379. var load = function () {
  26380. if (_this._onLoadObservable && _this._onLoadObservable.hasObservers()) {
  26381. _this.onLoadObservable.notifyObservers(_this);
  26382. }
  26383. if (onLoad) {
  26384. onLoad();
  26385. }
  26386. if (!_this.isBlocking && scene) {
  26387. scene.resetCachedMaterial();
  26388. }
  26389. };
  26390. if (!_this.url) {
  26391. _this._delayedOnLoad = load;
  26392. _this._delayedOnError = onError;
  26393. return _this;
  26394. }
  26395. _this._texture = _this._getFromCache(_this.url, noMipmap, samplingMode);
  26396. if (!_this._texture) {
  26397. if (!scene.useDelayedTextureLoading) {
  26398. _this._texture = scene.getEngine().createTexture(_this.url, noMipmap, invertY, scene, _this._samplingMode, load, onError, _this._buffer, undefined, _this._format);
  26399. if (deleteBuffer) {
  26400. delete _this._buffer;
  26401. }
  26402. }
  26403. else {
  26404. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  26405. _this._delayedOnLoad = load;
  26406. _this._delayedOnError = onError;
  26407. }
  26408. }
  26409. else {
  26410. if (_this._texture.isReady) {
  26411. BABYLON.Tools.SetImmediate(function () { return load(); });
  26412. }
  26413. else {
  26414. _this._texture.onLoadedObservable.add(load);
  26415. }
  26416. }
  26417. return _this;
  26418. }
  26419. Object.defineProperty(Texture.prototype, "noMipmap", {
  26420. get: function () {
  26421. return this._noMipmap;
  26422. },
  26423. enumerable: true,
  26424. configurable: true
  26425. });
  26426. Object.defineProperty(Texture.prototype, "isBlocking", {
  26427. get: function () {
  26428. return this._isBlocking;
  26429. },
  26430. set: function (value) {
  26431. this._isBlocking = value;
  26432. },
  26433. enumerable: true,
  26434. configurable: true
  26435. });
  26436. Object.defineProperty(Texture.prototype, "samplingMode", {
  26437. get: function () {
  26438. return this._samplingMode;
  26439. },
  26440. enumerable: true,
  26441. configurable: true
  26442. });
  26443. Texture.prototype.updateURL = function (url) {
  26444. this.url = url;
  26445. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  26446. this.delayLoad();
  26447. };
  26448. Texture.prototype.delayLoad = function () {
  26449. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  26450. return;
  26451. }
  26452. var scene = this.getScene();
  26453. if (!scene) {
  26454. return;
  26455. }
  26456. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  26457. this._texture = this._getFromCache(this.url, this._noMipmap, this._samplingMode);
  26458. if (!this._texture) {
  26459. this._texture = scene.getEngine().createTexture(this.url, this._noMipmap, this._invertY, scene, this._samplingMode, this._delayedOnLoad, this._delayedOnError, this._buffer, null, this._format);
  26460. if (this._deleteBuffer) {
  26461. delete this._buffer;
  26462. }
  26463. }
  26464. else {
  26465. if (this._delayedOnLoad) {
  26466. if (this._texture.isReady) {
  26467. BABYLON.Tools.SetImmediate(this._delayedOnLoad);
  26468. }
  26469. else {
  26470. this._texture.onLoadedObservable.add(this._delayedOnLoad);
  26471. }
  26472. }
  26473. }
  26474. this._delayedOnLoad = null;
  26475. this._delayedOnError = null;
  26476. };
  26477. Texture.prototype.updateSamplingMode = function (samplingMode) {
  26478. if (!this._texture) {
  26479. return;
  26480. }
  26481. var scene = this.getScene();
  26482. if (!scene) {
  26483. return;
  26484. }
  26485. this._samplingMode = samplingMode;
  26486. scene.getEngine().updateTextureSamplingMode(samplingMode, this._texture);
  26487. };
  26488. Texture.prototype._prepareRowForTextureGeneration = function (x, y, z, t) {
  26489. x *= this.uScale;
  26490. y *= this.vScale;
  26491. x -= 0.5 * this.uScale;
  26492. y -= 0.5 * this.vScale;
  26493. z -= 0.5;
  26494. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, this._rowGenerationMatrix, t);
  26495. t.x += 0.5 * this.uScale + this.uOffset;
  26496. t.y += 0.5 * this.vScale + this.vOffset;
  26497. t.z += 0.5;
  26498. };
  26499. Texture.prototype.getTextureMatrix = function () {
  26500. var _this = this;
  26501. if (this.uOffset === this._cachedUOffset &&
  26502. this.vOffset === this._cachedVOffset &&
  26503. this.uScale === this._cachedUScale &&
  26504. this.vScale === this._cachedVScale &&
  26505. this.uAng === this._cachedUAng &&
  26506. this.vAng === this._cachedVAng &&
  26507. this.wAng === this._cachedWAng) {
  26508. return this._cachedTextureMatrix;
  26509. }
  26510. this._cachedUOffset = this.uOffset;
  26511. this._cachedVOffset = this.vOffset;
  26512. this._cachedUScale = this.uScale;
  26513. this._cachedVScale = this.vScale;
  26514. this._cachedUAng = this.uAng;
  26515. this._cachedVAng = this.vAng;
  26516. this._cachedWAng = this.wAng;
  26517. if (!this._cachedTextureMatrix) {
  26518. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  26519. this._rowGenerationMatrix = new BABYLON.Matrix();
  26520. this._t0 = BABYLON.Vector3.Zero();
  26521. this._t1 = BABYLON.Vector3.Zero();
  26522. this._t2 = BABYLON.Vector3.Zero();
  26523. }
  26524. BABYLON.Matrix.RotationYawPitchRollToRef(this.vAng, this.uAng, this.wAng, this._rowGenerationMatrix);
  26525. this._prepareRowForTextureGeneration(0, 0, 0, this._t0);
  26526. this._prepareRowForTextureGeneration(1.0, 0, 0, this._t1);
  26527. this._prepareRowForTextureGeneration(0, 1.0, 0, this._t2);
  26528. this._t1.subtractInPlace(this._t0);
  26529. this._t2.subtractInPlace(this._t0);
  26530. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  26531. this._cachedTextureMatrix.m[0] = this._t1.x;
  26532. this._cachedTextureMatrix.m[1] = this._t1.y;
  26533. this._cachedTextureMatrix.m[2] = this._t1.z;
  26534. this._cachedTextureMatrix.m[4] = this._t2.x;
  26535. this._cachedTextureMatrix.m[5] = this._t2.y;
  26536. this._cachedTextureMatrix.m[6] = this._t2.z;
  26537. this._cachedTextureMatrix.m[8] = this._t0.x;
  26538. this._cachedTextureMatrix.m[9] = this._t0.y;
  26539. this._cachedTextureMatrix.m[10] = this._t0.z;
  26540. var scene = this.getScene();
  26541. if (!scene) {
  26542. return this._cachedTextureMatrix;
  26543. }
  26544. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag, function (mat) {
  26545. return mat.hasTexture(_this);
  26546. });
  26547. return this._cachedTextureMatrix;
  26548. };
  26549. Texture.prototype.getReflectionTextureMatrix = function () {
  26550. var _this = this;
  26551. var scene = this.getScene();
  26552. if (!scene) {
  26553. return this._cachedTextureMatrix;
  26554. }
  26555. if (this.uOffset === this._cachedUOffset &&
  26556. this.vOffset === this._cachedVOffset &&
  26557. this.uScale === this._cachedUScale &&
  26558. this.vScale === this._cachedVScale &&
  26559. this.coordinatesMode === this._cachedCoordinatesMode) {
  26560. if (this.coordinatesMode === Texture.PROJECTION_MODE) {
  26561. if (this._cachedProjectionMatrixId === scene.getProjectionMatrix().updateFlag) {
  26562. return this._cachedTextureMatrix;
  26563. }
  26564. }
  26565. else {
  26566. return this._cachedTextureMatrix;
  26567. }
  26568. }
  26569. if (!this._cachedTextureMatrix) {
  26570. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  26571. }
  26572. if (!this._projectionModeMatrix) {
  26573. this._projectionModeMatrix = BABYLON.Matrix.Zero();
  26574. }
  26575. this._cachedUOffset = this.uOffset;
  26576. this._cachedVOffset = this.vOffset;
  26577. this._cachedUScale = this.uScale;
  26578. this._cachedVScale = this.vScale;
  26579. this._cachedCoordinatesMode = this.coordinatesMode;
  26580. switch (this.coordinatesMode) {
  26581. case Texture.PLANAR_MODE:
  26582. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  26583. this._cachedTextureMatrix[0] = this.uScale;
  26584. this._cachedTextureMatrix[5] = this.vScale;
  26585. this._cachedTextureMatrix[12] = this.uOffset;
  26586. this._cachedTextureMatrix[13] = this.vOffset;
  26587. break;
  26588. case Texture.PROJECTION_MODE:
  26589. BABYLON.Matrix.IdentityToRef(this._projectionModeMatrix);
  26590. this._projectionModeMatrix.m[0] = 0.5;
  26591. this._projectionModeMatrix.m[5] = -0.5;
  26592. this._projectionModeMatrix.m[10] = 0.0;
  26593. this._projectionModeMatrix.m[12] = 0.5;
  26594. this._projectionModeMatrix.m[13] = 0.5;
  26595. this._projectionModeMatrix.m[14] = 1.0;
  26596. this._projectionModeMatrix.m[15] = 1.0;
  26597. var projectionMatrix = scene.getProjectionMatrix();
  26598. this._cachedProjectionMatrixId = projectionMatrix.updateFlag;
  26599. projectionMatrix.multiplyToRef(this._projectionModeMatrix, this._cachedTextureMatrix);
  26600. break;
  26601. default:
  26602. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  26603. break;
  26604. }
  26605. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag, function (mat) {
  26606. return (mat.getActiveTextures().indexOf(_this) !== -1);
  26607. });
  26608. return this._cachedTextureMatrix;
  26609. };
  26610. Texture.prototype.clone = function () {
  26611. var _this = this;
  26612. return BABYLON.SerializationHelper.Clone(function () {
  26613. return new Texture(_this._texture ? _this._texture.url : null, _this.getScene(), _this._noMipmap, _this._invertY, _this._samplingMode);
  26614. }, this);
  26615. };
  26616. Object.defineProperty(Texture.prototype, "onLoadObservable", {
  26617. get: function () {
  26618. if (!this._onLoadObservable) {
  26619. this._onLoadObservable = new BABYLON.Observable();
  26620. }
  26621. return this._onLoadObservable;
  26622. },
  26623. enumerable: true,
  26624. configurable: true
  26625. });
  26626. Texture.prototype.serialize = function () {
  26627. var serializationObject = _super.prototype.serialize.call(this);
  26628. if (typeof this._buffer === "string" && this._buffer.substr(0, 5) === "data:") {
  26629. serializationObject.base64String = this._buffer;
  26630. serializationObject.name = serializationObject.name.replace("data:", "");
  26631. }
  26632. return serializationObject;
  26633. };
  26634. Texture.prototype.getClassName = function () {
  26635. return "Texture";
  26636. };
  26637. Texture.prototype.dispose = function () {
  26638. _super.prototype.dispose.call(this);
  26639. if (this.onLoadObservable) {
  26640. this.onLoadObservable.clear();
  26641. this._onLoadObservable = null;
  26642. }
  26643. this._delayedOnLoad = null;
  26644. this._delayedOnError = null;
  26645. };
  26646. // Statics
  26647. Texture.CreateFromBase64String = function (data, name, scene, noMipmap, invertY, samplingMode, onLoad, onError, format) {
  26648. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  26649. if (onLoad === void 0) { onLoad = null; }
  26650. if (onError === void 0) { onError = null; }
  26651. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  26652. return new Texture("data:" + name, scene, noMipmap, invertY, samplingMode, onLoad, onError, data, false, format);
  26653. };
  26654. Texture.Parse = function (parsedTexture, scene, rootUrl) {
  26655. if (parsedTexture.customType) {
  26656. var customTexture = BABYLON.Tools.Instantiate(parsedTexture.customType);
  26657. // Update Sampling Mode
  26658. var parsedCustomTexture = customTexture.Parse(parsedTexture, scene, rootUrl);
  26659. if (parsedTexture.samplingMode && parsedCustomTexture.updateSamplingMode && parsedCustomTexture._samplingMode) {
  26660. if (parsedCustomTexture._samplingMode !== parsedTexture.samplingMode) {
  26661. parsedCustomTexture.updateSamplingMode(parsedTexture.samplingMode);
  26662. }
  26663. }
  26664. return parsedCustomTexture;
  26665. }
  26666. if (parsedTexture.isCube) {
  26667. return BABYLON.CubeTexture.Parse(parsedTexture, scene, rootUrl);
  26668. }
  26669. if (!parsedTexture.name && !parsedTexture.isRenderTarget) {
  26670. return null;
  26671. }
  26672. var texture = BABYLON.SerializationHelper.Parse(function () {
  26673. var generateMipMaps = true;
  26674. if (parsedTexture.noMipmap) {
  26675. generateMipMaps = false;
  26676. }
  26677. if (parsedTexture.mirrorPlane) {
  26678. var mirrorTexture = new BABYLON.MirrorTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene, generateMipMaps);
  26679. mirrorTexture._waitingRenderList = parsedTexture.renderList;
  26680. mirrorTexture.mirrorPlane = BABYLON.Plane.FromArray(parsedTexture.mirrorPlane);
  26681. return mirrorTexture;
  26682. }
  26683. else if (parsedTexture.isRenderTarget) {
  26684. var renderTargetTexture = new BABYLON.RenderTargetTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene, generateMipMaps);
  26685. renderTargetTexture._waitingRenderList = parsedTexture.renderList;
  26686. return renderTargetTexture;
  26687. }
  26688. else {
  26689. var texture;
  26690. if (parsedTexture.base64String) {
  26691. texture = Texture.CreateFromBase64String(parsedTexture.base64String, parsedTexture.name, scene, !generateMipMaps);
  26692. }
  26693. else {
  26694. texture = new Texture(rootUrl + parsedTexture.name, scene, !generateMipMaps);
  26695. }
  26696. return texture;
  26697. }
  26698. }, parsedTexture, scene);
  26699. // Update Sampling Mode
  26700. if (parsedTexture.samplingMode) {
  26701. var sampling = parsedTexture.samplingMode;
  26702. if (texture._samplingMode !== sampling) {
  26703. texture.updateSamplingMode(sampling);
  26704. }
  26705. }
  26706. // Animations
  26707. if (parsedTexture.animations) {
  26708. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  26709. var parsedAnimation = parsedTexture.animations[animationIndex];
  26710. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  26711. }
  26712. }
  26713. return texture;
  26714. };
  26715. Texture.LoadFromDataString = function (name, buffer, scene, deleteBuffer, noMipmap, invertY, samplingMode, onLoad, onError, format) {
  26716. if (deleteBuffer === void 0) { deleteBuffer = false; }
  26717. if (noMipmap === void 0) { noMipmap = false; }
  26718. if (invertY === void 0) { invertY = true; }
  26719. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  26720. if (onLoad === void 0) { onLoad = null; }
  26721. if (onError === void 0) { onError = null; }
  26722. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  26723. if (name.substr(0, 5) !== "data:") {
  26724. name = "data:" + name;
  26725. }
  26726. return new Texture(name, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer, format);
  26727. };
  26728. // Constants
  26729. Texture.NEAREST_SAMPLINGMODE = 1;
  26730. Texture.NEAREST_NEAREST_MIPLINEAR = 1; // nearest is mag = nearest and min = nearest and mip = linear
  26731. Texture.BILINEAR_SAMPLINGMODE = 2;
  26732. Texture.LINEAR_LINEAR_MIPNEAREST = 2; // Bilinear is mag = linear and min = linear and mip = nearest
  26733. Texture.TRILINEAR_SAMPLINGMODE = 3;
  26734. Texture.LINEAR_LINEAR_MIPLINEAR = 3; // Trilinear is mag = linear and min = linear and mip = linear
  26735. Texture.NEAREST_NEAREST_MIPNEAREST = 4;
  26736. Texture.NEAREST_LINEAR_MIPNEAREST = 5;
  26737. Texture.NEAREST_LINEAR_MIPLINEAR = 6;
  26738. Texture.NEAREST_LINEAR = 7;
  26739. Texture.NEAREST_NEAREST = 8;
  26740. Texture.LINEAR_NEAREST_MIPNEAREST = 9;
  26741. Texture.LINEAR_NEAREST_MIPLINEAR = 10;
  26742. Texture.LINEAR_LINEAR = 11;
  26743. Texture.LINEAR_NEAREST = 12;
  26744. Texture.EXPLICIT_MODE = 0;
  26745. Texture.SPHERICAL_MODE = 1;
  26746. Texture.PLANAR_MODE = 2;
  26747. Texture.CUBIC_MODE = 3;
  26748. Texture.PROJECTION_MODE = 4;
  26749. Texture.SKYBOX_MODE = 5;
  26750. Texture.INVCUBIC_MODE = 6;
  26751. Texture.EQUIRECTANGULAR_MODE = 7;
  26752. Texture.FIXED_EQUIRECTANGULAR_MODE = 8;
  26753. Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE = 9;
  26754. Texture.CLAMP_ADDRESSMODE = 0;
  26755. Texture.WRAP_ADDRESSMODE = 1;
  26756. Texture.MIRROR_ADDRESSMODE = 2;
  26757. __decorate([
  26758. BABYLON.serialize()
  26759. ], Texture.prototype, "url", void 0);
  26760. __decorate([
  26761. BABYLON.serialize()
  26762. ], Texture.prototype, "uOffset", void 0);
  26763. __decorate([
  26764. BABYLON.serialize()
  26765. ], Texture.prototype, "vOffset", void 0);
  26766. __decorate([
  26767. BABYLON.serialize()
  26768. ], Texture.prototype, "uScale", void 0);
  26769. __decorate([
  26770. BABYLON.serialize()
  26771. ], Texture.prototype, "vScale", void 0);
  26772. __decorate([
  26773. BABYLON.serialize()
  26774. ], Texture.prototype, "uAng", void 0);
  26775. __decorate([
  26776. BABYLON.serialize()
  26777. ], Texture.prototype, "vAng", void 0);
  26778. __decorate([
  26779. BABYLON.serialize()
  26780. ], Texture.prototype, "wAng", void 0);
  26781. __decorate([
  26782. BABYLON.serialize()
  26783. ], Texture.prototype, "isBlocking", null);
  26784. return Texture;
  26785. }(BABYLON.BaseTexture));
  26786. BABYLON.Texture = Texture;
  26787. })(BABYLON || (BABYLON = {}));
  26788. //# sourceMappingURL=babylon.texture.js.map
  26789. var BABYLON;
  26790. (function (BABYLON) {
  26791. var _InstancesBatch = /** @class */ (function () {
  26792. function _InstancesBatch() {
  26793. this.mustReturn = false;
  26794. this.visibleInstances = new Array();
  26795. this.renderSelf = new Array();
  26796. }
  26797. return _InstancesBatch;
  26798. }());
  26799. BABYLON._InstancesBatch = _InstancesBatch;
  26800. var Mesh = /** @class */ (function (_super) {
  26801. __extends(Mesh, _super);
  26802. /**
  26803. * @constructor
  26804. * @param {string} name The value used by scene.getMeshByName() to do a lookup.
  26805. * @param {Scene} scene The scene to add this mesh to.
  26806. * @param {Node} parent The parent of this mesh, if it has one
  26807. * @param {Mesh} source An optional Mesh from which geometry is shared, cloned.
  26808. * @param {boolean} doNotCloneChildren When cloning, skip cloning child meshes of source, default False.
  26809. * When false, achieved by calling a clone(), also passing False.
  26810. * This will make creation of children, recursive.
  26811. * @param {boolean} clonePhysicsImpostor When cloning, include cloning mesh physics impostor, default True.
  26812. */
  26813. function Mesh(name, scene, parent, source, doNotCloneChildren, clonePhysicsImpostor) {
  26814. if (scene === void 0) { scene = null; }
  26815. if (parent === void 0) { parent = null; }
  26816. if (source === void 0) { source = null; }
  26817. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  26818. var _this = _super.call(this, name, scene) || this;
  26819. // Events
  26820. /**
  26821. * An event triggered before rendering the mesh
  26822. * @type {BABYLON.Observable}
  26823. */
  26824. _this.onBeforeRenderObservable = new BABYLON.Observable();
  26825. /**
  26826. * An event triggered after rendering the mesh
  26827. * @type {BABYLON.Observable}
  26828. */
  26829. _this.onAfterRenderObservable = new BABYLON.Observable();
  26830. /**
  26831. * An event triggered before drawing the mesh
  26832. * @type {BABYLON.Observable}
  26833. */
  26834. _this.onBeforeDrawObservable = new BABYLON.Observable();
  26835. // Members
  26836. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  26837. _this.instances = new Array();
  26838. _this._LODLevels = new Array();
  26839. _this._visibleInstances = {};
  26840. _this._renderIdForInstances = new Array();
  26841. _this._batchCache = new _InstancesBatch();
  26842. _this._instancesBufferSize = 32 * 16 * 4; // let's start with a maximum of 32 instances
  26843. // Use by builder only to know what orientation were the mesh build in.
  26844. _this._originalBuilderSideOrientation = Mesh._DEFAULTSIDE;
  26845. _this.overrideMaterialSideOrientation = null;
  26846. _this._areNormalsFrozen = false; // Will be used by ribbons mainly
  26847. // Will be used to save a source mesh reference, If any
  26848. _this._source = null;
  26849. scene = _this.getScene();
  26850. if (source) {
  26851. // Source mesh
  26852. _this._source = source;
  26853. // Geometry
  26854. if (source._geometry) {
  26855. source._geometry.applyToMesh(_this);
  26856. }
  26857. // Deep copy
  26858. BABYLON.Tools.DeepCopy(source, _this, ["name", "material", "skeleton", "instances", "parent", "uniqueId", "source", "metadata"], ["_poseMatrix", "_source"]);
  26859. // Metadata
  26860. if (source.metadata && source.metadata.clone) {
  26861. _this.metadata = source.metadata.clone();
  26862. }
  26863. else {
  26864. _this.metadata = source.metadata;
  26865. }
  26866. // Tags
  26867. if (BABYLON.Tags && BABYLON.Tags.HasTags(source)) {
  26868. BABYLON.Tags.AddTagsTo(_this, BABYLON.Tags.GetTags(source, true));
  26869. }
  26870. // Parent
  26871. _this.parent = source.parent;
  26872. // Pivot
  26873. _this.setPivotMatrix(source.getPivotMatrix());
  26874. _this.id = name + "." + source.id;
  26875. // Material
  26876. _this.material = source.material;
  26877. var index;
  26878. if (!doNotCloneChildren) {
  26879. // Children
  26880. var directDescendants = source.getDescendants(true);
  26881. for (var index_1 = 0; index_1 < directDescendants.length; index_1++) {
  26882. var child = directDescendants[index_1];
  26883. if (child.clone) {
  26884. child.clone(name + "." + child.name, _this);
  26885. }
  26886. }
  26887. }
  26888. // Physics clone
  26889. var physicsEngine = _this.getScene().getPhysicsEngine();
  26890. if (clonePhysicsImpostor && physicsEngine) {
  26891. var impostor = physicsEngine.getImpostorForPhysicsObject(source);
  26892. if (impostor) {
  26893. _this.physicsImpostor = impostor.clone(_this);
  26894. }
  26895. }
  26896. // Particles
  26897. for (index = 0; index < scene.particleSystems.length; index++) {
  26898. var system = scene.particleSystems[index];
  26899. if (system.emitter === source) {
  26900. system.clone(system.name, _this);
  26901. }
  26902. }
  26903. _this.computeWorldMatrix(true);
  26904. }
  26905. // Parent
  26906. if (parent !== null) {
  26907. _this.parent = parent;
  26908. }
  26909. return _this;
  26910. }
  26911. Object.defineProperty(Mesh, "FRONTSIDE", {
  26912. /**
  26913. * Mesh side orientation : usually the external or front surface
  26914. */
  26915. get: function () {
  26916. return Mesh._FRONTSIDE;
  26917. },
  26918. enumerable: true,
  26919. configurable: true
  26920. });
  26921. Object.defineProperty(Mesh, "BACKSIDE", {
  26922. /**
  26923. * Mesh side orientation : usually the internal or back surface
  26924. */
  26925. get: function () {
  26926. return Mesh._BACKSIDE;
  26927. },
  26928. enumerable: true,
  26929. configurable: true
  26930. });
  26931. Object.defineProperty(Mesh, "DOUBLESIDE", {
  26932. /**
  26933. * Mesh side orientation : both internal and external or front and back surfaces
  26934. */
  26935. get: function () {
  26936. return Mesh._DOUBLESIDE;
  26937. },
  26938. enumerable: true,
  26939. configurable: true
  26940. });
  26941. Object.defineProperty(Mesh, "DEFAULTSIDE", {
  26942. /**
  26943. * Mesh side orientation : by default, `FRONTSIDE`
  26944. */
  26945. get: function () {
  26946. return Mesh._DEFAULTSIDE;
  26947. },
  26948. enumerable: true,
  26949. configurable: true
  26950. });
  26951. Object.defineProperty(Mesh, "NO_CAP", {
  26952. /**
  26953. * Mesh cap setting : no cap
  26954. */
  26955. get: function () {
  26956. return Mesh._NO_CAP;
  26957. },
  26958. enumerable: true,
  26959. configurable: true
  26960. });
  26961. Object.defineProperty(Mesh, "CAP_START", {
  26962. /**
  26963. * Mesh cap setting : one cap at the beginning of the mesh
  26964. */
  26965. get: function () {
  26966. return Mesh._CAP_START;
  26967. },
  26968. enumerable: true,
  26969. configurable: true
  26970. });
  26971. Object.defineProperty(Mesh, "CAP_END", {
  26972. /**
  26973. * Mesh cap setting : one cap at the end of the mesh
  26974. */
  26975. get: function () {
  26976. return Mesh._CAP_END;
  26977. },
  26978. enumerable: true,
  26979. configurable: true
  26980. });
  26981. Object.defineProperty(Mesh, "CAP_ALL", {
  26982. /**
  26983. * Mesh cap setting : two caps, one at the beginning and one at the end of the mesh
  26984. */
  26985. get: function () {
  26986. return Mesh._CAP_ALL;
  26987. },
  26988. enumerable: true,
  26989. configurable: true
  26990. });
  26991. Object.defineProperty(Mesh.prototype, "onBeforeDraw", {
  26992. set: function (callback) {
  26993. if (this._onBeforeDrawObserver) {
  26994. this.onBeforeDrawObservable.remove(this._onBeforeDrawObserver);
  26995. }
  26996. this._onBeforeDrawObserver = this.onBeforeDrawObservable.add(callback);
  26997. },
  26998. enumerable: true,
  26999. configurable: true
  27000. });
  27001. Object.defineProperty(Mesh.prototype, "morphTargetManager", {
  27002. get: function () {
  27003. return this._morphTargetManager;
  27004. },
  27005. set: function (value) {
  27006. if (this._morphTargetManager === value) {
  27007. return;
  27008. }
  27009. this._morphTargetManager = value;
  27010. this._syncGeometryWithMorphTargetManager();
  27011. },
  27012. enumerable: true,
  27013. configurable: true
  27014. });
  27015. Object.defineProperty(Mesh.prototype, "source", {
  27016. get: function () {
  27017. return this._source;
  27018. },
  27019. enumerable: true,
  27020. configurable: true
  27021. });
  27022. Object.defineProperty(Mesh.prototype, "isUnIndexed", {
  27023. get: function () {
  27024. return this._unIndexed;
  27025. },
  27026. set: function (value) {
  27027. if (this._unIndexed !== value) {
  27028. this._unIndexed = value;
  27029. this._markSubMeshesAsAttributesDirty();
  27030. }
  27031. },
  27032. enumerable: true,
  27033. configurable: true
  27034. });
  27035. // Methods
  27036. /**
  27037. * Returns the string "Mesh".
  27038. */
  27039. Mesh.prototype.getClassName = function () {
  27040. return "Mesh";
  27041. };
  27042. /**
  27043. * Returns a string.
  27044. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  27045. */
  27046. Mesh.prototype.toString = function (fullDetails) {
  27047. var ret = _super.prototype.toString.call(this, fullDetails);
  27048. ret += ", n vertices: " + this.getTotalVertices();
  27049. ret += ", parent: " + (this._waitingParentId ? this._waitingParentId : (this.parent ? this.parent.name : "NONE"));
  27050. if (this.animations) {
  27051. for (var i = 0; i < this.animations.length; i++) {
  27052. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  27053. }
  27054. }
  27055. if (fullDetails) {
  27056. if (this._geometry) {
  27057. var ib = this.getIndices();
  27058. var vb = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  27059. if (vb && ib) {
  27060. ret += ", flat shading: " + (vb.length / 3 === ib.length ? "YES" : "NO");
  27061. }
  27062. }
  27063. else {
  27064. ret += ", flat shading: UNKNOWN";
  27065. }
  27066. }
  27067. return ret;
  27068. };
  27069. Object.defineProperty(Mesh.prototype, "hasLODLevels", {
  27070. /**
  27071. * True if the mesh has some Levels Of Details (LOD).
  27072. * Returns a boolean.
  27073. */
  27074. get: function () {
  27075. return this._LODLevels.length > 0;
  27076. },
  27077. enumerable: true,
  27078. configurable: true
  27079. });
  27080. /**
  27081. * Gets the list of {BABYLON.MeshLODLevel} associated with the current mesh
  27082. * @returns an array of {BABYLON.MeshLODLevel}
  27083. */
  27084. Mesh.prototype.getLODLevels = function () {
  27085. return this._LODLevels;
  27086. };
  27087. Mesh.prototype._sortLODLevels = function () {
  27088. this._LODLevels.sort(function (a, b) {
  27089. if (a.distance < b.distance) {
  27090. return 1;
  27091. }
  27092. if (a.distance > b.distance) {
  27093. return -1;
  27094. }
  27095. return 0;
  27096. });
  27097. };
  27098. /**
  27099. * Add a mesh as LOD level triggered at the given distance.
  27100. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  27101. * @param {number} distance The distance from the center of the object to show this level
  27102. * @param {Mesh} mesh The mesh to be added as LOD level
  27103. * @return {Mesh} This mesh (for chaining)
  27104. */
  27105. Mesh.prototype.addLODLevel = function (distance, mesh) {
  27106. if (mesh && mesh._masterMesh) {
  27107. BABYLON.Tools.Warn("You cannot use a mesh as LOD level twice");
  27108. return this;
  27109. }
  27110. var level = new BABYLON.MeshLODLevel(distance, mesh);
  27111. this._LODLevels.push(level);
  27112. if (mesh) {
  27113. mesh._masterMesh = this;
  27114. }
  27115. this._sortLODLevels();
  27116. return this;
  27117. };
  27118. /**
  27119. * Returns the LOD level mesh at the passed distance or null if not found.
  27120. * It is related to the method `addLODLevel(distance, mesh)`.
  27121. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  27122. * Returns an object Mesh or `null`.
  27123. */
  27124. Mesh.prototype.getLODLevelAtDistance = function (distance) {
  27125. for (var index = 0; index < this._LODLevels.length; index++) {
  27126. var level = this._LODLevels[index];
  27127. if (level.distance === distance) {
  27128. return level.mesh;
  27129. }
  27130. }
  27131. return null;
  27132. };
  27133. /**
  27134. * Remove a mesh from the LOD array
  27135. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  27136. * @param {Mesh} mesh The mesh to be removed.
  27137. * @return {Mesh} This mesh (for chaining)
  27138. */
  27139. Mesh.prototype.removeLODLevel = function (mesh) {
  27140. for (var index = 0; index < this._LODLevels.length; index++) {
  27141. if (this._LODLevels[index].mesh === mesh) {
  27142. this._LODLevels.splice(index, 1);
  27143. if (mesh) {
  27144. mesh._masterMesh = null;
  27145. }
  27146. }
  27147. }
  27148. this._sortLODLevels();
  27149. return this;
  27150. };
  27151. /**
  27152. * Returns the registered LOD mesh distant from the parameter `camera` position if any, else returns the current mesh.
  27153. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  27154. */
  27155. Mesh.prototype.getLOD = function (camera, boundingSphere) {
  27156. if (!this._LODLevels || this._LODLevels.length === 0) {
  27157. return this;
  27158. }
  27159. var bSphere;
  27160. if (boundingSphere) {
  27161. bSphere = boundingSphere;
  27162. }
  27163. else {
  27164. var boundingInfo = this.getBoundingInfo();
  27165. bSphere = boundingInfo.boundingSphere;
  27166. }
  27167. var distanceToCamera = bSphere.centerWorld.subtract(camera.globalPosition).length();
  27168. if (this._LODLevels[this._LODLevels.length - 1].distance > distanceToCamera) {
  27169. if (this.onLODLevelSelection) {
  27170. this.onLODLevelSelection(distanceToCamera, this, this._LODLevels[this._LODLevels.length - 1].mesh);
  27171. }
  27172. return this;
  27173. }
  27174. for (var index = 0; index < this._LODLevels.length; index++) {
  27175. var level = this._LODLevels[index];
  27176. if (level.distance < distanceToCamera) {
  27177. if (level.mesh) {
  27178. level.mesh._preActivate();
  27179. level.mesh._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  27180. }
  27181. if (this.onLODLevelSelection) {
  27182. this.onLODLevelSelection(distanceToCamera, this, level.mesh);
  27183. }
  27184. return level.mesh;
  27185. }
  27186. }
  27187. if (this.onLODLevelSelection) {
  27188. this.onLODLevelSelection(distanceToCamera, this, this);
  27189. }
  27190. return this;
  27191. };
  27192. Object.defineProperty(Mesh.prototype, "geometry", {
  27193. /**
  27194. * Returns the mesh internal Geometry object.
  27195. */
  27196. get: function () {
  27197. return this._geometry;
  27198. },
  27199. enumerable: true,
  27200. configurable: true
  27201. });
  27202. /**
  27203. * Returns a positive integer : the total number of vertices within the mesh geometry or zero if the mesh has no geometry.
  27204. */
  27205. Mesh.prototype.getTotalVertices = function () {
  27206. if (this._geometry === null || this._geometry === undefined) {
  27207. return 0;
  27208. }
  27209. return this._geometry.getTotalVertices();
  27210. };
  27211. /**
  27212. * Returns an array of integers or floats, or a Float32Array, depending on the requested `kind` (positions, indices, normals, etc).
  27213. * 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.
  27214. * You can force the copy with forceCopy === true
  27215. * Returns null if the mesh has no geometry or no vertex buffer.
  27216. * Possible `kind` values :
  27217. * - BABYLON.VertexBuffer.PositionKind
  27218. * - BABYLON.VertexBuffer.UVKind
  27219. * - BABYLON.VertexBuffer.UV2Kind
  27220. * - BABYLON.VertexBuffer.UV3Kind
  27221. * - BABYLON.VertexBuffer.UV4Kind
  27222. * - BABYLON.VertexBuffer.UV5Kind
  27223. * - BABYLON.VertexBuffer.UV6Kind
  27224. * - BABYLON.VertexBuffer.ColorKind
  27225. * - BABYLON.VertexBuffer.MatricesIndicesKind
  27226. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  27227. * - BABYLON.VertexBuffer.MatricesWeightsKind
  27228. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  27229. */
  27230. Mesh.prototype.getVerticesData = function (kind, copyWhenShared, forceCopy) {
  27231. if (!this._geometry) {
  27232. return null;
  27233. }
  27234. return this._geometry.getVerticesData(kind, copyWhenShared, forceCopy);
  27235. };
  27236. /**
  27237. * Returns the mesh VertexBuffer object from the requested `kind` : positions, indices, normals, etc.
  27238. * Returns `null` if the mesh has no geometry.
  27239. * Possible `kind` values :
  27240. * - BABYLON.VertexBuffer.PositionKind
  27241. * - BABYLON.VertexBuffer.UVKind
  27242. * - BABYLON.VertexBuffer.UV2Kind
  27243. * - BABYLON.VertexBuffer.UV3Kind
  27244. * - BABYLON.VertexBuffer.UV4Kind
  27245. * - BABYLON.VertexBuffer.UV5Kind
  27246. * - BABYLON.VertexBuffer.UV6Kind
  27247. * - BABYLON.VertexBuffer.ColorKind
  27248. * - BABYLON.VertexBuffer.MatricesIndicesKind
  27249. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  27250. * - BABYLON.VertexBuffer.MatricesWeightsKind
  27251. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  27252. */
  27253. Mesh.prototype.getVertexBuffer = function (kind) {
  27254. if (!this._geometry) {
  27255. return null;
  27256. }
  27257. return this._geometry.getVertexBuffer(kind);
  27258. };
  27259. /**
  27260. * Returns a boolean depending on the existence of the Vertex Data for the requested `kind`.
  27261. * Possible `kind` values :
  27262. * - BABYLON.VertexBuffer.PositionKind
  27263. * - BABYLON.VertexBuffer.UVKind
  27264. * - BABYLON.VertexBuffer.UV2Kind
  27265. * - BABYLON.VertexBuffer.UV3Kind
  27266. * - BABYLON.VertexBuffer.UV4Kind
  27267. * - BABYLON.VertexBuffer.UV5Kind
  27268. * - BABYLON.VertexBuffer.UV6Kind
  27269. * - BABYLON.VertexBuffer.ColorKind
  27270. * - BABYLON.VertexBuffer.MatricesIndicesKind
  27271. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  27272. * - BABYLON.VertexBuffer.MatricesWeightsKind
  27273. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  27274. */
  27275. Mesh.prototype.isVerticesDataPresent = function (kind) {
  27276. if (!this._geometry) {
  27277. if (this._delayInfo) {
  27278. return this._delayInfo.indexOf(kind) !== -1;
  27279. }
  27280. return false;
  27281. }
  27282. return this._geometry.isVerticesDataPresent(kind);
  27283. };
  27284. /**
  27285. * Returns a boolean defining if the vertex data for the requested `kind` is updatable.
  27286. * Possible `kind` values :
  27287. * - BABYLON.VertexBuffer.PositionKind
  27288. * - BABYLON.VertexBuffer.UVKind
  27289. * - BABYLON.VertexBuffer.UV2Kind
  27290. * - BABYLON.VertexBuffer.UV3Kind
  27291. * - BABYLON.VertexBuffer.UV4Kind
  27292. * - BABYLON.VertexBuffer.UV5Kind
  27293. * - BABYLON.VertexBuffer.UV6Kind
  27294. * - BABYLON.VertexBuffer.ColorKind
  27295. * - BABYLON.VertexBuffer.MatricesIndicesKind
  27296. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  27297. * - BABYLON.VertexBuffer.MatricesWeightsKind
  27298. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  27299. */
  27300. Mesh.prototype.isVertexBufferUpdatable = function (kind) {
  27301. if (!this._geometry) {
  27302. if (this._delayInfo) {
  27303. return this._delayInfo.indexOf(kind) !== -1;
  27304. }
  27305. return false;
  27306. }
  27307. return this._geometry.isVertexBufferUpdatable(kind);
  27308. };
  27309. /**
  27310. * Returns a string : the list of existing `kinds` of Vertex Data for this mesh.
  27311. * Possible `kind` values :
  27312. * - BABYLON.VertexBuffer.PositionKind
  27313. * - BABYLON.VertexBuffer.UVKind
  27314. * - BABYLON.VertexBuffer.UV2Kind
  27315. * - BABYLON.VertexBuffer.UV3Kind
  27316. * - BABYLON.VertexBuffer.UV4Kind
  27317. * - BABYLON.VertexBuffer.UV5Kind
  27318. * - BABYLON.VertexBuffer.UV6Kind
  27319. * - BABYLON.VertexBuffer.ColorKind
  27320. * - BABYLON.VertexBuffer.MatricesIndicesKind
  27321. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  27322. * - BABYLON.VertexBuffer.MatricesWeightsKind
  27323. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  27324. */
  27325. Mesh.prototype.getVerticesDataKinds = function () {
  27326. if (!this._geometry) {
  27327. var result = new Array();
  27328. if (this._delayInfo) {
  27329. this._delayInfo.forEach(function (kind, index, array) {
  27330. result.push(kind);
  27331. });
  27332. }
  27333. return result;
  27334. }
  27335. return this._geometry.getVerticesDataKinds();
  27336. };
  27337. /**
  27338. * Returns a positive integer : the total number of indices in this mesh geometry.
  27339. * Returns zero if the mesh has no geometry.
  27340. */
  27341. Mesh.prototype.getTotalIndices = function () {
  27342. if (!this._geometry) {
  27343. return 0;
  27344. }
  27345. return this._geometry.getTotalIndices();
  27346. };
  27347. /**
  27348. * Returns an array of integers or a typed array (Int32Array, Uint32Array, Uint16Array) populated with the mesh indices.
  27349. * 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.
  27350. * Returns an empty array if the mesh has no geometry.
  27351. */
  27352. Mesh.prototype.getIndices = function (copyWhenShared) {
  27353. if (!this._geometry) {
  27354. return [];
  27355. }
  27356. return this._geometry.getIndices(copyWhenShared);
  27357. };
  27358. Object.defineProperty(Mesh.prototype, "isBlocked", {
  27359. get: function () {
  27360. return this._masterMesh !== null && this._masterMesh !== undefined;
  27361. },
  27362. enumerable: true,
  27363. configurable: true
  27364. });
  27365. /**
  27366. * Determine if the current mesh is ready to be rendered
  27367. * @param completeCheck defines if a complete check (including materials and lights) has to be done (false by default)
  27368. * @param forceInstanceSupport will check if the mesh will be ready when used with instances (false by default)
  27369. * @returns true if all associated assets are ready (material, textures, shaders)
  27370. */
  27371. Mesh.prototype.isReady = function (completeCheck, forceInstanceSupport) {
  27372. if (completeCheck === void 0) { completeCheck = false; }
  27373. if (forceInstanceSupport === void 0) { forceInstanceSupport = false; }
  27374. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  27375. return false;
  27376. }
  27377. if (!_super.prototype.isReady.call(this, completeCheck)) {
  27378. return false;
  27379. }
  27380. if (!this.subMeshes || this.subMeshes.length === 0) {
  27381. return true;
  27382. }
  27383. if (!completeCheck) {
  27384. return true;
  27385. }
  27386. var engine = this.getEngine();
  27387. var scene = this.getScene();
  27388. var hardwareInstancedRendering = forceInstanceSupport || engine.getCaps().instancedArrays && this.instances.length > 0;
  27389. this.computeWorldMatrix();
  27390. var mat = this.material || scene.defaultMaterial;
  27391. if (mat) {
  27392. if (mat.storeEffectOnSubMeshes) {
  27393. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  27394. var subMesh = _a[_i];
  27395. var effectiveMaterial = subMesh.getMaterial();
  27396. if (effectiveMaterial) {
  27397. if (!effectiveMaterial.isReadyForSubMesh(this, subMesh, hardwareInstancedRendering)) {
  27398. return false;
  27399. }
  27400. }
  27401. }
  27402. }
  27403. else {
  27404. if (!mat.isReady(this, hardwareInstancedRendering)) {
  27405. return false;
  27406. }
  27407. }
  27408. }
  27409. // Shadows
  27410. for (var _b = 0, _c = this._lightSources; _b < _c.length; _b++) {
  27411. var light = _c[_b];
  27412. var generator = light.getShadowGenerator();
  27413. if (generator) {
  27414. for (var _d = 0, _e = this.subMeshes; _d < _e.length; _d++) {
  27415. var subMesh = _e[_d];
  27416. if (!generator.isReady(subMesh, hardwareInstancedRendering)) {
  27417. return false;
  27418. }
  27419. }
  27420. }
  27421. }
  27422. // LOD
  27423. for (var _f = 0, _g = this._LODLevels; _f < _g.length; _f++) {
  27424. var lod = _g[_f];
  27425. if (lod.mesh && !lod.mesh.isReady(hardwareInstancedRendering)) {
  27426. return false;
  27427. }
  27428. }
  27429. return true;
  27430. };
  27431. Object.defineProperty(Mesh.prototype, "areNormalsFrozen", {
  27432. /**
  27433. * Boolean : true if the normals aren't to be recomputed on next mesh `positions` array update.
  27434. * This property is pertinent only for updatable parametric shapes.
  27435. */
  27436. get: function () {
  27437. return this._areNormalsFrozen;
  27438. },
  27439. enumerable: true,
  27440. configurable: true
  27441. });
  27442. /**
  27443. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc.
  27444. * It has no effect at all on other shapes.
  27445. * It prevents the mesh normals from being recomputed on next `positions` array update.
  27446. * Returns the Mesh.
  27447. */
  27448. Mesh.prototype.freezeNormals = function () {
  27449. this._areNormalsFrozen = true;
  27450. return this;
  27451. };
  27452. /**
  27453. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc.
  27454. * It has no effect at all on other shapes.
  27455. * It reactivates the mesh normals computation if it was previously frozen.
  27456. * Returns the Mesh.
  27457. */
  27458. Mesh.prototype.unfreezeNormals = function () {
  27459. this._areNormalsFrozen = false;
  27460. return this;
  27461. };
  27462. Object.defineProperty(Mesh.prototype, "overridenInstanceCount", {
  27463. /**
  27464. * Overrides instance count. Only applicable when custom instanced InterleavedVertexBuffer are used rather than InstancedMeshs
  27465. */
  27466. set: function (count) {
  27467. this._overridenInstanceCount = count;
  27468. },
  27469. enumerable: true,
  27470. configurable: true
  27471. });
  27472. // Methods
  27473. Mesh.prototype._preActivate = function () {
  27474. var sceneRenderId = this.getScene().getRenderId();
  27475. if (this._preActivateId === sceneRenderId) {
  27476. return this;
  27477. }
  27478. this._preActivateId = sceneRenderId;
  27479. this._visibleInstances = null;
  27480. return this;
  27481. };
  27482. Mesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  27483. if (this._visibleInstances) {
  27484. this._visibleInstances.intermediateDefaultRenderId = renderId;
  27485. }
  27486. return this;
  27487. };
  27488. Mesh.prototype._registerInstanceForRenderId = function (instance, renderId) {
  27489. if (!this._visibleInstances) {
  27490. this._visibleInstances = {};
  27491. this._visibleInstances.defaultRenderId = renderId;
  27492. this._visibleInstances.selfDefaultRenderId = this._renderId;
  27493. }
  27494. if (!this._visibleInstances[renderId]) {
  27495. this._visibleInstances[renderId] = new Array();
  27496. }
  27497. this._visibleInstances[renderId].push(instance);
  27498. return this;
  27499. };
  27500. /**
  27501. * This method recomputes and sets a new BoundingInfo to the mesh unless it is locked.
  27502. * This means the mesh underlying bounding box and sphere are recomputed.
  27503. * Returns the Mesh.
  27504. */
  27505. Mesh.prototype.refreshBoundingInfo = function () {
  27506. return this._refreshBoundingInfo(false);
  27507. };
  27508. Mesh.prototype._refreshBoundingInfo = function (applySkeleton) {
  27509. if (this._boundingInfo && this._boundingInfo.isLocked) {
  27510. return this;
  27511. }
  27512. var data = this._getPositionData(applySkeleton);
  27513. if (data) {
  27514. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this.getTotalVertices());
  27515. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  27516. }
  27517. if (this.subMeshes) {
  27518. for (var index = 0; index < this.subMeshes.length; index++) {
  27519. this.subMeshes[index].refreshBoundingInfo();
  27520. }
  27521. }
  27522. this._updateBoundingInfo();
  27523. return this;
  27524. };
  27525. Mesh.prototype._getPositionData = function (applySkeleton) {
  27526. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  27527. if (data && applySkeleton && this.skeleton) {
  27528. data = BABYLON.Tools.Slice(data);
  27529. var matricesIndicesData = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  27530. var matricesWeightsData = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  27531. if (matricesWeightsData && matricesIndicesData) {
  27532. var needExtras = this.numBoneInfluencers > 4;
  27533. var matricesIndicesExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind) : null;
  27534. var matricesWeightsExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind) : null;
  27535. var skeletonMatrices = this.skeleton.getTransformMatrices(this);
  27536. var tempVector = BABYLON.Tmp.Vector3[0];
  27537. var finalMatrix = BABYLON.Tmp.Matrix[0];
  27538. var tempMatrix = BABYLON.Tmp.Matrix[1];
  27539. var matWeightIdx = 0;
  27540. for (var index = 0; index < data.length; index += 3, matWeightIdx += 4) {
  27541. finalMatrix.reset();
  27542. var inf;
  27543. var weight;
  27544. for (inf = 0; inf < 4; inf++) {
  27545. weight = matricesWeightsData[matWeightIdx + inf];
  27546. if (weight <= 0)
  27547. break;
  27548. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, matricesIndicesData[matWeightIdx + inf] * 16, weight, tempMatrix);
  27549. finalMatrix.addToSelf(tempMatrix);
  27550. }
  27551. if (needExtras) {
  27552. for (inf = 0; inf < 4; inf++) {
  27553. weight = matricesWeightsExtraData[matWeightIdx + inf];
  27554. if (weight <= 0)
  27555. break;
  27556. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, matricesIndicesExtraData[matWeightIdx + inf] * 16, weight, tempMatrix);
  27557. finalMatrix.addToSelf(tempMatrix);
  27558. }
  27559. }
  27560. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(data[index], data[index + 1], data[index + 2], finalMatrix, tempVector);
  27561. tempVector.toArray(data, index);
  27562. }
  27563. }
  27564. }
  27565. return data;
  27566. };
  27567. Mesh.prototype._createGlobalSubMesh = function (force) {
  27568. var totalVertices = this.getTotalVertices();
  27569. if (!totalVertices || !this.getIndices()) {
  27570. return null;
  27571. }
  27572. // Check if we need to recreate the submeshes
  27573. if (this.subMeshes && this.subMeshes.length > 0) {
  27574. var ib = this.getIndices();
  27575. if (!ib) {
  27576. return null;
  27577. }
  27578. var totalIndices = ib.length;
  27579. var needToRecreate = false;
  27580. if (force) {
  27581. needToRecreate = true;
  27582. }
  27583. else {
  27584. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  27585. var submesh = _a[_i];
  27586. if (submesh.indexStart + submesh.indexCount >= totalIndices) {
  27587. needToRecreate = true;
  27588. break;
  27589. }
  27590. if (submesh.verticesStart + submesh.verticesCount >= totalVertices) {
  27591. needToRecreate = true;
  27592. break;
  27593. }
  27594. }
  27595. }
  27596. if (!needToRecreate) {
  27597. return this.subMeshes[0];
  27598. }
  27599. }
  27600. this.releaseSubMeshes();
  27601. return new BABYLON.SubMesh(0, 0, totalVertices, 0, this.getTotalIndices(), this);
  27602. };
  27603. Mesh.prototype.subdivide = function (count) {
  27604. if (count < 1) {
  27605. return;
  27606. }
  27607. var totalIndices = this.getTotalIndices();
  27608. var subdivisionSize = (totalIndices / count) | 0;
  27609. var offset = 0;
  27610. // Ensure that subdivisionSize is a multiple of 3
  27611. while (subdivisionSize % 3 !== 0) {
  27612. subdivisionSize++;
  27613. }
  27614. this.releaseSubMeshes();
  27615. for (var index = 0; index < count; index++) {
  27616. if (offset >= totalIndices) {
  27617. break;
  27618. }
  27619. BABYLON.SubMesh.CreateFromIndices(0, offset, Math.min(subdivisionSize, totalIndices - offset), this);
  27620. offset += subdivisionSize;
  27621. }
  27622. this.synchronizeInstances();
  27623. };
  27624. /**
  27625. * Sets the vertex data of the mesh geometry for the requested `kind`.
  27626. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  27627. * The `data` are either a numeric array either a Float32Array.
  27628. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  27629. * 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).
  27630. * Note that a new underlying VertexBuffer object is created each call.
  27631. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  27632. *
  27633. * Possible `kind` values :
  27634. * - BABYLON.VertexBuffer.PositionKind
  27635. * - BABYLON.VertexBuffer.UVKind
  27636. * - BABYLON.VertexBuffer.UV2Kind
  27637. * - BABYLON.VertexBuffer.UV3Kind
  27638. * - BABYLON.VertexBuffer.UV4Kind
  27639. * - BABYLON.VertexBuffer.UV5Kind
  27640. * - BABYLON.VertexBuffer.UV6Kind
  27641. * - BABYLON.VertexBuffer.ColorKind
  27642. * - BABYLON.VertexBuffer.MatricesIndicesKind
  27643. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  27644. * - BABYLON.VertexBuffer.MatricesWeightsKind
  27645. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  27646. *
  27647. * Returns the Mesh.
  27648. */
  27649. Mesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  27650. if (updatable === void 0) { updatable = false; }
  27651. if (!this._geometry) {
  27652. var vertexData = new BABYLON.VertexData();
  27653. vertexData.set(data, kind);
  27654. var scene = this.getScene();
  27655. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  27656. }
  27657. else {
  27658. this._geometry.setVerticesData(kind, data, updatable, stride);
  27659. }
  27660. return this;
  27661. };
  27662. Mesh.prototype.markVerticesDataAsUpdatable = function (kind, updatable) {
  27663. if (updatable === void 0) { updatable = true; }
  27664. var vb = this.getVertexBuffer(kind);
  27665. if (!vb || vb.isUpdatable() === updatable) {
  27666. return;
  27667. }
  27668. this.setVerticesData(kind, this.getVerticesData(kind), updatable);
  27669. };
  27670. /**
  27671. * Sets the mesh VertexBuffer.
  27672. * Returns the Mesh.
  27673. */
  27674. Mesh.prototype.setVerticesBuffer = function (buffer) {
  27675. if (!this._geometry) {
  27676. this._geometry = BABYLON.Geometry.CreateGeometryForMesh(this);
  27677. }
  27678. this._geometry.setVerticesBuffer(buffer);
  27679. return this;
  27680. };
  27681. /**
  27682. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  27683. * If the mesh has no geometry, it is simply returned as it is.
  27684. * The `data` are either a numeric array either a Float32Array.
  27685. * No new underlying VertexBuffer object is created.
  27686. * 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.
  27687. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  27688. *
  27689. * Possible `kind` values :
  27690. * - BABYLON.VertexBuffer.PositionKind
  27691. * - BABYLON.VertexBuffer.UVKind
  27692. * - BABYLON.VertexBuffer.UV2Kind
  27693. * - BABYLON.VertexBuffer.UV3Kind
  27694. * - BABYLON.VertexBuffer.UV4Kind
  27695. * - BABYLON.VertexBuffer.UV5Kind
  27696. * - BABYLON.VertexBuffer.UV6Kind
  27697. * - BABYLON.VertexBuffer.ColorKind
  27698. * - BABYLON.VertexBuffer.MatricesIndicesKind
  27699. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  27700. * - BABYLON.VertexBuffer.MatricesWeightsKind
  27701. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  27702. *
  27703. * Returns the Mesh.
  27704. */
  27705. Mesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  27706. if (!this._geometry) {
  27707. return this;
  27708. }
  27709. if (!makeItUnique) {
  27710. this._geometry.updateVerticesData(kind, data, updateExtends);
  27711. }
  27712. else {
  27713. this.makeGeometryUnique();
  27714. this.updateVerticesData(kind, data, updateExtends, false);
  27715. }
  27716. return this;
  27717. };
  27718. /**
  27719. * This method updates the vertex positions of an updatable mesh according to the `positionFunction` returned values.
  27720. * tuto : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#other-shapes-updatemeshpositions
  27721. * The parameter `positionFunction` is a simple JS function what is passed the mesh `positions` array. It doesn't need to return anything.
  27722. * The parameter `computeNormals` is a boolean (default true) to enable/disable the mesh normal recomputation after the vertex position update.
  27723. * Returns the Mesh.
  27724. */
  27725. Mesh.prototype.updateMeshPositions = function (positionFunction, computeNormals) {
  27726. if (computeNormals === void 0) { computeNormals = true; }
  27727. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  27728. if (!positions) {
  27729. return this;
  27730. }
  27731. positionFunction(positions);
  27732. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  27733. if (computeNormals) {
  27734. var indices = this.getIndices();
  27735. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  27736. if (!normals) {
  27737. return this;
  27738. }
  27739. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  27740. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  27741. }
  27742. return this;
  27743. };
  27744. /**
  27745. * Creates a un-shared specific occurence of the geometry for the mesh.
  27746. * Returns the Mesh.
  27747. */
  27748. Mesh.prototype.makeGeometryUnique = function () {
  27749. if (!this._geometry) {
  27750. return this;
  27751. }
  27752. var oldGeometry = this._geometry;
  27753. var geometry = this._geometry.copy(BABYLON.Geometry.RandomId());
  27754. oldGeometry.releaseForMesh(this, true);
  27755. geometry.applyToMesh(this);
  27756. return this;
  27757. };
  27758. /**
  27759. * Sets the mesh indices.
  27760. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array).
  27761. * Type is Uint16Array by default unless the mesh has more than 65536 vertices.
  27762. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  27763. * This method creates a new index buffer each call.
  27764. * Returns the Mesh.
  27765. */
  27766. Mesh.prototype.setIndices = function (indices, totalVertices, updatable) {
  27767. if (totalVertices === void 0) { totalVertices = null; }
  27768. if (updatable === void 0) { updatable = false; }
  27769. if (!this._geometry) {
  27770. var vertexData = new BABYLON.VertexData();
  27771. vertexData.indices = indices;
  27772. var scene = this.getScene();
  27773. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  27774. }
  27775. else {
  27776. this._geometry.setIndices(indices, totalVertices, updatable);
  27777. }
  27778. return this;
  27779. };
  27780. /**
  27781. * Update the current index buffer
  27782. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array)
  27783. * Returns the Mesh.
  27784. */
  27785. Mesh.prototype.updateIndices = function (indices, offset) {
  27786. if (!this._geometry) {
  27787. return this;
  27788. }
  27789. this._geometry.updateIndices(indices, offset);
  27790. return this;
  27791. };
  27792. /**
  27793. * Invert the geometry to move from a right handed system to a left handed one.
  27794. * Returns the Mesh.
  27795. */
  27796. Mesh.prototype.toLeftHanded = function () {
  27797. if (!this._geometry) {
  27798. return this;
  27799. }
  27800. this._geometry.toLeftHanded();
  27801. return this;
  27802. };
  27803. Mesh.prototype._bind = function (subMesh, effect, fillMode) {
  27804. if (!this._geometry) {
  27805. return this;
  27806. }
  27807. var engine = this.getScene().getEngine();
  27808. // Wireframe
  27809. var indexToBind;
  27810. if (this._unIndexed) {
  27811. indexToBind = null;
  27812. }
  27813. else {
  27814. switch (fillMode) {
  27815. case BABYLON.Material.PointFillMode:
  27816. indexToBind = null;
  27817. break;
  27818. case BABYLON.Material.WireFrameFillMode:
  27819. indexToBind = subMesh.getLinesIndexBuffer(this.getIndices(), engine);
  27820. break;
  27821. default:
  27822. case BABYLON.Material.TriangleFillMode:
  27823. indexToBind = this._unIndexed ? null : this._geometry.getIndexBuffer();
  27824. break;
  27825. }
  27826. }
  27827. // VBOs
  27828. this._geometry._bind(effect, indexToBind);
  27829. return this;
  27830. };
  27831. Mesh.prototype._draw = function (subMesh, fillMode, instancesCount, alternate) {
  27832. if (alternate === void 0) { alternate = false; }
  27833. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  27834. return this;
  27835. }
  27836. this.onBeforeDrawObservable.notifyObservers(this);
  27837. var scene = this.getScene();
  27838. var engine = scene.getEngine();
  27839. if (this._unIndexed || fillMode == BABYLON.Material.PointFillMode) {
  27840. // or triangles as points
  27841. engine.drawArraysType(fillMode, subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  27842. }
  27843. else if (fillMode == BABYLON.Material.WireFrameFillMode) {
  27844. // Triangles as wireframe
  27845. engine.drawElementsType(fillMode, 0, subMesh.linesIndexCount, instancesCount);
  27846. }
  27847. else {
  27848. engine.drawElementsType(fillMode, subMesh.indexStart, subMesh.indexCount, instancesCount);
  27849. }
  27850. if (scene._isAlternateRenderingEnabled && !alternate) {
  27851. var effect = subMesh.effect || this._effectiveMaterial.getEffect();
  27852. if (!effect || !scene.activeCamera) {
  27853. return this;
  27854. }
  27855. scene._switchToAlternateCameraConfiguration(true);
  27856. this._effectiveMaterial.bindView(effect);
  27857. this._effectiveMaterial.bindViewProjection(effect);
  27858. engine.setViewport(scene.activeCamera._alternateCamera.viewport);
  27859. this._draw(subMesh, fillMode, instancesCount, true);
  27860. engine.setViewport(scene.activeCamera.viewport);
  27861. scene._switchToAlternateCameraConfiguration(false);
  27862. this._effectiveMaterial.bindView(effect);
  27863. this._effectiveMaterial.bindViewProjection(effect);
  27864. }
  27865. return this;
  27866. };
  27867. /**
  27868. * Registers for this mesh a javascript function called just before the rendering process.
  27869. * This function is passed the current mesh.
  27870. * Return the Mesh.
  27871. */
  27872. Mesh.prototype.registerBeforeRender = function (func) {
  27873. this.onBeforeRenderObservable.add(func);
  27874. return this;
  27875. };
  27876. /**
  27877. * Disposes a previously registered javascript function called before the rendering.
  27878. * This function is passed the current mesh.
  27879. * Returns the Mesh.
  27880. */
  27881. Mesh.prototype.unregisterBeforeRender = function (func) {
  27882. this.onBeforeRenderObservable.removeCallback(func);
  27883. return this;
  27884. };
  27885. /**
  27886. * Registers for this mesh a javascript function called just after the rendering is complete.
  27887. * This function is passed the current mesh.
  27888. * Returns the Mesh.
  27889. */
  27890. Mesh.prototype.registerAfterRender = function (func) {
  27891. this.onAfterRenderObservable.add(func);
  27892. return this;
  27893. };
  27894. /**
  27895. * Disposes a previously registered javascript function called after the rendering.
  27896. * This function is passed the current mesh.
  27897. * Return the Mesh.
  27898. */
  27899. Mesh.prototype.unregisterAfterRender = function (func) {
  27900. this.onAfterRenderObservable.removeCallback(func);
  27901. return this;
  27902. };
  27903. Mesh.prototype._getInstancesRenderList = function (subMeshId) {
  27904. var scene = this.getScene();
  27905. this._batchCache.mustReturn = false;
  27906. this._batchCache.renderSelf[subMeshId] = this.isEnabled() && this.isVisible;
  27907. this._batchCache.visibleInstances[subMeshId] = null;
  27908. if (this._visibleInstances) {
  27909. var currentRenderId = scene.getRenderId();
  27910. var defaultRenderId = (scene._isInIntermediateRendering() ? this._visibleInstances.intermediateDefaultRenderId : this._visibleInstances.defaultRenderId);
  27911. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[currentRenderId];
  27912. var selfRenderId = this._renderId;
  27913. if (!this._batchCache.visibleInstances[subMeshId] && defaultRenderId) {
  27914. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[defaultRenderId];
  27915. currentRenderId = Math.max(defaultRenderId, currentRenderId);
  27916. selfRenderId = Math.max(this._visibleInstances.selfDefaultRenderId, currentRenderId);
  27917. }
  27918. var visibleInstancesForSubMesh = this._batchCache.visibleInstances[subMeshId];
  27919. if (visibleInstancesForSubMesh && visibleInstancesForSubMesh.length) {
  27920. if (this._renderIdForInstances[subMeshId] === currentRenderId) {
  27921. this._batchCache.mustReturn = true;
  27922. return this._batchCache;
  27923. }
  27924. if (currentRenderId !== selfRenderId) {
  27925. this._batchCache.renderSelf[subMeshId] = false;
  27926. }
  27927. }
  27928. this._renderIdForInstances[subMeshId] = currentRenderId;
  27929. }
  27930. return this._batchCache;
  27931. };
  27932. Mesh.prototype._renderWithInstances = function (subMesh, fillMode, batch, effect, engine) {
  27933. var visibleInstances = batch.visibleInstances[subMesh._id];
  27934. if (!visibleInstances) {
  27935. return this;
  27936. }
  27937. var matricesCount = visibleInstances.length + 1;
  27938. var bufferSize = matricesCount * 16 * 4;
  27939. var currentInstancesBufferSize = this._instancesBufferSize;
  27940. var instancesBuffer = this._instancesBuffer;
  27941. while (this._instancesBufferSize < bufferSize) {
  27942. this._instancesBufferSize *= 2;
  27943. }
  27944. if (!this._instancesData || currentInstancesBufferSize != this._instancesBufferSize) {
  27945. this._instancesData = new Float32Array(this._instancesBufferSize / 4);
  27946. }
  27947. var offset = 0;
  27948. var instancesCount = 0;
  27949. var world = this.getWorldMatrix();
  27950. if (batch.renderSelf[subMesh._id]) {
  27951. world.copyToArray(this._instancesData, offset);
  27952. offset += 16;
  27953. instancesCount++;
  27954. }
  27955. if (visibleInstances) {
  27956. for (var instanceIndex = 0; instanceIndex < visibleInstances.length; instanceIndex++) {
  27957. var instance = visibleInstances[instanceIndex];
  27958. instance.getWorldMatrix().copyToArray(this._instancesData, offset);
  27959. offset += 16;
  27960. instancesCount++;
  27961. }
  27962. }
  27963. if (!instancesBuffer || currentInstancesBufferSize != this._instancesBufferSize) {
  27964. if (instancesBuffer) {
  27965. instancesBuffer.dispose();
  27966. }
  27967. instancesBuffer = new BABYLON.Buffer(engine, this._instancesData, true, 16, false, true);
  27968. this._instancesBuffer = instancesBuffer;
  27969. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world0", 0, 4));
  27970. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world1", 4, 4));
  27971. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world2", 8, 4));
  27972. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world3", 12, 4));
  27973. }
  27974. else {
  27975. instancesBuffer.updateDirectly(this._instancesData, 0, instancesCount);
  27976. }
  27977. this._bind(subMesh, effect, fillMode);
  27978. this._draw(subMesh, fillMode, instancesCount);
  27979. engine.unbindInstanceAttributes();
  27980. return this;
  27981. };
  27982. Mesh.prototype._processRendering = function (subMesh, effect, fillMode, batch, hardwareInstancedRendering, onBeforeDraw, effectiveMaterial) {
  27983. var scene = this.getScene();
  27984. var engine = scene.getEngine();
  27985. if (hardwareInstancedRendering) {
  27986. this._renderWithInstances(subMesh, fillMode, batch, effect, engine);
  27987. }
  27988. else {
  27989. if (batch.renderSelf[subMesh._id]) {
  27990. // Draw
  27991. if (onBeforeDraw) {
  27992. onBeforeDraw(false, this.getWorldMatrix(), effectiveMaterial);
  27993. }
  27994. this._draw(subMesh, fillMode, this._overridenInstanceCount);
  27995. }
  27996. var visibleInstancesForSubMesh = batch.visibleInstances[subMesh._id];
  27997. if (visibleInstancesForSubMesh) {
  27998. for (var instanceIndex = 0; instanceIndex < visibleInstancesForSubMesh.length; instanceIndex++) {
  27999. var instance = visibleInstancesForSubMesh[instanceIndex];
  28000. // World
  28001. var world = instance.getWorldMatrix();
  28002. if (onBeforeDraw) {
  28003. onBeforeDraw(true, world, effectiveMaterial);
  28004. }
  28005. // Draw
  28006. this._draw(subMesh, fillMode);
  28007. }
  28008. }
  28009. }
  28010. return this;
  28011. };
  28012. /**
  28013. * Triggers the draw call for the mesh.
  28014. * Usually, you don't need to call this method by your own because the mesh rendering is handled by the scene rendering manager.
  28015. * Returns the Mesh.
  28016. */
  28017. Mesh.prototype.render = function (subMesh, enableAlphaMode) {
  28018. this.checkOcclusionQuery();
  28019. if (this._isOccluded) {
  28020. return this;
  28021. }
  28022. var scene = this.getScene();
  28023. // Managing instances
  28024. var batch = this._getInstancesRenderList(subMesh._id);
  28025. if (batch.mustReturn) {
  28026. return this;
  28027. }
  28028. // Checking geometry state
  28029. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  28030. return this;
  28031. }
  28032. this.onBeforeRenderObservable.notifyObservers(this);
  28033. var engine = scene.getEngine();
  28034. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  28035. // Material
  28036. var material = subMesh.getMaterial();
  28037. if (!material) {
  28038. return this;
  28039. }
  28040. this._effectiveMaterial = material;
  28041. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  28042. if (!this._effectiveMaterial.isReadyForSubMesh(this, subMesh, hardwareInstancedRendering)) {
  28043. return this;
  28044. }
  28045. }
  28046. else if (!this._effectiveMaterial.isReady(this, hardwareInstancedRendering)) {
  28047. return this;
  28048. }
  28049. // Alpha mode
  28050. if (enableAlphaMode) {
  28051. engine.setAlphaMode(this._effectiveMaterial.alphaMode);
  28052. }
  28053. // Outline - step 1
  28054. var savedDepthWrite = engine.getDepthWrite();
  28055. if (this.renderOutline) {
  28056. engine.setDepthWrite(false);
  28057. scene.getOutlineRenderer().render(subMesh, batch);
  28058. engine.setDepthWrite(savedDepthWrite);
  28059. }
  28060. var effect;
  28061. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  28062. effect = subMesh.effect;
  28063. }
  28064. else {
  28065. effect = this._effectiveMaterial.getEffect();
  28066. }
  28067. if (!effect) {
  28068. return this;
  28069. }
  28070. var sideOrientation = this.overrideMaterialSideOrientation;
  28071. if (sideOrientation == null) {
  28072. sideOrientation = this._effectiveMaterial.sideOrientation;
  28073. if (this._getWorldMatrixDeterminant() < 0) {
  28074. sideOrientation = (sideOrientation === BABYLON.Material.ClockWiseSideOrientation ? BABYLON.Material.CounterClockWiseSideOrientation : BABYLON.Material.ClockWiseSideOrientation);
  28075. }
  28076. }
  28077. var reverse = this._effectiveMaterial._preBind(effect, sideOrientation);
  28078. if (this._effectiveMaterial.forceDepthWrite) {
  28079. engine.setDepthWrite(true);
  28080. }
  28081. // Bind
  28082. var fillMode = scene.forcePointsCloud ? BABYLON.Material.PointFillMode : (scene.forceWireframe ? BABYLON.Material.WireFrameFillMode : this._effectiveMaterial.fillMode);
  28083. if (!hardwareInstancedRendering) {
  28084. this._bind(subMesh, effect, fillMode);
  28085. }
  28086. var world = this.getWorldMatrix();
  28087. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  28088. this._effectiveMaterial.bindForSubMesh(world, this, subMesh);
  28089. }
  28090. else {
  28091. this._effectiveMaterial.bind(world, this);
  28092. }
  28093. if (!this._effectiveMaterial.backFaceCulling && this._effectiveMaterial.separateCullingPass) {
  28094. engine.setState(true, this._effectiveMaterial.zOffset, false, !reverse);
  28095. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, this._onBeforeDraw, this._effectiveMaterial);
  28096. engine.setState(true, this._effectiveMaterial.zOffset, false, reverse);
  28097. }
  28098. // Draw
  28099. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, this._onBeforeDraw, this._effectiveMaterial);
  28100. // Unbind
  28101. this._effectiveMaterial.unbind();
  28102. // Outline - step 2
  28103. if (this.renderOutline && savedDepthWrite) {
  28104. engine.setDepthWrite(true);
  28105. engine.setColorWrite(false);
  28106. scene.getOutlineRenderer().render(subMesh, batch);
  28107. engine.setColorWrite(true);
  28108. }
  28109. // Overlay
  28110. if (this.renderOverlay) {
  28111. var currentMode = engine.getAlphaMode();
  28112. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  28113. scene.getOutlineRenderer().render(subMesh, batch, true);
  28114. engine.setAlphaMode(currentMode);
  28115. }
  28116. this.onAfterRenderObservable.notifyObservers(this);
  28117. return this;
  28118. };
  28119. Mesh.prototype._onBeforeDraw = function (isInstance, world, effectiveMaterial) {
  28120. if (isInstance && effectiveMaterial) {
  28121. effectiveMaterial.bindOnlyWorldMatrix(world);
  28122. }
  28123. };
  28124. /**
  28125. * Returns an array populated with ParticleSystem objects whose the mesh is the emitter.
  28126. */
  28127. Mesh.prototype.getEmittedParticleSystems = function () {
  28128. var results = new Array();
  28129. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  28130. var particleSystem = this.getScene().particleSystems[index];
  28131. if (particleSystem.emitter === this) {
  28132. results.push(particleSystem);
  28133. }
  28134. }
  28135. return results;
  28136. };
  28137. /**
  28138. * Returns an array populated with ParticleSystem objects whose the mesh or its children are the emitter.
  28139. */
  28140. Mesh.prototype.getHierarchyEmittedParticleSystems = function () {
  28141. var results = new Array();
  28142. var descendants = this.getDescendants();
  28143. descendants.push(this);
  28144. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  28145. var particleSystem = this.getScene().particleSystems[index];
  28146. var emitter = particleSystem.emitter;
  28147. if (emitter.position && descendants.indexOf(emitter) !== -1) {
  28148. results.push(particleSystem);
  28149. }
  28150. }
  28151. return results;
  28152. };
  28153. Mesh.prototype._checkDelayState = function () {
  28154. var scene = this.getScene();
  28155. if (this._geometry) {
  28156. this._geometry.load(scene);
  28157. }
  28158. else if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  28159. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  28160. this._queueLoad(scene);
  28161. }
  28162. return this;
  28163. };
  28164. Mesh.prototype._queueLoad = function (scene) {
  28165. var _this = this;
  28166. scene._addPendingData(this);
  28167. var getBinaryData = (this.delayLoadingFile.indexOf(".babylonbinarymeshdata") !== -1);
  28168. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  28169. if (data instanceof ArrayBuffer) {
  28170. _this._delayLoadingFunction(data, _this);
  28171. }
  28172. else {
  28173. _this._delayLoadingFunction(JSON.parse(data), _this);
  28174. }
  28175. _this.instances.forEach(function (instance) {
  28176. instance._syncSubMeshes();
  28177. });
  28178. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  28179. scene._removePendingData(_this);
  28180. }, function () { }, scene.database, getBinaryData);
  28181. return this;
  28182. };
  28183. /**
  28184. * Boolean, true is the mesh in the frustum defined by the Plane objects from the `frustumPlanes` array parameter.
  28185. */
  28186. Mesh.prototype.isInFrustum = function (frustumPlanes) {
  28187. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  28188. return false;
  28189. }
  28190. if (!_super.prototype.isInFrustum.call(this, frustumPlanes)) {
  28191. return false;
  28192. }
  28193. this._checkDelayState();
  28194. return true;
  28195. };
  28196. /**
  28197. * Sets the mesh material by the material or multiMaterial `id` property.
  28198. * The material `id` is a string identifying the material or the multiMaterial.
  28199. * This method returns the Mesh.
  28200. */
  28201. Mesh.prototype.setMaterialByID = function (id) {
  28202. var materials = this.getScene().materials;
  28203. var index;
  28204. for (index = materials.length - 1; index > -1; index--) {
  28205. if (materials[index].id === id) {
  28206. this.material = materials[index];
  28207. return this;
  28208. }
  28209. }
  28210. // Multi
  28211. var multiMaterials = this.getScene().multiMaterials;
  28212. for (index = multiMaterials.length - 1; index > -1; index--) {
  28213. if (multiMaterials[index].id === id) {
  28214. this.material = multiMaterials[index];
  28215. return this;
  28216. }
  28217. }
  28218. return this;
  28219. };
  28220. /**
  28221. * Returns as a new array populated with the mesh material and/or skeleton, if any.
  28222. */
  28223. Mesh.prototype.getAnimatables = function () {
  28224. var results = new Array();
  28225. if (this.material) {
  28226. results.push(this.material);
  28227. }
  28228. if (this.skeleton) {
  28229. results.push(this.skeleton);
  28230. }
  28231. return results;
  28232. };
  28233. /**
  28234. * Modifies the mesh geometry according to the passed transformation matrix.
  28235. * This method returns nothing but it really modifies the mesh even if it's originally not set as updatable.
  28236. * The mesh normals are modified accordingly the same transformation.
  28237. * tuto : http://doc.babylonjs.com/tutorials/How_Rotations_and_Translations_Work#baking-transform
  28238. * Note that, under the hood, this method sets a new VertexBuffer each call.
  28239. * Returns the Mesh.
  28240. */
  28241. Mesh.prototype.bakeTransformIntoVertices = function (transform) {
  28242. // Position
  28243. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  28244. return this;
  28245. }
  28246. var submeshes = this.subMeshes.splice(0);
  28247. this._resetPointsArrayCache();
  28248. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  28249. var temp = new Array();
  28250. var index;
  28251. for (index = 0; index < data.length; index += 3) {
  28252. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(data, index), transform).toArray(temp, index);
  28253. }
  28254. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable());
  28255. // Normals
  28256. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  28257. return this;
  28258. }
  28259. data = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  28260. temp = [];
  28261. for (index = 0; index < data.length; index += 3) {
  28262. BABYLON.Vector3.TransformNormal(BABYLON.Vector3.FromArray(data, index), transform).normalize().toArray(temp, index);
  28263. }
  28264. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable());
  28265. // flip faces?
  28266. if (transform.m[0] * transform.m[5] * transform.m[10] < 0) {
  28267. this.flipFaces();
  28268. }
  28269. // Restore submeshes
  28270. this.releaseSubMeshes();
  28271. this.subMeshes = submeshes;
  28272. return this;
  28273. };
  28274. /**
  28275. * Modifies the mesh geometry according to its own current World Matrix.
  28276. * The mesh World Matrix is then reset.
  28277. * This method returns nothing but really modifies the mesh even if it's originally not set as updatable.
  28278. * tuto : tuto : http://doc.babylonjs.com/resources/baking_transformations
  28279. * Note that, under the hood, this method sets a new VertexBuffer each call.
  28280. * Returns the Mesh.
  28281. */
  28282. Mesh.prototype.bakeCurrentTransformIntoVertices = function () {
  28283. this.bakeTransformIntoVertices(this.computeWorldMatrix(true));
  28284. this.scaling.copyFromFloats(1, 1, 1);
  28285. this.position.copyFromFloats(0, 0, 0);
  28286. this.rotation.copyFromFloats(0, 0, 0);
  28287. //only if quaternion is already set
  28288. if (this.rotationQuaternion) {
  28289. this.rotationQuaternion = BABYLON.Quaternion.Identity();
  28290. }
  28291. this._worldMatrix = BABYLON.Matrix.Identity();
  28292. return this;
  28293. };
  28294. Object.defineProperty(Mesh.prototype, "_positions", {
  28295. // Cache
  28296. get: function () {
  28297. if (this._geometry) {
  28298. return this._geometry._positions;
  28299. }
  28300. return null;
  28301. },
  28302. enumerable: true,
  28303. configurable: true
  28304. });
  28305. Mesh.prototype._resetPointsArrayCache = function () {
  28306. if (this._geometry) {
  28307. this._geometry._resetPointsArrayCache();
  28308. }
  28309. return this;
  28310. };
  28311. Mesh.prototype._generatePointsArray = function () {
  28312. if (this._geometry) {
  28313. return this._geometry._generatePointsArray();
  28314. }
  28315. return false;
  28316. };
  28317. /**
  28318. * Returns a new Mesh object generated from the current mesh properties.
  28319. * This method must not get confused with createInstance().
  28320. * The parameter `name` is a string, the name given to the new mesh.
  28321. * The optional parameter `newParent` can be any Node object (default `null`).
  28322. * The optional parameter `doNotCloneChildren` (default `false`) allows/denies the recursive cloning of the original mesh children if any.
  28323. * 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.
  28324. */
  28325. Mesh.prototype.clone = function (name, newParent, doNotCloneChildren, clonePhysicsImpostor) {
  28326. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  28327. return new Mesh(name, this.getScene(), newParent, this, doNotCloneChildren, clonePhysicsImpostor);
  28328. };
  28329. /**
  28330. * Disposes the Mesh.
  28331. * By default, all the mesh children are also disposed unless the parameter `doNotRecurse` is set to `true`.
  28332. * Returns nothing.
  28333. */
  28334. Mesh.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  28335. var _this = this;
  28336. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  28337. this.morphTargetManager = null;
  28338. if (this._geometry) {
  28339. this._geometry.releaseForMesh(this, true);
  28340. }
  28341. // Sources
  28342. var meshes = this.getScene().meshes;
  28343. meshes.forEach(function (abstractMesh) {
  28344. var mesh = abstractMesh;
  28345. if (mesh._source && mesh._source === _this) {
  28346. mesh._source = null;
  28347. }
  28348. });
  28349. this._source = null;
  28350. // Instances
  28351. if (this._instancesBuffer) {
  28352. this._instancesBuffer.dispose();
  28353. this._instancesBuffer = null;
  28354. }
  28355. while (this.instances.length) {
  28356. this.instances[0].dispose();
  28357. }
  28358. // Effect layers.
  28359. var effectLayers = this.getScene().effectLayers;
  28360. for (var i = 0; i < effectLayers.length; i++) {
  28361. var effectLayer = effectLayers[i];
  28362. if (effectLayer) {
  28363. effectLayer._disposeMesh(this);
  28364. }
  28365. }
  28366. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  28367. };
  28368. /**
  28369. * Modifies the mesh geometry according to a displacement map.
  28370. * 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.
  28371. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  28372. * This method returns nothing.
  28373. * The parameter `url` is a string, the URL from the image file is to be downloaded.
  28374. * The parameters `minHeight` and `maxHeight` are the lower and upper limits of the displacement.
  28375. * 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.
  28376. * The parameter `uvOffset` is an optional vector2 used to offset UV.
  28377. * The parameter `uvScale` is an optional vector2 used to scale UV.
  28378. *
  28379. * Returns the Mesh.
  28380. */
  28381. Mesh.prototype.applyDisplacementMap = function (url, minHeight, maxHeight, onSuccess, uvOffset, uvScale) {
  28382. var _this = this;
  28383. var scene = this.getScene();
  28384. var onload = function (img) {
  28385. // Getting height map data
  28386. var canvas = document.createElement("canvas");
  28387. var context = canvas.getContext("2d");
  28388. var heightMapWidth = img.width;
  28389. var heightMapHeight = img.height;
  28390. canvas.width = heightMapWidth;
  28391. canvas.height = heightMapHeight;
  28392. context.drawImage(img, 0, 0);
  28393. // Create VertexData from map data
  28394. //Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  28395. var buffer = context.getImageData(0, 0, heightMapWidth, heightMapHeight).data;
  28396. _this.applyDisplacementMapFromBuffer(buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight, uvOffset, uvScale);
  28397. //execute success callback, if set
  28398. if (onSuccess) {
  28399. onSuccess(_this);
  28400. }
  28401. };
  28402. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  28403. return this;
  28404. };
  28405. /**
  28406. * Modifies the mesh geometry according to a displacementMap buffer.
  28407. * 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.
  28408. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  28409. * This method returns nothing.
  28410. * 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.
  28411. * The parameters `heightMapWidth` and `heightMapHeight` are positive integers to set the width and height of the buffer image.
  28412. * The parameters `minHeight` and `maxHeight` are the lower and upper limits of the displacement.
  28413. * The parameter `uvOffset` is an optional vector2 used to offset UV.
  28414. * The parameter `uvScale` is an optional vector2 used to scale UV.
  28415. *
  28416. * Returns the Mesh.
  28417. */
  28418. Mesh.prototype.applyDisplacementMapFromBuffer = function (buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight, uvOffset, uvScale) {
  28419. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)
  28420. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)
  28421. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  28422. BABYLON.Tools.Warn("Cannot call applyDisplacementMap: Given mesh is not complete. Position, Normal or UV are missing");
  28423. return this;
  28424. }
  28425. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  28426. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  28427. var uvs = this.getVerticesData(BABYLON.VertexBuffer.UVKind);
  28428. var position = BABYLON.Vector3.Zero();
  28429. var normal = BABYLON.Vector3.Zero();
  28430. var uv = BABYLON.Vector2.Zero();
  28431. uvOffset = uvOffset || BABYLON.Vector2.Zero();
  28432. uvScale = uvScale || new BABYLON.Vector2(1, 1);
  28433. for (var index = 0; index < positions.length; index += 3) {
  28434. BABYLON.Vector3.FromArrayToRef(positions, index, position);
  28435. BABYLON.Vector3.FromArrayToRef(normals, index, normal);
  28436. BABYLON.Vector2.FromArrayToRef(uvs, (index / 3) * 2, uv);
  28437. // Compute height
  28438. var u = ((Math.abs(uv.x * uvScale.x + uvOffset.x) * heightMapWidth) % heightMapWidth) | 0;
  28439. var v = ((Math.abs(uv.y * uvScale.y + uvOffset.y) * heightMapHeight) % heightMapHeight) | 0;
  28440. var pos = (u + v * heightMapWidth) * 4;
  28441. var r = buffer[pos] / 255.0;
  28442. var g = buffer[pos + 1] / 255.0;
  28443. var b = buffer[pos + 2] / 255.0;
  28444. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  28445. normal.normalize();
  28446. normal.scaleInPlace(minHeight + (maxHeight - minHeight) * gradient);
  28447. position = position.add(normal);
  28448. position.toArray(positions, index);
  28449. }
  28450. BABYLON.VertexData.ComputeNormals(positions, this.getIndices(), normals);
  28451. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions);
  28452. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  28453. return this;
  28454. };
  28455. /**
  28456. * Modify the mesh to get a flat shading rendering.
  28457. * This means each mesh facet will then have its own normals. Usually new vertices are added in the mesh geometry to get this result.
  28458. * This method returns the Mesh.
  28459. * Warning : the mesh is really modified even if not set originally as updatable and, under the hood, a new VertexBuffer is allocated.
  28460. */
  28461. Mesh.prototype.convertToFlatShadedMesh = function () {
  28462. /// <summary>Update normals and vertices to get a flat shading rendering.</summary>
  28463. /// <summary>Warning: This may imply adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  28464. var kinds = this.getVerticesDataKinds();
  28465. var vbs = {};
  28466. var data = {};
  28467. var newdata = {};
  28468. var updatableNormals = false;
  28469. var kindIndex;
  28470. var kind;
  28471. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  28472. kind = kinds[kindIndex];
  28473. var vertexBuffer = this.getVertexBuffer(kind);
  28474. if (kind === BABYLON.VertexBuffer.NormalKind) {
  28475. updatableNormals = vertexBuffer.isUpdatable();
  28476. kinds.splice(kindIndex, 1);
  28477. kindIndex--;
  28478. continue;
  28479. }
  28480. vbs[kind] = vertexBuffer;
  28481. data[kind] = vbs[kind].getData();
  28482. newdata[kind] = [];
  28483. }
  28484. // Save previous submeshes
  28485. var previousSubmeshes = this.subMeshes.slice(0);
  28486. var indices = this.getIndices();
  28487. var totalIndices = this.getTotalIndices();
  28488. // Generating unique vertices per face
  28489. var index;
  28490. for (index = 0; index < totalIndices; index++) {
  28491. var vertexIndex = indices[index];
  28492. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  28493. kind = kinds[kindIndex];
  28494. var stride = vbs[kind].getStrideSize();
  28495. for (var offset = 0; offset < stride; offset++) {
  28496. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  28497. }
  28498. }
  28499. }
  28500. // Updating faces & normal
  28501. var normals = [];
  28502. var positions = newdata[BABYLON.VertexBuffer.PositionKind];
  28503. for (index = 0; index < totalIndices; index += 3) {
  28504. indices[index] = index;
  28505. indices[index + 1] = index + 1;
  28506. indices[index + 2] = index + 2;
  28507. var p1 = BABYLON.Vector3.FromArray(positions, index * 3);
  28508. var p2 = BABYLON.Vector3.FromArray(positions, (index + 1) * 3);
  28509. var p3 = BABYLON.Vector3.FromArray(positions, (index + 2) * 3);
  28510. var p1p2 = p1.subtract(p2);
  28511. var p3p2 = p3.subtract(p2);
  28512. var normal = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(p1p2, p3p2));
  28513. // Store same normals for every vertex
  28514. for (var localIndex = 0; localIndex < 3; localIndex++) {
  28515. normals.push(normal.x);
  28516. normals.push(normal.y);
  28517. normals.push(normal.z);
  28518. }
  28519. }
  28520. this.setIndices(indices);
  28521. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatableNormals);
  28522. // Updating vertex buffers
  28523. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  28524. kind = kinds[kindIndex];
  28525. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  28526. }
  28527. // Updating submeshes
  28528. this.releaseSubMeshes();
  28529. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  28530. var previousOne = previousSubmeshes[submeshIndex];
  28531. BABYLON.SubMesh.AddToMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  28532. }
  28533. this.synchronizeInstances();
  28534. return this;
  28535. };
  28536. /**
  28537. * This method removes all the mesh indices and add new vertices (duplication) in order to unfold facets into buffers.
  28538. * In other words, more vertices, no more indices and a single bigger VBO.
  28539. * The mesh is really modified even if not set originally as updatable. Under the hood, a new VertexBuffer is allocated.
  28540. * Returns the Mesh.
  28541. */
  28542. Mesh.prototype.convertToUnIndexedMesh = function () {
  28543. /// <summary>Remove indices by unfolding faces into buffers</summary>
  28544. /// <summary>Warning: This implies adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  28545. var kinds = this.getVerticesDataKinds();
  28546. var vbs = {};
  28547. var data = {};
  28548. var newdata = {};
  28549. var kindIndex;
  28550. var kind;
  28551. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  28552. kind = kinds[kindIndex];
  28553. var vertexBuffer = this.getVertexBuffer(kind);
  28554. vbs[kind] = vertexBuffer;
  28555. data[kind] = vbs[kind].getData();
  28556. newdata[kind] = [];
  28557. }
  28558. // Save previous submeshes
  28559. var previousSubmeshes = this.subMeshes.slice(0);
  28560. var indices = this.getIndices();
  28561. var totalIndices = this.getTotalIndices();
  28562. // Generating unique vertices per face
  28563. var index;
  28564. for (index = 0; index < totalIndices; index++) {
  28565. var vertexIndex = indices[index];
  28566. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  28567. kind = kinds[kindIndex];
  28568. var stride = vbs[kind].getStrideSize();
  28569. for (var offset = 0; offset < stride; offset++) {
  28570. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  28571. }
  28572. }
  28573. }
  28574. // Updating indices
  28575. for (index = 0; index < totalIndices; index += 3) {
  28576. indices[index] = index;
  28577. indices[index + 1] = index + 1;
  28578. indices[index + 2] = index + 2;
  28579. }
  28580. this.setIndices(indices);
  28581. // Updating vertex buffers
  28582. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  28583. kind = kinds[kindIndex];
  28584. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  28585. }
  28586. // Updating submeshes
  28587. this.releaseSubMeshes();
  28588. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  28589. var previousOne = previousSubmeshes[submeshIndex];
  28590. BABYLON.SubMesh.AddToMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  28591. }
  28592. this._unIndexed = true;
  28593. this.synchronizeInstances();
  28594. return this;
  28595. };
  28596. /**
  28597. * Inverses facet orientations and inverts also the normals with `flipNormals` (default `false`) if true.
  28598. * This method returns the Mesh.
  28599. * Warning : the mesh is really modified even if not set originally as updatable. A new VertexBuffer is created under the hood each call.
  28600. */
  28601. Mesh.prototype.flipFaces = function (flipNormals) {
  28602. if (flipNormals === void 0) { flipNormals = false; }
  28603. var vertex_data = BABYLON.VertexData.ExtractFromMesh(this);
  28604. var i;
  28605. if (flipNormals && this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind) && vertex_data.normals) {
  28606. for (i = 0; i < vertex_data.normals.length; i++) {
  28607. vertex_data.normals[i] *= -1;
  28608. }
  28609. }
  28610. if (vertex_data.indices) {
  28611. var temp;
  28612. for (i = 0; i < vertex_data.indices.length; i += 3) {
  28613. // reassign indices
  28614. temp = vertex_data.indices[i + 1];
  28615. vertex_data.indices[i + 1] = vertex_data.indices[i + 2];
  28616. vertex_data.indices[i + 2] = temp;
  28617. }
  28618. }
  28619. vertex_data.applyToMesh(this);
  28620. return this;
  28621. };
  28622. // Instances
  28623. /**
  28624. * Creates a new InstancedMesh object from the mesh model.
  28625. * An instance shares the same properties and the same material than its model.
  28626. * Only these properties of each instance can then be set individually :
  28627. * - position
  28628. * - rotation
  28629. * - rotationQuaternion
  28630. * - setPivotMatrix
  28631. * - scaling
  28632. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_Instances
  28633. * Warning : this method is not supported for Line mesh and LineSystem
  28634. */
  28635. Mesh.prototype.createInstance = function (name) {
  28636. return new BABYLON.InstancedMesh(name, this);
  28637. };
  28638. /**
  28639. * Synchronises all the mesh instance submeshes to the current mesh submeshes, if any.
  28640. * After this call, all the mesh instances have the same submeshes than the current mesh.
  28641. * This method returns the Mesh.
  28642. */
  28643. Mesh.prototype.synchronizeInstances = function () {
  28644. for (var instanceIndex = 0; instanceIndex < this.instances.length; instanceIndex++) {
  28645. var instance = this.instances[instanceIndex];
  28646. instance._syncSubMeshes();
  28647. }
  28648. return this;
  28649. };
  28650. /**
  28651. * Simplify the mesh according to the given array of settings.
  28652. * Function will return immediately and will simplify async. It returns the Mesh.
  28653. * @param settings a collection of simplification settings.
  28654. * @param parallelProcessing should all levels calculate parallel or one after the other.
  28655. * @param type the type of simplification to run.
  28656. * @param successCallback optional success callback to be called after the simplification finished processing all settings.
  28657. */
  28658. Mesh.prototype.simplify = function (settings, parallelProcessing, simplificationType, successCallback) {
  28659. if (parallelProcessing === void 0) { parallelProcessing = true; }
  28660. if (simplificationType === void 0) { simplificationType = BABYLON.SimplificationType.QUADRATIC; }
  28661. this.getScene().simplificationQueue.addTask({
  28662. settings: settings,
  28663. parallelProcessing: parallelProcessing,
  28664. mesh: this,
  28665. simplificationType: simplificationType,
  28666. successCallback: successCallback
  28667. });
  28668. return this;
  28669. };
  28670. /**
  28671. * Optimization of the mesh's indices, in case a mesh has duplicated vertices.
  28672. * The function will only reorder the indices and will not remove unused vertices to avoid problems with submeshes.
  28673. * This should be used together with the simplification to avoid disappearing triangles.
  28674. * Returns the Mesh.
  28675. * @param successCallback an optional success callback to be called after the optimization finished.
  28676. */
  28677. Mesh.prototype.optimizeIndices = function (successCallback) {
  28678. var _this = this;
  28679. var indices = this.getIndices();
  28680. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  28681. if (!positions || !indices) {
  28682. return this;
  28683. }
  28684. var vectorPositions = new Array();
  28685. for (var pos = 0; pos < positions.length; pos = pos + 3) {
  28686. vectorPositions.push(BABYLON.Vector3.FromArray(positions, pos));
  28687. }
  28688. var dupes = new Array();
  28689. BABYLON.AsyncLoop.SyncAsyncForLoop(vectorPositions.length, 40, function (iteration) {
  28690. var realPos = vectorPositions.length - 1 - iteration;
  28691. var testedPosition = vectorPositions[realPos];
  28692. for (var j = 0; j < realPos; ++j) {
  28693. var againstPosition = vectorPositions[j];
  28694. if (testedPosition.equals(againstPosition)) {
  28695. dupes[realPos] = j;
  28696. break;
  28697. }
  28698. }
  28699. }, function () {
  28700. for (var i = 0; i < indices.length; ++i) {
  28701. indices[i] = dupes[indices[i]] || indices[i];
  28702. }
  28703. //indices are now reordered
  28704. var originalSubMeshes = _this.subMeshes.slice(0);
  28705. _this.setIndices(indices);
  28706. _this.subMeshes = originalSubMeshes;
  28707. if (successCallback) {
  28708. successCallback(_this);
  28709. }
  28710. });
  28711. return this;
  28712. };
  28713. Mesh.prototype.serialize = function (serializationObject) {
  28714. serializationObject.name = this.name;
  28715. serializationObject.id = this.id;
  28716. serializationObject.type = this.getClassName();
  28717. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  28718. serializationObject.tags = BABYLON.Tags.GetTags(this);
  28719. }
  28720. serializationObject.position = this.position.asArray();
  28721. if (this.rotationQuaternion) {
  28722. serializationObject.rotationQuaternion = this.rotationQuaternion.asArray();
  28723. }
  28724. else if (this.rotation) {
  28725. serializationObject.rotation = this.rotation.asArray();
  28726. }
  28727. serializationObject.scaling = this.scaling.asArray();
  28728. serializationObject.localMatrix = this.getPivotMatrix().asArray();
  28729. serializationObject.isEnabled = this.isEnabled(false);
  28730. serializationObject.isVisible = this.isVisible;
  28731. serializationObject.infiniteDistance = this.infiniteDistance;
  28732. serializationObject.pickable = this.isPickable;
  28733. serializationObject.receiveShadows = this.receiveShadows;
  28734. serializationObject.billboardMode = this.billboardMode;
  28735. serializationObject.visibility = this.visibility;
  28736. serializationObject.checkCollisions = this.checkCollisions;
  28737. serializationObject.isBlocker = this.isBlocker;
  28738. // Parent
  28739. if (this.parent) {
  28740. serializationObject.parentId = this.parent.id;
  28741. }
  28742. // Geometry
  28743. serializationObject.isUnIndexed = this.isUnIndexed;
  28744. var geometry = this._geometry;
  28745. if (geometry) {
  28746. var geometryId = geometry.id;
  28747. serializationObject.geometryId = geometryId;
  28748. // SubMeshes
  28749. serializationObject.subMeshes = [];
  28750. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  28751. var subMesh = this.subMeshes[subIndex];
  28752. serializationObject.subMeshes.push({
  28753. materialIndex: subMesh.materialIndex,
  28754. verticesStart: subMesh.verticesStart,
  28755. verticesCount: subMesh.verticesCount,
  28756. indexStart: subMesh.indexStart,
  28757. indexCount: subMesh.indexCount
  28758. });
  28759. }
  28760. }
  28761. // Material
  28762. if (this.material) {
  28763. serializationObject.materialId = this.material.id;
  28764. }
  28765. else {
  28766. this.material = null;
  28767. }
  28768. // Morph targets
  28769. if (this.morphTargetManager) {
  28770. serializationObject.morphTargetManagerId = this.morphTargetManager.uniqueId;
  28771. }
  28772. // Skeleton
  28773. if (this.skeleton) {
  28774. serializationObject.skeletonId = this.skeleton.id;
  28775. }
  28776. // Physics
  28777. //TODO implement correct serialization for physics impostors.
  28778. var impostor = this.getPhysicsImpostor();
  28779. if (impostor) {
  28780. serializationObject.physicsMass = impostor.getParam("mass");
  28781. serializationObject.physicsFriction = impostor.getParam("friction");
  28782. serializationObject.physicsRestitution = impostor.getParam("mass");
  28783. serializationObject.physicsImpostor = impostor.type;
  28784. }
  28785. // Metadata
  28786. if (this.metadata) {
  28787. serializationObject.metadata = this.metadata;
  28788. }
  28789. // Instances
  28790. serializationObject.instances = [];
  28791. for (var index = 0; index < this.instances.length; index++) {
  28792. var instance = this.instances[index];
  28793. var serializationInstance = {
  28794. name: instance.name,
  28795. id: instance.id,
  28796. position: instance.position.asArray(),
  28797. scaling: instance.scaling.asArray()
  28798. };
  28799. if (instance.rotationQuaternion) {
  28800. serializationInstance.rotationQuaternion = instance.rotationQuaternion.asArray();
  28801. }
  28802. else if (instance.rotation) {
  28803. serializationInstance.rotation = instance.rotation.asArray();
  28804. }
  28805. serializationObject.instances.push(serializationInstance);
  28806. // Animations
  28807. BABYLON.Animation.AppendSerializedAnimations(instance, serializationInstance);
  28808. serializationInstance.ranges = instance.serializeAnimationRanges();
  28809. }
  28810. //
  28811. // Animations
  28812. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  28813. serializationObject.ranges = this.serializeAnimationRanges();
  28814. // Layer mask
  28815. serializationObject.layerMask = this.layerMask;
  28816. // Alpha
  28817. serializationObject.alphaIndex = this.alphaIndex;
  28818. serializationObject.hasVertexAlpha = this.hasVertexAlpha;
  28819. // Overlay
  28820. serializationObject.overlayAlpha = this.overlayAlpha;
  28821. serializationObject.overlayColor = this.overlayColor.asArray();
  28822. serializationObject.renderOverlay = this.renderOverlay;
  28823. // Fog
  28824. serializationObject.applyFog = this.applyFog;
  28825. // Action Manager
  28826. if (this.actionManager) {
  28827. serializationObject.actions = this.actionManager.serialize(this.name);
  28828. }
  28829. };
  28830. Mesh.prototype._syncGeometryWithMorphTargetManager = function () {
  28831. if (!this.geometry) {
  28832. return;
  28833. }
  28834. this._markSubMeshesAsAttributesDirty();
  28835. var morphTargetManager = this._morphTargetManager;
  28836. if (morphTargetManager && morphTargetManager.vertexCount) {
  28837. if (morphTargetManager.vertexCount !== this.getTotalVertices()) {
  28838. BABYLON.Tools.Error("Mesh is incompatible with morph targets. Targets and mesh must all have the same vertices count.");
  28839. this.morphTargetManager = null;
  28840. return;
  28841. }
  28842. for (var index = 0; index < morphTargetManager.numInfluencers; index++) {
  28843. var morphTarget = morphTargetManager.getActiveTarget(index);
  28844. var positions = morphTarget.getPositions();
  28845. if (!positions) {
  28846. BABYLON.Tools.Error("Invalid morph target. Target must have positions.");
  28847. return;
  28848. }
  28849. this.geometry.setVerticesData(BABYLON.VertexBuffer.PositionKind + index, positions, false, 3);
  28850. var normals = morphTarget.getNormals();
  28851. if (normals) {
  28852. this.geometry.setVerticesData(BABYLON.VertexBuffer.NormalKind + index, normals, false, 3);
  28853. }
  28854. var tangents = morphTarget.getTangents();
  28855. if (tangents) {
  28856. this.geometry.setVerticesData(BABYLON.VertexBuffer.TangentKind + index, tangents, false, 3);
  28857. }
  28858. }
  28859. }
  28860. else {
  28861. var index = 0;
  28862. // Positions
  28863. while (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind + index)) {
  28864. this.geometry.removeVerticesData(BABYLON.VertexBuffer.PositionKind + index);
  28865. if (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind + index)) {
  28866. this.geometry.removeVerticesData(BABYLON.VertexBuffer.NormalKind + index);
  28867. }
  28868. if (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind + index)) {
  28869. this.geometry.removeVerticesData(BABYLON.VertexBuffer.TangentKind + index);
  28870. }
  28871. index++;
  28872. }
  28873. }
  28874. };
  28875. // Statics
  28876. /**
  28877. * Returns a new Mesh object parsed from the source provided.
  28878. * The parameter `parsedMesh` is the source.
  28879. * The parameter `rootUrl` is a string, it's the root URL to prefix the `delayLoadingFile` property with
  28880. */
  28881. Mesh.Parse = function (parsedMesh, scene, rootUrl) {
  28882. var mesh;
  28883. if (parsedMesh.type && parsedMesh.type === "GroundMesh") {
  28884. mesh = BABYLON.GroundMesh.Parse(parsedMesh, scene);
  28885. }
  28886. else {
  28887. mesh = new Mesh(parsedMesh.name, scene);
  28888. }
  28889. mesh.id = parsedMesh.id;
  28890. if (BABYLON.Tags) {
  28891. BABYLON.Tags.AddTagsTo(mesh, parsedMesh.tags);
  28892. }
  28893. mesh.position = BABYLON.Vector3.FromArray(parsedMesh.position);
  28894. if (parsedMesh.metadata !== undefined) {
  28895. mesh.metadata = parsedMesh.metadata;
  28896. }
  28897. if (parsedMesh.rotationQuaternion) {
  28898. mesh.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedMesh.rotationQuaternion);
  28899. }
  28900. else if (parsedMesh.rotation) {
  28901. mesh.rotation = BABYLON.Vector3.FromArray(parsedMesh.rotation);
  28902. }
  28903. mesh.scaling = BABYLON.Vector3.FromArray(parsedMesh.scaling);
  28904. if (parsedMesh.localMatrix) {
  28905. mesh.setPreTransformMatrix(BABYLON.Matrix.FromArray(parsedMesh.localMatrix));
  28906. }
  28907. else if (parsedMesh.pivotMatrix) {
  28908. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.pivotMatrix));
  28909. }
  28910. mesh.setEnabled(parsedMesh.isEnabled);
  28911. mesh.isVisible = parsedMesh.isVisible;
  28912. mesh.infiniteDistance = parsedMesh.infiniteDistance;
  28913. mesh.showBoundingBox = parsedMesh.showBoundingBox;
  28914. mesh.showSubMeshesBoundingBox = parsedMesh.showSubMeshesBoundingBox;
  28915. if (parsedMesh.applyFog !== undefined) {
  28916. mesh.applyFog = parsedMesh.applyFog;
  28917. }
  28918. if (parsedMesh.pickable !== undefined) {
  28919. mesh.isPickable = parsedMesh.pickable;
  28920. }
  28921. if (parsedMesh.alphaIndex !== undefined) {
  28922. mesh.alphaIndex = parsedMesh.alphaIndex;
  28923. }
  28924. mesh.receiveShadows = parsedMesh.receiveShadows;
  28925. mesh.billboardMode = parsedMesh.billboardMode;
  28926. if (parsedMesh.visibility !== undefined) {
  28927. mesh.visibility = parsedMesh.visibility;
  28928. }
  28929. mesh.checkCollisions = parsedMesh.checkCollisions;
  28930. if (parsedMesh.isBlocker !== undefined) {
  28931. mesh.isBlocker = parsedMesh.isBlocker;
  28932. }
  28933. mesh._shouldGenerateFlatShading = parsedMesh.useFlatShading;
  28934. // freezeWorldMatrix
  28935. if (parsedMesh.freezeWorldMatrix) {
  28936. mesh._waitingFreezeWorldMatrix = parsedMesh.freezeWorldMatrix;
  28937. }
  28938. // Parent
  28939. if (parsedMesh.parentId) {
  28940. mesh._waitingParentId = parsedMesh.parentId;
  28941. }
  28942. // Actions
  28943. if (parsedMesh.actions !== undefined) {
  28944. mesh._waitingActions = parsedMesh.actions;
  28945. }
  28946. // Overlay
  28947. if (parsedMesh.overlayAlpha !== undefined) {
  28948. mesh.overlayAlpha = parsedMesh.overlayAlpha;
  28949. }
  28950. if (parsedMesh.overlayColor !== undefined) {
  28951. mesh.overlayColor = BABYLON.Color3.FromArray(parsedMesh.overlayColor);
  28952. }
  28953. if (parsedMesh.renderOverlay !== undefined) {
  28954. mesh.renderOverlay = parsedMesh.renderOverlay;
  28955. }
  28956. // Geometry
  28957. mesh.isUnIndexed = !!parsedMesh.isUnIndexed;
  28958. mesh.hasVertexAlpha = parsedMesh.hasVertexAlpha;
  28959. if (parsedMesh.delayLoadingFile) {
  28960. mesh.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  28961. mesh.delayLoadingFile = rootUrl + parsedMesh.delayLoadingFile;
  28962. mesh._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMaximum));
  28963. if (parsedMesh._binaryInfo) {
  28964. mesh._binaryInfo = parsedMesh._binaryInfo;
  28965. }
  28966. mesh._delayInfo = [];
  28967. if (parsedMesh.hasUVs) {
  28968. mesh._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  28969. }
  28970. if (parsedMesh.hasUVs2) {
  28971. mesh._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  28972. }
  28973. if (parsedMesh.hasUVs3) {
  28974. mesh._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  28975. }
  28976. if (parsedMesh.hasUVs4) {
  28977. mesh._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  28978. }
  28979. if (parsedMesh.hasUVs5) {
  28980. mesh._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  28981. }
  28982. if (parsedMesh.hasUVs6) {
  28983. mesh._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  28984. }
  28985. if (parsedMesh.hasColors) {
  28986. mesh._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  28987. }
  28988. if (parsedMesh.hasMatricesIndices) {
  28989. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  28990. }
  28991. if (parsedMesh.hasMatricesWeights) {
  28992. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  28993. }
  28994. mesh._delayLoadingFunction = BABYLON.Geometry._ImportGeometry;
  28995. if (BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental) {
  28996. mesh._checkDelayState();
  28997. }
  28998. }
  28999. else {
  29000. BABYLON.Geometry._ImportGeometry(parsedMesh, mesh);
  29001. }
  29002. // Material
  29003. if (parsedMesh.materialId) {
  29004. mesh.setMaterialByID(parsedMesh.materialId);
  29005. }
  29006. else {
  29007. mesh.material = null;
  29008. }
  29009. // Morph targets
  29010. if (parsedMesh.morphTargetManagerId > -1) {
  29011. mesh.morphTargetManager = scene.getMorphTargetManagerById(parsedMesh.morphTargetManagerId);
  29012. }
  29013. // Skeleton
  29014. if (parsedMesh.skeletonId > -1) {
  29015. mesh.skeleton = scene.getLastSkeletonByID(parsedMesh.skeletonId);
  29016. if (parsedMesh.numBoneInfluencers) {
  29017. mesh.numBoneInfluencers = parsedMesh.numBoneInfluencers;
  29018. }
  29019. }
  29020. // Animations
  29021. if (parsedMesh.animations) {
  29022. for (var animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  29023. var parsedAnimation = parsedMesh.animations[animationIndex];
  29024. mesh.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  29025. }
  29026. BABYLON.Node.ParseAnimationRanges(mesh, parsedMesh, scene);
  29027. }
  29028. if (parsedMesh.autoAnimate) {
  29029. scene.beginAnimation(mesh, parsedMesh.autoAnimateFrom, parsedMesh.autoAnimateTo, parsedMesh.autoAnimateLoop, parsedMesh.autoAnimateSpeed || 1.0);
  29030. }
  29031. // Layer Mask
  29032. if (parsedMesh.layerMask && (!isNaN(parsedMesh.layerMask))) {
  29033. mesh.layerMask = Math.abs(parseInt(parsedMesh.layerMask));
  29034. }
  29035. else {
  29036. mesh.layerMask = 0x0FFFFFFF;
  29037. }
  29038. // Physics
  29039. if (parsedMesh.physicsImpostor) {
  29040. mesh.physicsImpostor = new BABYLON.PhysicsImpostor(mesh, parsedMesh.physicsImpostor, {
  29041. mass: parsedMesh.physicsMass,
  29042. friction: parsedMesh.physicsFriction,
  29043. restitution: parsedMesh.physicsRestitution
  29044. }, scene);
  29045. }
  29046. // Instances
  29047. if (parsedMesh.instances) {
  29048. for (var index = 0; index < parsedMesh.instances.length; index++) {
  29049. var parsedInstance = parsedMesh.instances[index];
  29050. var instance = mesh.createInstance(parsedInstance.name);
  29051. if (parsedInstance.id) {
  29052. instance.id = parsedInstance.id;
  29053. }
  29054. if (BABYLON.Tags) {
  29055. BABYLON.Tags.AddTagsTo(instance, parsedInstance.tags);
  29056. }
  29057. instance.position = BABYLON.Vector3.FromArray(parsedInstance.position);
  29058. if (parsedInstance.parentId) {
  29059. instance._waitingParentId = parsedInstance.parentId;
  29060. }
  29061. if (parsedInstance.rotationQuaternion) {
  29062. instance.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedInstance.rotationQuaternion);
  29063. }
  29064. else if (parsedInstance.rotation) {
  29065. instance.rotation = BABYLON.Vector3.FromArray(parsedInstance.rotation);
  29066. }
  29067. instance.scaling = BABYLON.Vector3.FromArray(parsedInstance.scaling);
  29068. instance.checkCollisions = mesh.checkCollisions;
  29069. if (parsedMesh.animations) {
  29070. for (animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  29071. parsedAnimation = parsedMesh.animations[animationIndex];
  29072. instance.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  29073. }
  29074. BABYLON.Node.ParseAnimationRanges(instance, parsedMesh, scene);
  29075. }
  29076. }
  29077. }
  29078. return mesh;
  29079. };
  29080. /**
  29081. * Creates a ribbon mesh.
  29082. * Please consider using the same method from the MeshBuilder class instead.
  29083. * 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.
  29084. *
  29085. * Please read this full tutorial to understand how to design a ribbon : http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  29086. * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry.
  29087. * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array.
  29088. * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array.
  29089. * 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.
  29090. * 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.
  29091. * 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
  29092. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  29093. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  29094. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29095. */
  29096. Mesh.CreateRibbon = function (name, pathArray, closeArray, closePath, offset, scene, updatable, sideOrientation, instance) {
  29097. if (closeArray === void 0) { closeArray = false; }
  29098. if (updatable === void 0) { updatable = false; }
  29099. return BABYLON.MeshBuilder.CreateRibbon(name, {
  29100. pathArray: pathArray,
  29101. closeArray: closeArray,
  29102. closePath: closePath,
  29103. offset: offset,
  29104. updatable: updatable,
  29105. sideOrientation: sideOrientation,
  29106. instance: instance
  29107. }, scene);
  29108. };
  29109. /**
  29110. * Creates a plane polygonal mesh. By default, this is a disc.
  29111. * Please consider using the same method from the MeshBuilder class instead.
  29112. * The parameter `radius` sets the radius size (float) of the polygon (default 0.5).
  29113. * 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.
  29114. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  29115. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  29116. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29117. */
  29118. Mesh.CreateDisc = function (name, radius, tessellation, scene, updatable, sideOrientation) {
  29119. if (scene === void 0) { scene = null; }
  29120. var options = {
  29121. radius: radius,
  29122. tessellation: tessellation,
  29123. sideOrientation: sideOrientation,
  29124. updatable: updatable
  29125. };
  29126. return BABYLON.MeshBuilder.CreateDisc(name, options, scene);
  29127. };
  29128. /**
  29129. * Creates a box mesh.
  29130. * Please consider using the same method from the MeshBuilder class instead.
  29131. * The parameter `size` sets the size (float) of each box side (default 1).
  29132. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  29133. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  29134. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29135. */
  29136. Mesh.CreateBox = function (name, size, scene, updatable, sideOrientation) {
  29137. if (scene === void 0) { scene = null; }
  29138. var options = {
  29139. size: size,
  29140. sideOrientation: sideOrientation,
  29141. updatable: updatable
  29142. };
  29143. return BABYLON.MeshBuilder.CreateBox(name, options, scene);
  29144. };
  29145. /**
  29146. * Creates a sphere mesh.
  29147. * Please consider using the same method from the MeshBuilder class instead.
  29148. * The parameter `diameter` sets the diameter size (float) of the sphere (default 1).
  29149. * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32).
  29150. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  29151. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  29152. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29153. */
  29154. Mesh.CreateSphere = function (name, segments, diameter, scene, updatable, sideOrientation) {
  29155. var options = {
  29156. segments: segments,
  29157. diameterX: diameter,
  29158. diameterY: diameter,
  29159. diameterZ: diameter,
  29160. sideOrientation: sideOrientation,
  29161. updatable: updatable
  29162. };
  29163. return BABYLON.MeshBuilder.CreateSphere(name, options, scene);
  29164. };
  29165. /**
  29166. * Creates a cylinder or a cone mesh.
  29167. * Please consider using the same method from the MeshBuilder class instead.
  29168. * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  29169. * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  29170. * 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.
  29171. * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  29172. * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  29173. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  29174. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  29175. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29176. */
  29177. Mesh.CreateCylinder = function (name, height, diameterTop, diameterBottom, tessellation, subdivisions, scene, updatable, sideOrientation) {
  29178. if (scene === undefined || !(scene instanceof BABYLON.Scene)) {
  29179. if (scene !== undefined) {
  29180. sideOrientation = updatable || Mesh.DEFAULTSIDE;
  29181. updatable = scene;
  29182. }
  29183. scene = subdivisions;
  29184. subdivisions = 1;
  29185. }
  29186. var options = {
  29187. height: height,
  29188. diameterTop: diameterTop,
  29189. diameterBottom: diameterBottom,
  29190. tessellation: tessellation,
  29191. subdivisions: subdivisions,
  29192. sideOrientation: sideOrientation,
  29193. updatable: updatable
  29194. };
  29195. return BABYLON.MeshBuilder.CreateCylinder(name, options, scene);
  29196. };
  29197. // Torus (Code from SharpDX.org)
  29198. /**
  29199. * Creates a torus mesh.
  29200. * Please consider using the same method from the MeshBuilder class instead.
  29201. * The parameter `diameter` sets the diameter size (float) of the torus (default 1).
  29202. * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5).
  29203. * The parameter `tessellation` sets the number of torus sides (postive integer, default 16).
  29204. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  29205. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  29206. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29207. */
  29208. Mesh.CreateTorus = function (name, diameter, thickness, tessellation, scene, updatable, sideOrientation) {
  29209. var options = {
  29210. diameter: diameter,
  29211. thickness: thickness,
  29212. tessellation: tessellation,
  29213. sideOrientation: sideOrientation,
  29214. updatable: updatable
  29215. };
  29216. return BABYLON.MeshBuilder.CreateTorus(name, options, scene);
  29217. };
  29218. /**
  29219. * Creates a torus knot mesh.
  29220. * Please consider using the same method from the MeshBuilder class instead.
  29221. * The parameter `radius` sets the global radius size (float) of the torus knot (default 2).
  29222. * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32).
  29223. * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32).
  29224. * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3).
  29225. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  29226. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  29227. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29228. */
  29229. Mesh.CreateTorusKnot = function (name, radius, tube, radialSegments, tubularSegments, p, q, scene, updatable, sideOrientation) {
  29230. var options = {
  29231. radius: radius,
  29232. tube: tube,
  29233. radialSegments: radialSegments,
  29234. tubularSegments: tubularSegments,
  29235. p: p,
  29236. q: q,
  29237. sideOrientation: sideOrientation,
  29238. updatable: updatable
  29239. };
  29240. return BABYLON.MeshBuilder.CreateTorusKnot(name, options, scene);
  29241. };
  29242. /**
  29243. * Creates a line mesh.
  29244. * Please consider using the same method from the MeshBuilder class instead.
  29245. * 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.
  29246. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  29247. * The parameter `points` is an array successive Vector3.
  29248. * 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
  29249. * When updating an instance, remember that only point positions can change, not the number of points.
  29250. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29251. */
  29252. Mesh.CreateLines = function (name, points, scene, updatable, instance) {
  29253. if (scene === void 0) { scene = null; }
  29254. if (updatable === void 0) { updatable = false; }
  29255. if (instance === void 0) { instance = null; }
  29256. var options = {
  29257. points: points,
  29258. updatable: updatable,
  29259. instance: instance
  29260. };
  29261. return BABYLON.MeshBuilder.CreateLines(name, options, scene);
  29262. };
  29263. /**
  29264. * Creates a dashed line mesh.
  29265. * Please consider using the same method from the MeshBuilder class instead.
  29266. * 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.
  29267. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  29268. * The parameter `points` is an array successive Vector3.
  29269. * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200).
  29270. * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3).
  29271. * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1).
  29272. * 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
  29273. * When updating an instance, remember that only point positions can change, not the number of points.
  29274. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29275. */
  29276. Mesh.CreateDashedLines = function (name, points, dashSize, gapSize, dashNb, scene, updatable, instance) {
  29277. if (scene === void 0) { scene = null; }
  29278. var options = {
  29279. points: points,
  29280. dashSize: dashSize,
  29281. gapSize: gapSize,
  29282. dashNb: dashNb,
  29283. updatable: updatable,
  29284. instance: instance
  29285. };
  29286. return BABYLON.MeshBuilder.CreateDashedLines(name, options, scene);
  29287. };
  29288. /**
  29289. * Creates a polygon mesh.
  29290. * Please consider using the same method from the MeshBuilder class instead.
  29291. * The polygon's shape will depend on the input parameters and is constructed parallel to a ground mesh.
  29292. * 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.
  29293. * You can set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  29294. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29295. * Remember you can only change the shape positions, not their number when updating a polygon.
  29296. */
  29297. Mesh.CreatePolygon = function (name, shape, scene, holes, updatable, sideOrientation) {
  29298. var options = {
  29299. shape: shape,
  29300. holes: holes,
  29301. updatable: updatable,
  29302. sideOrientation: sideOrientation
  29303. };
  29304. return BABYLON.MeshBuilder.CreatePolygon(name, options, scene);
  29305. };
  29306. /**
  29307. * Creates an extruded polygon mesh, with depth in the Y direction.
  29308. * Please consider using the same method from the MeshBuilder class instead.
  29309. */
  29310. Mesh.ExtrudePolygon = function (name, shape, depth, scene, holes, updatable, sideOrientation) {
  29311. var options = {
  29312. shape: shape,
  29313. holes: holes,
  29314. depth: depth,
  29315. updatable: updatable,
  29316. sideOrientation: sideOrientation
  29317. };
  29318. return BABYLON.MeshBuilder.ExtrudePolygon(name, options, scene);
  29319. };
  29320. /**
  29321. * Creates an extruded shape mesh.
  29322. * 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.
  29323. * Please consider using the same method from the MeshBuilder class instead.
  29324. *
  29325. * Please read this full tutorial to understand how to design an extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  29326. * 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
  29327. * extruded along the Z axis.
  29328. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  29329. * 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.
  29330. * The parameter `scale` (float, default 1) is the value to scale the shape.
  29331. * 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
  29332. * 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
  29333. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  29334. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  29335. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  29336. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29337. */
  29338. Mesh.ExtrudeShape = function (name, shape, path, scale, rotation, cap, scene, updatable, sideOrientation, instance) {
  29339. if (scene === void 0) { scene = null; }
  29340. var options = {
  29341. shape: shape,
  29342. path: path,
  29343. scale: scale,
  29344. rotation: rotation,
  29345. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  29346. sideOrientation: sideOrientation,
  29347. instance: instance,
  29348. updatable: updatable
  29349. };
  29350. return BABYLON.MeshBuilder.ExtrudeShape(name, options, scene);
  29351. };
  29352. /**
  29353. * Creates an custom extruded shape mesh.
  29354. * 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.
  29355. * Please consider using the same method from the MeshBuilder class instead.
  29356. *
  29357. * Please read this full tutorial to understand how to design a custom extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  29358. * 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
  29359. * extruded along the Z axis.
  29360. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  29361. * 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
  29362. * and the distance of this point from the begining of the path :
  29363. * ```javascript
  29364. * var rotationFunction = function(i, distance) {
  29365. * // do things
  29366. * return rotationValue; }
  29367. * ```
  29368. * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  29369. * 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
  29370. * and the distance of this point from the begining of the path :
  29371. * ```javascript
  29372. * var scaleFunction = function(i, distance) {
  29373. * // do things
  29374. * return scaleValue;}
  29375. * ```
  29376. * It must returns a float value that will be the scale value applied to the shape on each path point.
  29377. * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`.
  29378. * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`.
  29379. * 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
  29380. * 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
  29381. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  29382. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  29383. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  29384. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29385. */
  29386. Mesh.ExtrudeShapeCustom = function (name, shape, path, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, cap, scene, updatable, sideOrientation, instance) {
  29387. var options = {
  29388. shape: shape,
  29389. path: path,
  29390. scaleFunction: scaleFunction,
  29391. rotationFunction: rotationFunction,
  29392. ribbonCloseArray: ribbonCloseArray,
  29393. ribbonClosePath: ribbonClosePath,
  29394. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  29395. sideOrientation: sideOrientation,
  29396. instance: instance,
  29397. updatable: updatable
  29398. };
  29399. return BABYLON.MeshBuilder.ExtrudeShapeCustom(name, options, scene);
  29400. };
  29401. /**
  29402. * Creates lathe mesh.
  29403. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe.
  29404. * Please consider using the same method from the MeshBuilder class instead.
  29405. * 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
  29406. * rotated around the Y axis. It's usually a 2D shape, so the Vector3 z coordinates are often set to zero.
  29407. * The parameter `radius` (positive float, default 1) is the radius value of the lathe.
  29408. * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe.
  29409. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  29410. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  29411. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29412. */
  29413. Mesh.CreateLathe = function (name, shape, radius, tessellation, scene, updatable, sideOrientation) {
  29414. var options = {
  29415. shape: shape,
  29416. radius: radius,
  29417. tessellation: tessellation,
  29418. sideOrientation: sideOrientation,
  29419. updatable: updatable
  29420. };
  29421. return BABYLON.MeshBuilder.CreateLathe(name, options, scene);
  29422. };
  29423. /**
  29424. * Creates a plane mesh.
  29425. * Please consider using the same method from the MeshBuilder class instead.
  29426. * The parameter `size` sets the size (float) of both sides of the plane at once (default 1).
  29427. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  29428. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  29429. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29430. */
  29431. Mesh.CreatePlane = function (name, size, scene, updatable, sideOrientation) {
  29432. var options = {
  29433. size: size,
  29434. width: size,
  29435. height: size,
  29436. sideOrientation: sideOrientation,
  29437. updatable: updatable
  29438. };
  29439. return BABYLON.MeshBuilder.CreatePlane(name, options, scene);
  29440. };
  29441. /**
  29442. * Creates a ground mesh.
  29443. * Please consider using the same method from the MeshBuilder class instead.
  29444. * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground.
  29445. * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side.
  29446. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29447. */
  29448. Mesh.CreateGround = function (name, width, height, subdivisions, scene, updatable) {
  29449. var options = {
  29450. width: width,
  29451. height: height,
  29452. subdivisions: subdivisions,
  29453. updatable: updatable
  29454. };
  29455. return BABYLON.MeshBuilder.CreateGround(name, options, scene);
  29456. };
  29457. /**
  29458. * Creates a tiled ground mesh.
  29459. * Please consider using the same method from the MeshBuilder class instead.
  29460. * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates.
  29461. * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates.
  29462. * The parameter `subdivisions` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 6, h: 6}`). `w` and `h` are the
  29463. * numbers of subdivisions on the ground width and height. Each subdivision is called a tile.
  29464. * The parameter `precision` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 2, h: 2}`). `w` and `h` are the
  29465. * numbers of subdivisions on the ground width and height of each tile.
  29466. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29467. */
  29468. Mesh.CreateTiledGround = function (name, xmin, zmin, xmax, zmax, subdivisions, precision, scene, updatable) {
  29469. var options = {
  29470. xmin: xmin,
  29471. zmin: zmin,
  29472. xmax: xmax,
  29473. zmax: zmax,
  29474. subdivisions: subdivisions,
  29475. precision: precision,
  29476. updatable: updatable
  29477. };
  29478. return BABYLON.MeshBuilder.CreateTiledGround(name, options, scene);
  29479. };
  29480. /**
  29481. * Creates a ground mesh from a height map.
  29482. * tuto : http://doc.babylonjs.com/tutorials/14._Height_Map
  29483. * Please consider using the same method from the MeshBuilder class instead.
  29484. * The parameter `url` sets the URL of the height map image resource.
  29485. * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  29486. * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  29487. * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  29488. * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  29489. * 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).
  29490. * This function is passed the newly built mesh :
  29491. * ```javascript
  29492. * function(mesh) { // do things
  29493. * return; }
  29494. * ```
  29495. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29496. */
  29497. Mesh.CreateGroundFromHeightMap = function (name, url, width, height, subdivisions, minHeight, maxHeight, scene, updatable, onReady) {
  29498. var options = {
  29499. width: width,
  29500. height: height,
  29501. subdivisions: subdivisions,
  29502. minHeight: minHeight,
  29503. maxHeight: maxHeight,
  29504. updatable: updatable,
  29505. onReady: onReady
  29506. };
  29507. return BABYLON.MeshBuilder.CreateGroundFromHeightMap(name, url, options, scene);
  29508. };
  29509. /**
  29510. * Creates a tube mesh.
  29511. * 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.
  29512. * Please consider using the same method from the MeshBuilder class instead.
  29513. * The parameter `path` is a required array of successive Vector3. It is the curve used as the axis of the tube.
  29514. * The parameter `radius` (positive float, default 1) sets the tube radius size.
  29515. * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface.
  29516. * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`.
  29517. * 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.
  29518. * It must return a radius value (positive float) :
  29519. * ```javascript
  29520. * var radiusFunction = function(i, distance) {
  29521. * // do things
  29522. * return radius; }
  29523. * ```
  29524. * 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
  29525. * 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
  29526. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  29527. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  29528. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29529. */
  29530. Mesh.CreateTube = function (name, path, radius, tessellation, radiusFunction, cap, scene, updatable, sideOrientation, instance) {
  29531. var options = {
  29532. path: path,
  29533. radius: radius,
  29534. tessellation: tessellation,
  29535. radiusFunction: radiusFunction,
  29536. arc: 1,
  29537. cap: cap,
  29538. updatable: updatable,
  29539. sideOrientation: sideOrientation,
  29540. instance: instance
  29541. };
  29542. return BABYLON.MeshBuilder.CreateTube(name, options, scene);
  29543. };
  29544. /**
  29545. * Creates a polyhedron mesh.
  29546. * Please consider using the same method from the MeshBuilder class instead.
  29547. * 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
  29548. * to choose the wanted type.
  29549. * The parameter `size` (positive float, default 1) sets the polygon size.
  29550. * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value).
  29551. * 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`.
  29552. * 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
  29553. * 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)`).
  29554. * 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
  29555. * 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.
  29556. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  29557. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  29558. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29559. */
  29560. Mesh.CreatePolyhedron = function (name, options, scene) {
  29561. return BABYLON.MeshBuilder.CreatePolyhedron(name, options, scene);
  29562. };
  29563. /**
  29564. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided.
  29565. * Please consider using the same method from the MeshBuilder class instead.
  29566. * The parameter `radius` sets the radius size (float) of the icosphere (default 1).
  29567. * 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`).
  29568. * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size.
  29569. * 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.
  29570. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  29571. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  29572. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29573. */
  29574. Mesh.CreateIcoSphere = function (name, options, scene) {
  29575. return BABYLON.MeshBuilder.CreateIcoSphere(name, options, scene);
  29576. };
  29577. /**
  29578. * Creates a decal mesh.
  29579. * Please consider using the same method from the MeshBuilder class instead.
  29580. * 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.
  29581. * The parameter `position` (Vector3, default `(0, 0, 0)`) sets the position of the decal in World coordinates.
  29582. * The parameter `normal` (Vector3, default Vector3.Up) sets the normal of the mesh where the decal is applied onto in World coordinates.
  29583. * The parameter `size` (Vector3, default `(1, 1, 1)`) sets the decal scaling.
  29584. * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal.
  29585. */
  29586. Mesh.CreateDecal = function (name, sourceMesh, position, normal, size, angle) {
  29587. var options = {
  29588. position: position,
  29589. normal: normal,
  29590. size: size,
  29591. angle: angle
  29592. };
  29593. return BABYLON.MeshBuilder.CreateDecal(name, sourceMesh, options);
  29594. };
  29595. // Skeletons
  29596. /**
  29597. * @returns original positions used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  29598. */
  29599. Mesh.prototype.setPositionsForCPUSkinning = function () {
  29600. if (!this._sourcePositions) {
  29601. var source = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  29602. if (!source) {
  29603. return this._sourcePositions;
  29604. }
  29605. this._sourcePositions = new Float32Array(source);
  29606. if (!this.isVertexBufferUpdatable(BABYLON.VertexBuffer.PositionKind)) {
  29607. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, source, true);
  29608. }
  29609. }
  29610. return this._sourcePositions;
  29611. };
  29612. /**
  29613. * @returns original normals used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  29614. */
  29615. Mesh.prototype.setNormalsForCPUSkinning = function () {
  29616. if (!this._sourceNormals) {
  29617. var source = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  29618. if (!source) {
  29619. return this._sourceNormals;
  29620. }
  29621. this._sourceNormals = new Float32Array(source);
  29622. if (!this.isVertexBufferUpdatable(BABYLON.VertexBuffer.NormalKind)) {
  29623. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, source, true);
  29624. }
  29625. }
  29626. return this._sourceNormals;
  29627. };
  29628. /**
  29629. * Updates the vertex buffer by applying transformation from the bones.
  29630. * Returns the Mesh.
  29631. *
  29632. * @param {skeleton} skeleton to apply
  29633. */
  29634. Mesh.prototype.applySkeleton = function (skeleton) {
  29635. if (!this.geometry) {
  29636. return this;
  29637. }
  29638. if (this.geometry._softwareSkinningRenderId == this.getScene().getRenderId()) {
  29639. return this;
  29640. }
  29641. this.geometry._softwareSkinningRenderId = this.getScene().getRenderId();
  29642. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  29643. return this;
  29644. }
  29645. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  29646. return this;
  29647. }
  29648. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  29649. return this;
  29650. }
  29651. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  29652. return this;
  29653. }
  29654. if (!this._sourcePositions) {
  29655. var submeshes = this.subMeshes.slice();
  29656. this.setPositionsForCPUSkinning();
  29657. this.subMeshes = submeshes;
  29658. }
  29659. if (!this._sourceNormals) {
  29660. this.setNormalsForCPUSkinning();
  29661. }
  29662. // positionsData checks for not being Float32Array will only pass at most once
  29663. var positionsData = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  29664. if (!positionsData) {
  29665. return this;
  29666. }
  29667. if (!(positionsData instanceof Float32Array)) {
  29668. positionsData = new Float32Array(positionsData);
  29669. }
  29670. // normalsData checks for not being Float32Array will only pass at most once
  29671. var normalsData = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  29672. if (!normalsData) {
  29673. return this;
  29674. }
  29675. if (!(normalsData instanceof Float32Array)) {
  29676. normalsData = new Float32Array(normalsData);
  29677. }
  29678. var matricesIndicesData = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  29679. var matricesWeightsData = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  29680. if (!matricesWeightsData || !matricesIndicesData) {
  29681. return this;
  29682. }
  29683. var needExtras = this.numBoneInfluencers > 4;
  29684. var matricesIndicesExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind) : null;
  29685. var matricesWeightsExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind) : null;
  29686. var skeletonMatrices = skeleton.getTransformMatrices(this);
  29687. var tempVector3 = BABYLON.Vector3.Zero();
  29688. var finalMatrix = new BABYLON.Matrix();
  29689. var tempMatrix = new BABYLON.Matrix();
  29690. var matWeightIdx = 0;
  29691. var inf;
  29692. for (var index = 0; index < positionsData.length; index += 3, matWeightIdx += 4) {
  29693. var weight;
  29694. for (inf = 0; inf < 4; inf++) {
  29695. weight = matricesWeightsData[matWeightIdx + inf];
  29696. if (weight > 0) {
  29697. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, matricesIndicesData[matWeightIdx + inf] * 16, weight, tempMatrix);
  29698. finalMatrix.addToSelf(tempMatrix);
  29699. }
  29700. else
  29701. break;
  29702. }
  29703. if (needExtras) {
  29704. for (inf = 0; inf < 4; inf++) {
  29705. weight = matricesWeightsExtraData[matWeightIdx + inf];
  29706. if (weight > 0) {
  29707. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, matricesIndicesExtraData[matWeightIdx + inf] * 16, weight, tempMatrix);
  29708. finalMatrix.addToSelf(tempMatrix);
  29709. }
  29710. else
  29711. break;
  29712. }
  29713. }
  29714. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(this._sourcePositions[index], this._sourcePositions[index + 1], this._sourcePositions[index + 2], finalMatrix, tempVector3);
  29715. tempVector3.toArray(positionsData, index);
  29716. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._sourceNormals[index], this._sourceNormals[index + 1], this._sourceNormals[index + 2], finalMatrix, tempVector3);
  29717. tempVector3.toArray(normalsData, index);
  29718. finalMatrix.reset();
  29719. }
  29720. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData);
  29721. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData);
  29722. return this;
  29723. };
  29724. // Tools
  29725. /**
  29726. * Returns an object `{min:` Vector3`, max:` Vector3`}`
  29727. * This min and max Vector3 are the minimum and maximum vectors of each mesh bounding box from the passed array, in the World system
  29728. */
  29729. Mesh.MinMax = function (meshes) {
  29730. var minVector = null;
  29731. var maxVector = null;
  29732. meshes.forEach(function (mesh, index, array) {
  29733. var boundingInfo = mesh.getBoundingInfo();
  29734. var boundingBox = boundingInfo.boundingBox;
  29735. if (!minVector || !maxVector) {
  29736. minVector = boundingBox.minimumWorld;
  29737. maxVector = boundingBox.maximumWorld;
  29738. }
  29739. else {
  29740. minVector.minimizeInPlace(boundingBox.minimumWorld);
  29741. maxVector.maximizeInPlace(boundingBox.maximumWorld);
  29742. }
  29743. });
  29744. if (!minVector || !maxVector) {
  29745. return {
  29746. min: BABYLON.Vector3.Zero(),
  29747. max: BABYLON.Vector3.Zero()
  29748. };
  29749. }
  29750. return {
  29751. min: minVector,
  29752. max: maxVector
  29753. };
  29754. };
  29755. /**
  29756. * Returns a Vector3, the center of the `{min:` Vector3`, max:` Vector3`}` or the center of MinMax vector3 computed from a mesh array.
  29757. */
  29758. Mesh.Center = function (meshesOrMinMaxVector) {
  29759. var minMaxVector = (meshesOrMinMaxVector instanceof Array) ? Mesh.MinMax(meshesOrMinMaxVector) : meshesOrMinMaxVector;
  29760. return BABYLON.Vector3.Center(minMaxVector.min, minMaxVector.max);
  29761. };
  29762. /**
  29763. * Merge the array of meshes into a single mesh for performance reasons.
  29764. * @param {Array<Mesh>} meshes - The vertices source. They should all be of the same material. Entries can empty
  29765. * @param {boolean} disposeSource - When true (default), dispose of the vertices from the source meshes
  29766. * @param {boolean} allow32BitsIndices - When the sum of the vertices > 64k, this must be set to true.
  29767. * @param {Mesh} meshSubclass - When set, vertices inserted into this Mesh. Meshes can then be merged into a Mesh sub-class.
  29768. * @param {boolean} subdivideWithSubMeshes - When true (false default), subdivide mesh to his subMesh array with meshes source.
  29769. */
  29770. Mesh.MergeMeshes = function (meshes, disposeSource, allow32BitsIndices, meshSubclass, subdivideWithSubMeshes) {
  29771. if (disposeSource === void 0) { disposeSource = true; }
  29772. var index;
  29773. if (!allow32BitsIndices) {
  29774. var totalVertices = 0;
  29775. // Counting vertices
  29776. for (index = 0; index < meshes.length; index++) {
  29777. if (meshes[index]) {
  29778. totalVertices += meshes[index].getTotalVertices();
  29779. if (totalVertices > 65536) {
  29780. BABYLON.Tools.Warn("Cannot merge meshes because resulting mesh will have more than 65536 vertices. Please use allow32BitsIndices = true to use 32 bits indices");
  29781. return null;
  29782. }
  29783. }
  29784. }
  29785. }
  29786. // Merge
  29787. var vertexData = null;
  29788. var otherVertexData;
  29789. var indiceArray = new Array();
  29790. var source = null;
  29791. for (index = 0; index < meshes.length; index++) {
  29792. if (meshes[index]) {
  29793. meshes[index].computeWorldMatrix(true);
  29794. otherVertexData = BABYLON.VertexData.ExtractFromMesh(meshes[index], true);
  29795. otherVertexData.transform(meshes[index].getWorldMatrix());
  29796. if (vertexData) {
  29797. vertexData.merge(otherVertexData);
  29798. }
  29799. else {
  29800. vertexData = otherVertexData;
  29801. source = meshes[index];
  29802. }
  29803. if (subdivideWithSubMeshes) {
  29804. indiceArray.push(meshes[index].getTotalIndices());
  29805. }
  29806. }
  29807. }
  29808. source = source;
  29809. if (!meshSubclass) {
  29810. meshSubclass = new Mesh(source.name + "_merged", source.getScene());
  29811. }
  29812. vertexData.applyToMesh(meshSubclass);
  29813. // Setting properties
  29814. meshSubclass.material = source.material;
  29815. meshSubclass.checkCollisions = source.checkCollisions;
  29816. // Cleaning
  29817. if (disposeSource) {
  29818. for (index = 0; index < meshes.length; index++) {
  29819. if (meshes[index]) {
  29820. meshes[index].dispose();
  29821. }
  29822. }
  29823. }
  29824. // Subdivide
  29825. if (subdivideWithSubMeshes) {
  29826. //-- Suppresions du submesh global
  29827. meshSubclass.releaseSubMeshes();
  29828. index = 0;
  29829. var offset = 0;
  29830. //-- aplique la subdivision en fonction du tableau d'indices
  29831. while (index < indiceArray.length) {
  29832. BABYLON.SubMesh.CreateFromIndices(0, offset, indiceArray[index], meshSubclass);
  29833. offset += indiceArray[index];
  29834. index++;
  29835. }
  29836. }
  29837. return meshSubclass;
  29838. };
  29839. // Consts
  29840. Mesh._FRONTSIDE = 0;
  29841. Mesh._BACKSIDE = 1;
  29842. Mesh._DOUBLESIDE = 2;
  29843. Mesh._DEFAULTSIDE = 0;
  29844. Mesh._NO_CAP = 0;
  29845. Mesh._CAP_START = 1;
  29846. Mesh._CAP_END = 2;
  29847. Mesh._CAP_ALL = 3;
  29848. return Mesh;
  29849. }(BABYLON.AbstractMesh));
  29850. BABYLON.Mesh = Mesh;
  29851. })(BABYLON || (BABYLON = {}));
  29852. //# sourceMappingURL=babylon.mesh.js.map
  29853. var BABYLON;
  29854. (function (BABYLON) {
  29855. var BaseSubMesh = /** @class */ (function () {
  29856. function BaseSubMesh() {
  29857. }
  29858. Object.defineProperty(BaseSubMesh.prototype, "effect", {
  29859. get: function () {
  29860. return this._materialEffect;
  29861. },
  29862. enumerable: true,
  29863. configurable: true
  29864. });
  29865. BaseSubMesh.prototype.setEffect = function (effect, defines) {
  29866. if (defines === void 0) { defines = null; }
  29867. if (this._materialEffect === effect) {
  29868. if (!effect) {
  29869. this._materialDefines = null;
  29870. }
  29871. return;
  29872. }
  29873. this._materialDefines = defines;
  29874. this._materialEffect = effect;
  29875. };
  29876. return BaseSubMesh;
  29877. }());
  29878. BABYLON.BaseSubMesh = BaseSubMesh;
  29879. var SubMesh = /** @class */ (function (_super) {
  29880. __extends(SubMesh, _super);
  29881. function SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  29882. if (createBoundingBox === void 0) { createBoundingBox = true; }
  29883. var _this = _super.call(this) || this;
  29884. _this.materialIndex = materialIndex;
  29885. _this.verticesStart = verticesStart;
  29886. _this.verticesCount = verticesCount;
  29887. _this.indexStart = indexStart;
  29888. _this.indexCount = indexCount;
  29889. _this._renderId = 0;
  29890. _this._mesh = mesh;
  29891. _this._renderingMesh = renderingMesh || mesh;
  29892. mesh.subMeshes.push(_this);
  29893. _this._trianglePlanes = [];
  29894. _this._id = mesh.subMeshes.length - 1;
  29895. if (createBoundingBox) {
  29896. _this.refreshBoundingInfo();
  29897. mesh.computeWorldMatrix(true);
  29898. }
  29899. return _this;
  29900. }
  29901. SubMesh.AddToMesh = function (materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  29902. if (createBoundingBox === void 0) { createBoundingBox = true; }
  29903. return new SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox);
  29904. };
  29905. Object.defineProperty(SubMesh.prototype, "IsGlobal", {
  29906. get: function () {
  29907. return (this.verticesStart === 0 && this.verticesCount == this._mesh.getTotalVertices());
  29908. },
  29909. enumerable: true,
  29910. configurable: true
  29911. });
  29912. /**
  29913. * Returns the submesh BoudingInfo object.
  29914. */
  29915. SubMesh.prototype.getBoundingInfo = function () {
  29916. if (this.IsGlobal) {
  29917. return this._mesh.getBoundingInfo();
  29918. }
  29919. return this._boundingInfo;
  29920. };
  29921. /**
  29922. * Sets the submesh BoundingInfo.
  29923. * Return the SubMesh.
  29924. */
  29925. SubMesh.prototype.setBoundingInfo = function (boundingInfo) {
  29926. this._boundingInfo = boundingInfo;
  29927. return this;
  29928. };
  29929. /**
  29930. * Returns the mesh of the current submesh.
  29931. */
  29932. SubMesh.prototype.getMesh = function () {
  29933. return this._mesh;
  29934. };
  29935. /**
  29936. * Returns the rendering mesh of the submesh.
  29937. */
  29938. SubMesh.prototype.getRenderingMesh = function () {
  29939. return this._renderingMesh;
  29940. };
  29941. /**
  29942. * Returns the submesh material.
  29943. */
  29944. SubMesh.prototype.getMaterial = function () {
  29945. var rootMaterial = this._renderingMesh.material;
  29946. if (rootMaterial === null || rootMaterial === undefined) {
  29947. return this._mesh.getScene().defaultMaterial;
  29948. }
  29949. else if (rootMaterial.getSubMaterial) {
  29950. var multiMaterial = rootMaterial;
  29951. var effectiveMaterial = multiMaterial.getSubMaterial(this.materialIndex);
  29952. if (this._currentMaterial !== effectiveMaterial) {
  29953. this._currentMaterial = effectiveMaterial;
  29954. this._materialDefines = null;
  29955. }
  29956. return effectiveMaterial;
  29957. }
  29958. return rootMaterial;
  29959. };
  29960. // Methods
  29961. /**
  29962. * Sets a new updated BoundingInfo object to the submesh.
  29963. * Returns the SubMesh.
  29964. */
  29965. SubMesh.prototype.refreshBoundingInfo = function () {
  29966. this._lastColliderWorldVertices = null;
  29967. if (this.IsGlobal || !this._renderingMesh || !this._renderingMesh.geometry) {
  29968. return this;
  29969. }
  29970. var data = this._renderingMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  29971. if (!data) {
  29972. this._boundingInfo = this._mesh.getBoundingInfo();
  29973. return this;
  29974. }
  29975. var indices = this._renderingMesh.getIndices();
  29976. var extend;
  29977. //is this the only submesh?
  29978. if (this.indexStart === 0 && this.indexCount === indices.length) {
  29979. var boundingInfo = this._renderingMesh.getBoundingInfo();
  29980. //the rendering mesh's bounding info can be used, it is the standard submesh for all indices.
  29981. extend = { minimum: boundingInfo.minimum.clone(), maximum: boundingInfo.maximum.clone() };
  29982. }
  29983. else {
  29984. extend = BABYLON.Tools.ExtractMinAndMaxIndexed(data, indices, this.indexStart, this.indexCount, this._renderingMesh.geometry.boundingBias);
  29985. }
  29986. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  29987. return this;
  29988. };
  29989. SubMesh.prototype._checkCollision = function (collider) {
  29990. var boundingInfo = this._renderingMesh.getBoundingInfo();
  29991. return boundingInfo._checkCollision(collider);
  29992. };
  29993. /**
  29994. * Updates the submesh BoundingInfo.
  29995. * Returns the Submesh.
  29996. */
  29997. SubMesh.prototype.updateBoundingInfo = function (world) {
  29998. var boundingInfo = this.getBoundingInfo();
  29999. if (!boundingInfo) {
  30000. this.refreshBoundingInfo();
  30001. boundingInfo = this.getBoundingInfo();
  30002. }
  30003. boundingInfo.update(world);
  30004. return this;
  30005. };
  30006. /**
  30007. * True is the submesh bounding box intersects the frustum defined by the passed array of planes.
  30008. * Boolean returned.
  30009. */
  30010. SubMesh.prototype.isInFrustum = function (frustumPlanes) {
  30011. var boundingInfo = this.getBoundingInfo();
  30012. if (!boundingInfo) {
  30013. return false;
  30014. }
  30015. return boundingInfo.isInFrustum(frustumPlanes);
  30016. };
  30017. /**
  30018. * True is the submesh bounding box is completely inside the frustum defined by the passed array of planes.
  30019. * Boolean returned.
  30020. */
  30021. SubMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  30022. var boundingInfo = this.getBoundingInfo();
  30023. if (!boundingInfo) {
  30024. return false;
  30025. }
  30026. return boundingInfo.isCompletelyInFrustum(frustumPlanes);
  30027. };
  30028. /**
  30029. * Renders the submesh.
  30030. * Returns it.
  30031. */
  30032. SubMesh.prototype.render = function (enableAlphaMode) {
  30033. this._renderingMesh.render(this, enableAlphaMode);
  30034. return this;
  30035. };
  30036. /**
  30037. * Returns a new Index Buffer.
  30038. * Type returned : WebGLBuffer.
  30039. */
  30040. SubMesh.prototype.getLinesIndexBuffer = function (indices, engine) {
  30041. if (!this._linesIndexBuffer) {
  30042. var linesIndices = [];
  30043. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  30044. linesIndices.push(indices[index], indices[index + 1], indices[index + 1], indices[index + 2], indices[index + 2], indices[index]);
  30045. }
  30046. this._linesIndexBuffer = engine.createIndexBuffer(linesIndices);
  30047. this.linesIndexCount = linesIndices.length;
  30048. }
  30049. return this._linesIndexBuffer;
  30050. };
  30051. /**
  30052. * True is the passed Ray intersects the submesh bounding box.
  30053. * Boolean returned.
  30054. */
  30055. SubMesh.prototype.canIntersects = function (ray) {
  30056. var boundingInfo = this.getBoundingInfo();
  30057. if (!boundingInfo) {
  30058. return false;
  30059. }
  30060. return ray.intersectsBox(boundingInfo.boundingBox);
  30061. };
  30062. /**
  30063. * Returns an object IntersectionInfo.
  30064. */
  30065. SubMesh.prototype.intersects = function (ray, positions, indices, fastCheck) {
  30066. var intersectInfo = null;
  30067. // LineMesh first as it's also a Mesh...
  30068. if (BABYLON.LinesMesh && this._mesh instanceof BABYLON.LinesMesh) {
  30069. var lineMesh = this._mesh;
  30070. // Line test
  30071. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 2) {
  30072. var p0 = positions[indices[index]];
  30073. var p1 = positions[indices[index + 1]];
  30074. var length = ray.intersectionSegment(p0, p1, lineMesh.intersectionThreshold);
  30075. if (length < 0) {
  30076. continue;
  30077. }
  30078. if (fastCheck || !intersectInfo || length < intersectInfo.distance) {
  30079. intersectInfo = new BABYLON.IntersectionInfo(null, null, length);
  30080. if (fastCheck) {
  30081. break;
  30082. }
  30083. }
  30084. }
  30085. }
  30086. else {
  30087. // Triangles test
  30088. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  30089. var p0 = positions[indices[index]];
  30090. var p1 = positions[indices[index + 1]];
  30091. var p2 = positions[indices[index + 2]];
  30092. var currentIntersectInfo = ray.intersectsTriangle(p0, p1, p2);
  30093. if (currentIntersectInfo) {
  30094. if (currentIntersectInfo.distance < 0) {
  30095. continue;
  30096. }
  30097. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  30098. intersectInfo = currentIntersectInfo;
  30099. intersectInfo.faceId = index / 3;
  30100. if (fastCheck) {
  30101. break;
  30102. }
  30103. }
  30104. }
  30105. }
  30106. }
  30107. return intersectInfo;
  30108. };
  30109. SubMesh.prototype._rebuild = function () {
  30110. if (this._linesIndexBuffer) {
  30111. this._linesIndexBuffer = null;
  30112. }
  30113. };
  30114. // Clone
  30115. /**
  30116. * Creates a new Submesh from the passed Mesh.
  30117. */
  30118. SubMesh.prototype.clone = function (newMesh, newRenderingMesh) {
  30119. var result = new SubMesh(this.materialIndex, this.verticesStart, this.verticesCount, this.indexStart, this.indexCount, newMesh, newRenderingMesh, false);
  30120. if (!this.IsGlobal) {
  30121. var boundingInfo = this.getBoundingInfo();
  30122. if (!boundingInfo) {
  30123. return result;
  30124. }
  30125. result._boundingInfo = new BABYLON.BoundingInfo(boundingInfo.minimum, boundingInfo.maximum);
  30126. }
  30127. return result;
  30128. };
  30129. // Dispose
  30130. /**
  30131. * Disposes the Submesh.
  30132. * Returns nothing.
  30133. */
  30134. SubMesh.prototype.dispose = function () {
  30135. if (this._linesIndexBuffer) {
  30136. this._mesh.getScene().getEngine()._releaseBuffer(this._linesIndexBuffer);
  30137. this._linesIndexBuffer = null;
  30138. }
  30139. // Remove from mesh
  30140. var index = this._mesh.subMeshes.indexOf(this);
  30141. this._mesh.subMeshes.splice(index, 1);
  30142. };
  30143. // Statics
  30144. /**
  30145. * Creates a new Submesh from the passed parameters :
  30146. * - materialIndex (integer) : the index of the main mesh material.
  30147. * - startIndex (integer) : the index where to start the copy in the mesh indices array.
  30148. * - indexCount (integer) : the number of indices to copy then from the startIndex.
  30149. * - mesh (Mesh) : the main mesh to create the submesh from.
  30150. * - renderingMesh (optional Mesh) : rendering mesh.
  30151. */
  30152. SubMesh.CreateFromIndices = function (materialIndex, startIndex, indexCount, mesh, renderingMesh) {
  30153. var minVertexIndex = Number.MAX_VALUE;
  30154. var maxVertexIndex = -Number.MAX_VALUE;
  30155. renderingMesh = (renderingMesh || mesh);
  30156. var indices = renderingMesh.getIndices();
  30157. for (var index = startIndex; index < startIndex + indexCount; index++) {
  30158. var vertexIndex = indices[index];
  30159. if (vertexIndex < minVertexIndex)
  30160. minVertexIndex = vertexIndex;
  30161. if (vertexIndex > maxVertexIndex)
  30162. maxVertexIndex = vertexIndex;
  30163. }
  30164. return new SubMesh(materialIndex, minVertexIndex, maxVertexIndex - minVertexIndex + 1, startIndex, indexCount, mesh, renderingMesh);
  30165. };
  30166. return SubMesh;
  30167. }(BaseSubMesh));
  30168. BABYLON.SubMesh = SubMesh;
  30169. })(BABYLON || (BABYLON = {}));
  30170. //# sourceMappingURL=babylon.subMesh.js.map
  30171. var __assign = (this && this.__assign) || Object.assign || function(t) {
  30172. for (var s, i = 1, n = arguments.length; i < n; i++) {
  30173. s = arguments[i];
  30174. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  30175. t[p] = s[p];
  30176. }
  30177. return t;
  30178. };
  30179. var BABYLON;
  30180. (function (BABYLON) {
  30181. /**
  30182. * Manages the defines for the Material.
  30183. */
  30184. var MaterialDefines = /** @class */ (function () {
  30185. function MaterialDefines() {
  30186. this._isDirty = true;
  30187. this._areLightsDirty = true;
  30188. this._areAttributesDirty = true;
  30189. this._areTexturesDirty = true;
  30190. this._areFresnelDirty = true;
  30191. this._areMiscDirty = true;
  30192. this._areImageProcessingDirty = true;
  30193. this._normals = false;
  30194. this._uvs = false;
  30195. this._needNormals = false;
  30196. this._needUVs = false;
  30197. }
  30198. Object.defineProperty(MaterialDefines.prototype, "isDirty", {
  30199. /**
  30200. * Specifies if the material needs to be re-calculated.
  30201. */
  30202. get: function () {
  30203. return this._isDirty;
  30204. },
  30205. enumerable: true,
  30206. configurable: true
  30207. });
  30208. /**
  30209. * Marks the material to indicate that it has been re-calculated.
  30210. */
  30211. MaterialDefines.prototype.markAsProcessed = function () {
  30212. this._isDirty = false;
  30213. this._areAttributesDirty = false;
  30214. this._areTexturesDirty = false;
  30215. this._areFresnelDirty = false;
  30216. this._areLightsDirty = false;
  30217. this._areMiscDirty = false;
  30218. this._areImageProcessingDirty = false;
  30219. };
  30220. /**
  30221. * Marks the material to indicate that it needs to be re-calculated.
  30222. */
  30223. MaterialDefines.prototype.markAsUnprocessed = function () {
  30224. this._isDirty = true;
  30225. };
  30226. /**
  30227. * Marks the material to indicate all of its defines need to be re-calculated.
  30228. */
  30229. MaterialDefines.prototype.markAllAsDirty = function () {
  30230. this._areTexturesDirty = true;
  30231. this._areAttributesDirty = true;
  30232. this._areLightsDirty = true;
  30233. this._areFresnelDirty = true;
  30234. this._areMiscDirty = true;
  30235. this._areImageProcessingDirty = true;
  30236. this._isDirty = true;
  30237. };
  30238. /**
  30239. * Marks the material to indicate that image processing needs to be re-calculated.
  30240. */
  30241. MaterialDefines.prototype.markAsImageProcessingDirty = function () {
  30242. this._areImageProcessingDirty = true;
  30243. this._isDirty = true;
  30244. };
  30245. /**
  30246. * Marks the material to indicate the lights need to be re-calculated.
  30247. */
  30248. MaterialDefines.prototype.markAsLightDirty = function () {
  30249. this._areLightsDirty = true;
  30250. this._isDirty = true;
  30251. };
  30252. /**
  30253. * Marks the attribute state as changed.
  30254. */
  30255. MaterialDefines.prototype.markAsAttributesDirty = function () {
  30256. this._areAttributesDirty = true;
  30257. this._isDirty = true;
  30258. };
  30259. /**
  30260. * Marks the texture state as changed.
  30261. */
  30262. MaterialDefines.prototype.markAsTexturesDirty = function () {
  30263. this._areTexturesDirty = true;
  30264. this._isDirty = true;
  30265. };
  30266. /**
  30267. * Marks the fresnel state as changed.
  30268. */
  30269. MaterialDefines.prototype.markAsFresnelDirty = function () {
  30270. this._areFresnelDirty = true;
  30271. this._isDirty = true;
  30272. };
  30273. /**
  30274. * Marks the misc state as changed.
  30275. */
  30276. MaterialDefines.prototype.markAsMiscDirty = function () {
  30277. this._areMiscDirty = true;
  30278. this._isDirty = true;
  30279. };
  30280. /**
  30281. * Rebuilds the material defines.
  30282. */
  30283. MaterialDefines.prototype.rebuild = function () {
  30284. if (this._keys) {
  30285. delete this._keys;
  30286. }
  30287. this._keys = [];
  30288. for (var _i = 0, _a = Object.keys(this); _i < _a.length; _i++) {
  30289. var key = _a[_i];
  30290. if (key[0] === "_") {
  30291. continue;
  30292. }
  30293. this._keys.push(key);
  30294. }
  30295. };
  30296. /**
  30297. * Specifies if two material defines are equal.
  30298. * @param other - A material define instance to compare to.
  30299. * @returns - Boolean indicating if the material defines are equal (true) or not (false).
  30300. */
  30301. MaterialDefines.prototype.isEqual = function (other) {
  30302. if (this._keys.length !== other._keys.length) {
  30303. return false;
  30304. }
  30305. for (var index = 0; index < this._keys.length; index++) {
  30306. var prop = this._keys[index];
  30307. if (this[prop] !== other[prop]) {
  30308. return false;
  30309. }
  30310. }
  30311. return true;
  30312. };
  30313. /**
  30314. * Clones this instance's defines to another instance.
  30315. * @param other - material defines to clone values to.
  30316. */
  30317. MaterialDefines.prototype.cloneTo = function (other) {
  30318. if (this._keys.length !== other._keys.length) {
  30319. other._keys = this._keys.slice(0);
  30320. }
  30321. for (var index = 0; index < this._keys.length; index++) {
  30322. var prop = this._keys[index];
  30323. other[prop] = this[prop];
  30324. }
  30325. };
  30326. /**
  30327. * Resets the material define values.
  30328. */
  30329. MaterialDefines.prototype.reset = function () {
  30330. for (var index = 0; index < this._keys.length; index++) {
  30331. var prop = this._keys[index];
  30332. if (typeof (this[prop]) === "number") {
  30333. this[prop] = 0;
  30334. }
  30335. else {
  30336. this[prop] = false;
  30337. }
  30338. }
  30339. };
  30340. /**
  30341. * Converts the material define values to a string.
  30342. * @returns - String of material define information.
  30343. */
  30344. MaterialDefines.prototype.toString = function () {
  30345. var result = "";
  30346. for (var index = 0; index < this._keys.length; index++) {
  30347. var prop = this._keys[index];
  30348. var value = this[prop];
  30349. if (typeof (value) === "number") {
  30350. result += "#define " + prop + " " + this[prop] + "\n";
  30351. }
  30352. else if (value) {
  30353. result += "#define " + prop + "\n";
  30354. }
  30355. }
  30356. return result;
  30357. };
  30358. return MaterialDefines;
  30359. }());
  30360. BABYLON.MaterialDefines = MaterialDefines;
  30361. /**
  30362. * This offers the main features of a material in BJS.
  30363. */
  30364. var Material = /** @class */ (function () {
  30365. /**
  30366. * Creates a material instance.
  30367. * @param name - The name of the material.
  30368. * @param scene - The BJS scene to reference.
  30369. * @param doNotAdd - Specifies if the material should be added to the scene.
  30370. */
  30371. function Material(name, scene, doNotAdd) {
  30372. /**
  30373. * Specifies if the ready state should be checked on each call.
  30374. */
  30375. this.checkReadyOnEveryCall = false;
  30376. /**
  30377. * Specifies if the ready state should be checked once.
  30378. */
  30379. this.checkReadyOnlyOnce = false;
  30380. /**
  30381. * The state of the material.
  30382. */
  30383. this.state = "";
  30384. /**
  30385. * The alpha value of the material.
  30386. */
  30387. this._alpha = 1.0;
  30388. /**
  30389. * Specifies if back face culling is enabled.
  30390. */
  30391. this._backFaceCulling = true;
  30392. /**
  30393. * Specifies if the material should be serialized.
  30394. */
  30395. this.doNotSerialize = false;
  30396. /**
  30397. * Specifies if the effect should be stored on sub meshes.
  30398. */
  30399. this.storeEffectOnSubMeshes = false;
  30400. /**
  30401. * An event triggered when the material is disposed.
  30402. * @type {BABYLON.Observable}
  30403. */
  30404. this.onDisposeObservable = new BABYLON.Observable();
  30405. /**
  30406. * An event triggered when the material is bound.
  30407. * @type {BABYLON.Observable}
  30408. */
  30409. this.onBindObservable = new BABYLON.Observable();
  30410. /**
  30411. * An event triggered when the material is unbound.
  30412. * @type {BABYLON.Observable}
  30413. */
  30414. this.onUnBindObservable = new BABYLON.Observable();
  30415. /**
  30416. * Stores the value of the alpha mode.
  30417. */
  30418. this._alphaMode = BABYLON.Engine.ALPHA_COMBINE;
  30419. /**
  30420. * Stores the state of the need depth pre-pass value.
  30421. */
  30422. this._needDepthPrePass = false;
  30423. /**
  30424. * Specifies if depth writing should be disabled.
  30425. */
  30426. this.disableDepthWrite = false;
  30427. /**
  30428. * Specifies if depth writing should be forced.
  30429. */
  30430. this.forceDepthWrite = false;
  30431. /**
  30432. * Specifies if there should be a separate pass for culling.
  30433. */
  30434. this.separateCullingPass = false;
  30435. /**
  30436. * Stores the state specifing if fog should be enabled.
  30437. */
  30438. this._fogEnabled = true;
  30439. /**
  30440. * Stores the size of points.
  30441. */
  30442. this.pointSize = 1.0;
  30443. /**
  30444. * Stores the z offset value.
  30445. */
  30446. this.zOffset = 0;
  30447. /**
  30448. * Specifies if the material was previously ready.
  30449. */
  30450. this._wasPreviouslyReady = false;
  30451. /**
  30452. * Stores the fill mode state.
  30453. */
  30454. this._fillMode = Material.TriangleFillMode;
  30455. this.name = name;
  30456. this.id = name || BABYLON.Tools.RandomId();
  30457. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  30458. if (this._scene.useRightHandedSystem) {
  30459. this.sideOrientation = Material.ClockWiseSideOrientation;
  30460. }
  30461. else {
  30462. this.sideOrientation = Material.CounterClockWiseSideOrientation;
  30463. }
  30464. this._uniformBuffer = new BABYLON.UniformBuffer(this._scene.getEngine());
  30465. this._useUBO = this.getScene().getEngine().supportsUniformBuffers;
  30466. if (!doNotAdd) {
  30467. this._scene.materials.push(this);
  30468. }
  30469. }
  30470. Object.defineProperty(Material, "TriangleFillMode", {
  30471. /**
  30472. * Returns the triangle fill mode.
  30473. */
  30474. get: function () {
  30475. return Material._TriangleFillMode;
  30476. },
  30477. enumerable: true,
  30478. configurable: true
  30479. });
  30480. Object.defineProperty(Material, "WireFrameFillMode", {
  30481. /**
  30482. * Returns the wireframe mode.
  30483. */
  30484. get: function () {
  30485. return Material._WireFrameFillMode;
  30486. },
  30487. enumerable: true,
  30488. configurable: true
  30489. });
  30490. Object.defineProperty(Material, "PointFillMode", {
  30491. /**
  30492. * Returns the point fill mode.
  30493. */
  30494. get: function () {
  30495. return Material._PointFillMode;
  30496. },
  30497. enumerable: true,
  30498. configurable: true
  30499. });
  30500. Object.defineProperty(Material, "PointListDrawMode", {
  30501. /**
  30502. * Returns the point list draw mode.
  30503. */
  30504. get: function () {
  30505. return Material._PointListDrawMode;
  30506. },
  30507. enumerable: true,
  30508. configurable: true
  30509. });
  30510. Object.defineProperty(Material, "LineListDrawMode", {
  30511. /**
  30512. * Returns the line list draw mode.
  30513. */
  30514. get: function () {
  30515. return Material._LineListDrawMode;
  30516. },
  30517. enumerable: true,
  30518. configurable: true
  30519. });
  30520. Object.defineProperty(Material, "LineLoopDrawMode", {
  30521. /**
  30522. * Returns the line loop draw mode.
  30523. */
  30524. get: function () {
  30525. return Material._LineLoopDrawMode;
  30526. },
  30527. enumerable: true,
  30528. configurable: true
  30529. });
  30530. Object.defineProperty(Material, "LineStripDrawMode", {
  30531. /**
  30532. * Returns the line strip draw mode.
  30533. */
  30534. get: function () {
  30535. return Material._LineStripDrawMode;
  30536. },
  30537. enumerable: true,
  30538. configurable: true
  30539. });
  30540. Object.defineProperty(Material, "TriangleStripDrawMode", {
  30541. /**
  30542. * Returns the triangle strip draw mode.
  30543. */
  30544. get: function () {
  30545. return Material._TriangleStripDrawMode;
  30546. },
  30547. enumerable: true,
  30548. configurable: true
  30549. });
  30550. Object.defineProperty(Material, "TriangleFanDrawMode", {
  30551. /**
  30552. * Returns the triangle fan draw mode.
  30553. */
  30554. get: function () {
  30555. return Material._TriangleFanDrawMode;
  30556. },
  30557. enumerable: true,
  30558. configurable: true
  30559. });
  30560. Object.defineProperty(Material, "ClockWiseSideOrientation", {
  30561. /**
  30562. * Returns the clock-wise side orientation.
  30563. */
  30564. get: function () {
  30565. return Material._ClockWiseSideOrientation;
  30566. },
  30567. enumerable: true,
  30568. configurable: true
  30569. });
  30570. Object.defineProperty(Material, "CounterClockWiseSideOrientation", {
  30571. /**
  30572. * Returns the counter clock-wise side orientation.
  30573. */
  30574. get: function () {
  30575. return Material._CounterClockWiseSideOrientation;
  30576. },
  30577. enumerable: true,
  30578. configurable: true
  30579. });
  30580. Object.defineProperty(Material, "TextureDirtyFlag", {
  30581. /**
  30582. * Returns the dirty texture flag value.
  30583. */
  30584. get: function () {
  30585. return Material._TextureDirtyFlag;
  30586. },
  30587. enumerable: true,
  30588. configurable: true
  30589. });
  30590. Object.defineProperty(Material, "LightDirtyFlag", {
  30591. /**
  30592. * Returns the dirty light flag value.
  30593. */
  30594. get: function () {
  30595. return Material._LightDirtyFlag;
  30596. },
  30597. enumerable: true,
  30598. configurable: true
  30599. });
  30600. Object.defineProperty(Material, "FresnelDirtyFlag", {
  30601. /**
  30602. * Returns the dirty fresnel flag value.
  30603. */
  30604. get: function () {
  30605. return Material._FresnelDirtyFlag;
  30606. },
  30607. enumerable: true,
  30608. configurable: true
  30609. });
  30610. Object.defineProperty(Material, "AttributesDirtyFlag", {
  30611. /**
  30612. * Returns the dirty attributes flag value.
  30613. */
  30614. get: function () {
  30615. return Material._AttributesDirtyFlag;
  30616. },
  30617. enumerable: true,
  30618. configurable: true
  30619. });
  30620. Object.defineProperty(Material, "MiscDirtyFlag", {
  30621. /**
  30622. * Returns the dirty misc flag value.
  30623. */
  30624. get: function () {
  30625. return Material._MiscDirtyFlag;
  30626. },
  30627. enumerable: true,
  30628. configurable: true
  30629. });
  30630. Object.defineProperty(Material.prototype, "alpha", {
  30631. /**
  30632. * Gets the alpha value of the material.
  30633. */
  30634. get: function () {
  30635. return this._alpha;
  30636. },
  30637. /**
  30638. * Sets the alpha value of the material.
  30639. */
  30640. set: function (value) {
  30641. if (this._alpha === value) {
  30642. return;
  30643. }
  30644. this._alpha = value;
  30645. this.markAsDirty(Material.MiscDirtyFlag);
  30646. },
  30647. enumerable: true,
  30648. configurable: true
  30649. });
  30650. Object.defineProperty(Material.prototype, "backFaceCulling", {
  30651. /**
  30652. * Gets the back-face culling state.
  30653. */
  30654. get: function () {
  30655. return this._backFaceCulling;
  30656. },
  30657. /**
  30658. * Sets the back-face culling state.
  30659. */
  30660. set: function (value) {
  30661. if (this._backFaceCulling === value) {
  30662. return;
  30663. }
  30664. this._backFaceCulling = value;
  30665. this.markAsDirty(Material.TextureDirtyFlag);
  30666. },
  30667. enumerable: true,
  30668. configurable: true
  30669. });
  30670. Object.defineProperty(Material.prototype, "onDispose", {
  30671. /**
  30672. * Called during a dispose event.
  30673. */
  30674. set: function (callback) {
  30675. if (this._onDisposeObserver) {
  30676. this.onDisposeObservable.remove(this._onDisposeObserver);
  30677. }
  30678. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  30679. },
  30680. enumerable: true,
  30681. configurable: true
  30682. });
  30683. Object.defineProperty(Material.prototype, "onBind", {
  30684. /**
  30685. * Called during a bind event.
  30686. */
  30687. set: function (callback) {
  30688. if (this._onBindObserver) {
  30689. this.onBindObservable.remove(this._onBindObserver);
  30690. }
  30691. this._onBindObserver = this.onBindObservable.add(callback);
  30692. },
  30693. enumerable: true,
  30694. configurable: true
  30695. });
  30696. Object.defineProperty(Material.prototype, "alphaMode", {
  30697. /**
  30698. * Gets the value of the alpha mode.
  30699. */
  30700. get: function () {
  30701. return this._alphaMode;
  30702. },
  30703. /**
  30704. * Sets the value of the alpha mode.
  30705. */
  30706. set: function (value) {
  30707. if (this._alphaMode === value) {
  30708. return;
  30709. }
  30710. this._alphaMode = value;
  30711. this.markAsDirty(Material.TextureDirtyFlag);
  30712. },
  30713. enumerable: true,
  30714. configurable: true
  30715. });
  30716. Object.defineProperty(Material.prototype, "needDepthPrePass", {
  30717. /**
  30718. * Gets the depth pre-pass value.
  30719. */
  30720. get: function () {
  30721. return this._needDepthPrePass;
  30722. },
  30723. /**
  30724. * Sets the need depth pre-pass value.
  30725. */
  30726. set: function (value) {
  30727. if (this._needDepthPrePass === value) {
  30728. return;
  30729. }
  30730. this._needDepthPrePass = value;
  30731. if (this._needDepthPrePass) {
  30732. this.checkReadyOnEveryCall = true;
  30733. }
  30734. },
  30735. enumerable: true,
  30736. configurable: true
  30737. });
  30738. Object.defineProperty(Material.prototype, "fogEnabled", {
  30739. /**
  30740. * Gets the value of the fog enabled state.
  30741. */
  30742. get: function () {
  30743. return this._fogEnabled;
  30744. },
  30745. /**
  30746. * Sets the state for enabling fog.
  30747. */
  30748. set: function (value) {
  30749. if (this._fogEnabled === value) {
  30750. return;
  30751. }
  30752. this._fogEnabled = value;
  30753. this.markAsDirty(Material.MiscDirtyFlag);
  30754. },
  30755. enumerable: true,
  30756. configurable: true
  30757. });
  30758. Object.defineProperty(Material.prototype, "wireframe", {
  30759. /**
  30760. * Gets a value specifying if wireframe mode is enabled.
  30761. */
  30762. get: function () {
  30763. return this._fillMode === Material.WireFrameFillMode;
  30764. },
  30765. /**
  30766. * Sets the state of wireframe mode.
  30767. */
  30768. set: function (value) {
  30769. this._fillMode = (value ? Material.WireFrameFillMode : Material.TriangleFillMode);
  30770. },
  30771. enumerable: true,
  30772. configurable: true
  30773. });
  30774. Object.defineProperty(Material.prototype, "pointsCloud", {
  30775. /**
  30776. * Gets the value specifying if point clouds are enabled.
  30777. */
  30778. get: function () {
  30779. return this._fillMode === Material.PointFillMode;
  30780. },
  30781. /**
  30782. * Sets the state of point cloud mode.
  30783. */
  30784. set: function (value) {
  30785. this._fillMode = (value ? Material.PointFillMode : Material.TriangleFillMode);
  30786. },
  30787. enumerable: true,
  30788. configurable: true
  30789. });
  30790. Object.defineProperty(Material.prototype, "fillMode", {
  30791. /**
  30792. * Gets the material fill mode.
  30793. */
  30794. get: function () {
  30795. return this._fillMode;
  30796. },
  30797. /**
  30798. * Sets the material fill mode.
  30799. */
  30800. set: function (value) {
  30801. if (this._fillMode === value) {
  30802. return;
  30803. }
  30804. this._fillMode = value;
  30805. this.markAsDirty(Material.MiscDirtyFlag);
  30806. },
  30807. enumerable: true,
  30808. configurable: true
  30809. });
  30810. /**
  30811. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  30812. * subclasses should override adding information pertainent to themselves.
  30813. * @returns - String with material information.
  30814. */
  30815. Material.prototype.toString = function (fullDetails) {
  30816. var ret = "Name: " + this.name;
  30817. if (fullDetails) {
  30818. }
  30819. return ret;
  30820. };
  30821. /**
  30822. * Gets the class name of the material.
  30823. * @returns - String with the class name of the material.
  30824. */
  30825. Material.prototype.getClassName = function () {
  30826. return "Material";
  30827. };
  30828. Object.defineProperty(Material.prototype, "isFrozen", {
  30829. /**
  30830. * Specifies if updates for the material been locked.
  30831. */
  30832. get: function () {
  30833. return this.checkReadyOnlyOnce;
  30834. },
  30835. enumerable: true,
  30836. configurable: true
  30837. });
  30838. /**
  30839. * Locks updates for the material.
  30840. */
  30841. Material.prototype.freeze = function () {
  30842. this.checkReadyOnlyOnce = true;
  30843. };
  30844. /**
  30845. * Unlocks updates for the material.
  30846. */
  30847. Material.prototype.unfreeze = function () {
  30848. this.checkReadyOnlyOnce = false;
  30849. };
  30850. /**
  30851. * Specifies if the material is ready to be used.
  30852. * @param mesh - BJS mesh.
  30853. * @param useInstances - Specifies if instances should be used.
  30854. * @returns - Boolean indicating if the material is ready to be used.
  30855. */
  30856. Material.prototype.isReady = function (mesh, useInstances) {
  30857. return true;
  30858. };
  30859. /**
  30860. * Specifies that the submesh is ready to be used.
  30861. * @param mesh - BJS mesh.
  30862. * @param subMesh - A submesh of the BJS mesh. Used to check if it is ready.
  30863. * @param useInstances - Specifies that instances should be used.
  30864. * @returns - boolean indicating that the submesh is ready or not.
  30865. */
  30866. Material.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  30867. return false;
  30868. };
  30869. /**
  30870. * Returns the material effect.
  30871. * @returns - Nullable material effect.
  30872. */
  30873. Material.prototype.getEffect = function () {
  30874. return this._effect;
  30875. };
  30876. /**
  30877. * Returns the BJS scene.
  30878. * @returns - BJS Scene.
  30879. */
  30880. Material.prototype.getScene = function () {
  30881. return this._scene;
  30882. };
  30883. /**
  30884. * Specifies if the material will require alpha blending
  30885. * @returns - Boolean specifying if alpha blending is needed.
  30886. */
  30887. Material.prototype.needAlphaBlending = function () {
  30888. return (this.alpha < 1.0);
  30889. };
  30890. /**
  30891. * Specifies if the mesh will require alpha blending.
  30892. * @param mesh - BJS mesh.
  30893. * @returns - Boolean specifying if alpha blending is needed for the mesh.
  30894. */
  30895. Material.prototype.needAlphaBlendingForMesh = function (mesh) {
  30896. return this.needAlphaBlending() || (mesh.visibility < 1.0) || mesh.hasVertexAlpha;
  30897. };
  30898. /**
  30899. * Specifies if this material should be rendered in alpha test mode.
  30900. * @returns - Boolean specifying if an alpha test is needed.
  30901. */
  30902. Material.prototype.needAlphaTesting = function () {
  30903. return false;
  30904. };
  30905. /**
  30906. * Gets the texture used for the alpha test.
  30907. * @returns - Nullable alpha test texture.
  30908. */
  30909. Material.prototype.getAlphaTestTexture = function () {
  30910. return null;
  30911. };
  30912. /**
  30913. * Marks the material to indicate that it needs to be re-calculated.
  30914. */
  30915. Material.prototype.markDirty = function () {
  30916. this._wasPreviouslyReady = false;
  30917. };
  30918. Material.prototype._preBind = function (effect, overrideOrientation) {
  30919. if (overrideOrientation === void 0) { overrideOrientation = null; }
  30920. var engine = this._scene.getEngine();
  30921. var orientation = (overrideOrientation == null) ? this.sideOrientation : overrideOrientation;
  30922. var reverse = orientation === Material.ClockWiseSideOrientation;
  30923. engine.enableEffect(effect ? effect : this._effect);
  30924. engine.setState(this.backFaceCulling, this.zOffset, false, reverse);
  30925. return reverse;
  30926. };
  30927. /**
  30928. * Binds the material to the mesh.
  30929. * @param world - World transformation matrix.
  30930. * @param mesh - Mesh to bind the material to.
  30931. */
  30932. Material.prototype.bind = function (world, mesh) {
  30933. };
  30934. /**
  30935. * Binds the submesh to the material.
  30936. * @param world - World transformation matrix.
  30937. * @param mesh - Mesh containing the submesh.
  30938. * @param subMesh - Submesh to bind the material to.
  30939. */
  30940. Material.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  30941. };
  30942. /**
  30943. * Binds the world matrix to the material.
  30944. * @param world - World transformation matrix.
  30945. */
  30946. Material.prototype.bindOnlyWorldMatrix = function (world) {
  30947. };
  30948. /**
  30949. * Binds the scene's uniform buffer to the effect.
  30950. * @param effect - Effect to bind to the scene uniform buffer.
  30951. * @param sceneUbo - Scene uniform buffer.
  30952. */
  30953. Material.prototype.bindSceneUniformBuffer = function (effect, sceneUbo) {
  30954. sceneUbo.bindToEffect(effect, "Scene");
  30955. };
  30956. /**
  30957. * Binds the view matrix to the effect.
  30958. * @param effect - Effect to bind the view matrix to.
  30959. */
  30960. Material.prototype.bindView = function (effect) {
  30961. if (!this._useUBO) {
  30962. effect.setMatrix("view", this.getScene().getViewMatrix());
  30963. }
  30964. else {
  30965. this.bindSceneUniformBuffer(effect, this.getScene().getSceneUniformBuffer());
  30966. }
  30967. };
  30968. /**
  30969. * Binds the view projection matrix to the effect.
  30970. * @param effect - Effect to bind the view projection matrix to.
  30971. */
  30972. Material.prototype.bindViewProjection = function (effect) {
  30973. if (!this._useUBO) {
  30974. effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  30975. }
  30976. else {
  30977. this.bindSceneUniformBuffer(effect, this.getScene().getSceneUniformBuffer());
  30978. }
  30979. };
  30980. /**
  30981. * Specifies if material alpha testing should be turned on for the mesh.
  30982. * @param mesh - BJS mesh.
  30983. */
  30984. Material.prototype._shouldTurnAlphaTestOn = function (mesh) {
  30985. return (!this.needAlphaBlendingForMesh(mesh) && this.needAlphaTesting());
  30986. };
  30987. /**
  30988. * Processes to execute after binding the material to a mesh.
  30989. * @param mesh - BJS mesh.
  30990. */
  30991. Material.prototype._afterBind = function (mesh) {
  30992. this._scene._cachedMaterial = this;
  30993. if (mesh) {
  30994. this._scene._cachedVisibility = mesh.visibility;
  30995. }
  30996. else {
  30997. this._scene._cachedVisibility = 1;
  30998. }
  30999. if (mesh) {
  31000. this.onBindObservable.notifyObservers(mesh);
  31001. }
  31002. if (this.disableDepthWrite) {
  31003. var engine = this._scene.getEngine();
  31004. this._cachedDepthWriteState = engine.getDepthWrite();
  31005. engine.setDepthWrite(false);
  31006. }
  31007. };
  31008. /**
  31009. * Unbinds the material from the mesh.
  31010. */
  31011. Material.prototype.unbind = function () {
  31012. this.onUnBindObservable.notifyObservers(this);
  31013. if (this.disableDepthWrite) {
  31014. var engine = this._scene.getEngine();
  31015. engine.setDepthWrite(this._cachedDepthWriteState);
  31016. }
  31017. };
  31018. /**
  31019. * Gets the active textures from the material.
  31020. * @returns - Array of textures.
  31021. */
  31022. Material.prototype.getActiveTextures = function () {
  31023. return [];
  31024. };
  31025. /**
  31026. * Specifies if the material uses a texture.
  31027. * @param texture - Texture to check against the material.
  31028. * @returns - Boolean specifying if the material uses the texture.
  31029. */
  31030. Material.prototype.hasTexture = function (texture) {
  31031. return false;
  31032. };
  31033. /**
  31034. * Makes a duplicate of the material, and gives it a new name.
  31035. * @param name - Name to call the duplicated material.
  31036. * @returns - Nullable cloned material
  31037. */
  31038. Material.prototype.clone = function (name) {
  31039. return null;
  31040. };
  31041. /**
  31042. * Gets the meshes bound to the material.
  31043. * @returns - Array of meshes bound to the material.
  31044. */
  31045. Material.prototype.getBindedMeshes = function () {
  31046. var result = new Array();
  31047. for (var index = 0; index < this._scene.meshes.length; index++) {
  31048. var mesh = this._scene.meshes[index];
  31049. if (mesh.material === this) {
  31050. result.push(mesh);
  31051. }
  31052. }
  31053. return result;
  31054. };
  31055. /**
  31056. * Force shader compilation
  31057. * @param mesh - BJS mesh.
  31058. * @param onCompiled - function to execute once the material is compiled.
  31059. * @param options - options to pass to this function.
  31060. */
  31061. Material.prototype.forceCompilation = function (mesh, onCompiled, options) {
  31062. var _this = this;
  31063. var localOptions = __assign({ clipPlane: false }, options);
  31064. var subMesh = new BABYLON.BaseSubMesh();
  31065. var scene = this.getScene();
  31066. var checkReady = function () {
  31067. if (!_this._scene || !_this._scene.getEngine()) {
  31068. return;
  31069. }
  31070. if (subMesh._materialDefines) {
  31071. subMesh._materialDefines._renderId = -1;
  31072. }
  31073. var clipPlaneState = scene.clipPlane;
  31074. if (localOptions.clipPlane) {
  31075. scene.clipPlane = new BABYLON.Plane(0, 0, 0, 1);
  31076. }
  31077. if (_this.storeEffectOnSubMeshes) {
  31078. if (_this.isReadyForSubMesh(mesh, subMesh)) {
  31079. if (onCompiled) {
  31080. onCompiled(_this);
  31081. }
  31082. }
  31083. else {
  31084. setTimeout(checkReady, 16);
  31085. }
  31086. }
  31087. else {
  31088. if (_this.isReady(mesh)) {
  31089. if (onCompiled) {
  31090. onCompiled(_this);
  31091. }
  31092. }
  31093. else {
  31094. setTimeout(checkReady, 16);
  31095. }
  31096. }
  31097. if (localOptions.clipPlane) {
  31098. scene.clipPlane = clipPlaneState;
  31099. }
  31100. };
  31101. checkReady();
  31102. };
  31103. /**
  31104. * Force shader compilation.
  31105. * @param mesh The mesh that will use this material
  31106. * @param options Additional options for compiling the shaders
  31107. * @returns A promise that resolves when the compilation completes
  31108. */
  31109. Material.prototype.forceCompilationAsync = function (mesh, options) {
  31110. var _this = this;
  31111. return new Promise(function (resolve) {
  31112. _this.forceCompilation(mesh, function () {
  31113. resolve();
  31114. }, options);
  31115. });
  31116. };
  31117. /**
  31118. * Marks a define in the material to indicate that it needs to be re-computed.
  31119. * @param flag - Material define flag.
  31120. */
  31121. Material.prototype.markAsDirty = function (flag) {
  31122. if (flag & Material.TextureDirtyFlag) {
  31123. this._markAllSubMeshesAsTexturesDirty();
  31124. }
  31125. if (flag & Material.LightDirtyFlag) {
  31126. this._markAllSubMeshesAsLightsDirty();
  31127. }
  31128. if (flag & Material.FresnelDirtyFlag) {
  31129. this._markAllSubMeshesAsFresnelDirty();
  31130. }
  31131. if (flag & Material.AttributesDirtyFlag) {
  31132. this._markAllSubMeshesAsAttributesDirty();
  31133. }
  31134. if (flag & Material.MiscDirtyFlag) {
  31135. this._markAllSubMeshesAsMiscDirty();
  31136. }
  31137. this.getScene().resetCachedMaterial();
  31138. };
  31139. /**
  31140. * Marks all submeshes of a material to indicate that their material defines need to be re-calculated.
  31141. * @param func - function which checks material defines against the submeshes.
  31142. */
  31143. Material.prototype._markAllSubMeshesAsDirty = function (func) {
  31144. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  31145. var mesh = _a[_i];
  31146. if (!mesh.subMeshes) {
  31147. continue;
  31148. }
  31149. for (var _b = 0, _c = mesh.subMeshes; _b < _c.length; _b++) {
  31150. var subMesh = _c[_b];
  31151. if (subMesh.getMaterial() !== this) {
  31152. continue;
  31153. }
  31154. if (!subMesh._materialDefines) {
  31155. continue;
  31156. }
  31157. func(subMesh._materialDefines);
  31158. }
  31159. }
  31160. };
  31161. /**
  31162. * Indicates that image processing needs to be re-calculated for all submeshes.
  31163. */
  31164. Material.prototype._markAllSubMeshesAsImageProcessingDirty = function () {
  31165. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsImageProcessingDirty(); });
  31166. };
  31167. /**
  31168. * Indicates that textures need to be re-calculated for all submeshes.
  31169. */
  31170. Material.prototype._markAllSubMeshesAsTexturesDirty = function () {
  31171. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsTexturesDirty(); });
  31172. };
  31173. /**
  31174. * Indicates that fresnel needs to be re-calculated for all submeshes.
  31175. */
  31176. Material.prototype._markAllSubMeshesAsFresnelDirty = function () {
  31177. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsFresnelDirty(); });
  31178. };
  31179. /**
  31180. * Indicates that fresnel and misc need to be re-calculated for all submeshes.
  31181. */
  31182. Material.prototype._markAllSubMeshesAsFresnelAndMiscDirty = function () {
  31183. this._markAllSubMeshesAsDirty(function (defines) {
  31184. defines.markAsFresnelDirty();
  31185. defines.markAsMiscDirty();
  31186. });
  31187. };
  31188. /**
  31189. * Indicates that lights need to be re-calculated for all submeshes.
  31190. */
  31191. Material.prototype._markAllSubMeshesAsLightsDirty = function () {
  31192. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsLightDirty(); });
  31193. };
  31194. /**
  31195. * Indicates that attributes need to be re-calculated for all submeshes.
  31196. */
  31197. Material.prototype._markAllSubMeshesAsAttributesDirty = function () {
  31198. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsAttributesDirty(); });
  31199. };
  31200. /**
  31201. * Indicates that misc needs to be re-calculated for all submeshes.
  31202. */
  31203. Material.prototype._markAllSubMeshesAsMiscDirty = function () {
  31204. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsMiscDirty(); });
  31205. };
  31206. /**
  31207. * Indicates that textures and misc need to be re-calculated for all submeshes.
  31208. */
  31209. Material.prototype._markAllSubMeshesAsTexturesAndMiscDirty = function () {
  31210. this._markAllSubMeshesAsDirty(function (defines) {
  31211. defines.markAsTexturesDirty();
  31212. defines.markAsMiscDirty();
  31213. });
  31214. };
  31215. /**
  31216. * Disposes the material.
  31217. * @param forceDisposeEffect - Specifies if effects should be force disposed.
  31218. * @param forceDisposeTextures - Specifies if textures should be force disposed.
  31219. */
  31220. Material.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  31221. // Animations
  31222. this.getScene().stopAnimation(this);
  31223. // Remove from scene
  31224. var index = this._scene.materials.indexOf(this);
  31225. if (index >= 0) {
  31226. this._scene.materials.splice(index, 1);
  31227. }
  31228. // Remove from meshes
  31229. for (index = 0; index < this._scene.meshes.length; index++) {
  31230. var mesh = this._scene.meshes[index];
  31231. if (mesh.material === this) {
  31232. mesh.material = null;
  31233. if (mesh.geometry) {
  31234. var geometry = (mesh.geometry);
  31235. if (this.storeEffectOnSubMeshes) {
  31236. for (var _i = 0, _a = mesh.subMeshes; _i < _a.length; _i++) {
  31237. var subMesh = _a[_i];
  31238. geometry._releaseVertexArrayObject(subMesh._materialEffect);
  31239. if (forceDisposeEffect && subMesh._materialEffect) {
  31240. this._scene.getEngine()._releaseEffect(subMesh._materialEffect);
  31241. }
  31242. }
  31243. }
  31244. else {
  31245. geometry._releaseVertexArrayObject(this._effect);
  31246. }
  31247. }
  31248. }
  31249. }
  31250. this._uniformBuffer.dispose();
  31251. // Shader are kept in cache for further use but we can get rid of this by using forceDisposeEffect
  31252. if (forceDisposeEffect && this._effect) {
  31253. if (!this.storeEffectOnSubMeshes) {
  31254. this._scene.getEngine()._releaseEffect(this._effect);
  31255. }
  31256. this._effect = null;
  31257. }
  31258. // Callback
  31259. this.onDisposeObservable.notifyObservers(this);
  31260. this.onDisposeObservable.clear();
  31261. this.onBindObservable.clear();
  31262. this.onUnBindObservable.clear();
  31263. };
  31264. /**
  31265. * Serializes this material.
  31266. * @returns - serialized material object.
  31267. */
  31268. Material.prototype.serialize = function () {
  31269. return BABYLON.SerializationHelper.Serialize(this);
  31270. };
  31271. /**
  31272. * Creates a MultiMaterial from parse MultiMaterial data.
  31273. * @param parsedMultiMaterial - Parsed MultiMaterial data.
  31274. * @param scene - BJS scene.
  31275. * @returns - MultiMaterial.
  31276. */
  31277. Material.ParseMultiMaterial = function (parsedMultiMaterial, scene) {
  31278. var multiMaterial = new BABYLON.MultiMaterial(parsedMultiMaterial.name, scene);
  31279. multiMaterial.id = parsedMultiMaterial.id;
  31280. if (BABYLON.Tags) {
  31281. BABYLON.Tags.AddTagsTo(multiMaterial, parsedMultiMaterial.tags);
  31282. }
  31283. for (var matIndex = 0; matIndex < parsedMultiMaterial.materials.length; matIndex++) {
  31284. var subMatId = parsedMultiMaterial.materials[matIndex];
  31285. if (subMatId) {
  31286. multiMaterial.subMaterials.push(scene.getMaterialByID(subMatId));
  31287. }
  31288. else {
  31289. multiMaterial.subMaterials.push(null);
  31290. }
  31291. }
  31292. return multiMaterial;
  31293. };
  31294. /**
  31295. * Creates a material from parsed material data.
  31296. * @param parsedMaterial - Parsed material data.
  31297. * @param scene - BJS scene.
  31298. * @param rootUrl - Root URL containing the material information.
  31299. * @returns - Parsed material.
  31300. */
  31301. Material.Parse = function (parsedMaterial, scene, rootUrl) {
  31302. if (!parsedMaterial.customType) {
  31303. return BABYLON.StandardMaterial.Parse(parsedMaterial, scene, rootUrl);
  31304. }
  31305. if (parsedMaterial.customType === "BABYLON.PBRMaterial" && parsedMaterial.overloadedAlbedo) {
  31306. parsedMaterial.customType = "BABYLON.LegacyPBRMaterial";
  31307. if (!BABYLON.LegacyPBRMaterial) {
  31308. BABYLON.Tools.Error("Your scene is trying to load a legacy version of the PBRMaterial, please, include it from the materials library.");
  31309. return;
  31310. }
  31311. }
  31312. var materialType = BABYLON.Tools.Instantiate(parsedMaterial.customType);
  31313. return materialType.Parse(parsedMaterial, scene, rootUrl);
  31314. ;
  31315. };
  31316. // Triangle views
  31317. Material._TriangleFillMode = 0;
  31318. Material._WireFrameFillMode = 1;
  31319. Material._PointFillMode = 2;
  31320. // Draw modes
  31321. Material._PointListDrawMode = 3;
  31322. Material._LineListDrawMode = 4;
  31323. Material._LineLoopDrawMode = 5;
  31324. Material._LineStripDrawMode = 6;
  31325. Material._TriangleStripDrawMode = 7;
  31326. Material._TriangleFanDrawMode = 8;
  31327. /**
  31328. * Stores the clock-wise side orientation.
  31329. */
  31330. Material._ClockWiseSideOrientation = 0;
  31331. /**
  31332. * Stores the counter clock-wise side orientation.
  31333. */
  31334. Material._CounterClockWiseSideOrientation = 1;
  31335. /**
  31336. * The dirty texture flag value.
  31337. */
  31338. Material._TextureDirtyFlag = 1;
  31339. /**
  31340. * The dirty light flag value.
  31341. */
  31342. Material._LightDirtyFlag = 2;
  31343. /**
  31344. * The dirty fresnel flag value.
  31345. */
  31346. Material._FresnelDirtyFlag = 4;
  31347. /**
  31348. * The dirty attribute flag value.
  31349. */
  31350. Material._AttributesDirtyFlag = 8;
  31351. /**
  31352. * The dirty misc flag value.
  31353. */
  31354. Material._MiscDirtyFlag = 16;
  31355. __decorate([
  31356. BABYLON.serialize()
  31357. ], Material.prototype, "id", void 0);
  31358. __decorate([
  31359. BABYLON.serialize()
  31360. ], Material.prototype, "name", void 0);
  31361. __decorate([
  31362. BABYLON.serialize()
  31363. ], Material.prototype, "checkReadyOnEveryCall", void 0);
  31364. __decorate([
  31365. BABYLON.serialize()
  31366. ], Material.prototype, "checkReadyOnlyOnce", void 0);
  31367. __decorate([
  31368. BABYLON.serialize()
  31369. ], Material.prototype, "state", void 0);
  31370. __decorate([
  31371. BABYLON.serialize("alpha")
  31372. ], Material.prototype, "_alpha", void 0);
  31373. __decorate([
  31374. BABYLON.serialize("backFaceCulling")
  31375. ], Material.prototype, "_backFaceCulling", void 0);
  31376. __decorate([
  31377. BABYLON.serialize()
  31378. ], Material.prototype, "sideOrientation", void 0);
  31379. __decorate([
  31380. BABYLON.serialize("alphaMode")
  31381. ], Material.prototype, "_alphaMode", void 0);
  31382. __decorate([
  31383. BABYLON.serialize()
  31384. ], Material.prototype, "_needDepthPrePass", void 0);
  31385. __decorate([
  31386. BABYLON.serialize()
  31387. ], Material.prototype, "disableDepthWrite", void 0);
  31388. __decorate([
  31389. BABYLON.serialize()
  31390. ], Material.prototype, "forceDepthWrite", void 0);
  31391. __decorate([
  31392. BABYLON.serialize()
  31393. ], Material.prototype, "separateCullingPass", void 0);
  31394. __decorate([
  31395. BABYLON.serialize("fogEnabled")
  31396. ], Material.prototype, "_fogEnabled", void 0);
  31397. __decorate([
  31398. BABYLON.serialize()
  31399. ], Material.prototype, "pointSize", void 0);
  31400. __decorate([
  31401. BABYLON.serialize()
  31402. ], Material.prototype, "zOffset", void 0);
  31403. __decorate([
  31404. BABYLON.serialize()
  31405. ], Material.prototype, "wireframe", null);
  31406. __decorate([
  31407. BABYLON.serialize()
  31408. ], Material.prototype, "pointsCloud", null);
  31409. __decorate([
  31410. BABYLON.serialize()
  31411. ], Material.prototype, "fillMode", null);
  31412. return Material;
  31413. }());
  31414. BABYLON.Material = Material;
  31415. })(BABYLON || (BABYLON = {}));
  31416. //# sourceMappingURL=babylon.material.js.map
  31417. var BABYLON;
  31418. (function (BABYLON) {
  31419. var UniformBuffer = /** @class */ (function () {
  31420. /**
  31421. * Uniform buffer objects.
  31422. *
  31423. * Handles blocks of uniform on the GPU.
  31424. *
  31425. * If WebGL 2 is not available, this class falls back on traditionnal setUniformXXX calls.
  31426. *
  31427. * For more information, please refer to :
  31428. * https://www.khronos.org/opengl/wiki/Uniform_Buffer_Object
  31429. */
  31430. function UniformBuffer(engine, data, dynamic) {
  31431. this._engine = engine;
  31432. this._noUBO = !engine.supportsUniformBuffers;
  31433. this._dynamic = dynamic;
  31434. this._data = data || [];
  31435. this._uniformLocations = {};
  31436. this._uniformSizes = {};
  31437. this._uniformLocationPointer = 0;
  31438. this._needSync = false;
  31439. if (this._noUBO) {
  31440. this.updateMatrix3x3 = this._updateMatrix3x3ForEffect;
  31441. this.updateMatrix2x2 = this._updateMatrix2x2ForEffect;
  31442. this.updateFloat = this._updateFloatForEffect;
  31443. this.updateFloat2 = this._updateFloat2ForEffect;
  31444. this.updateFloat3 = this._updateFloat3ForEffect;
  31445. this.updateFloat4 = this._updateFloat4ForEffect;
  31446. this.updateMatrix = this._updateMatrixForEffect;
  31447. this.updateVector3 = this._updateVector3ForEffect;
  31448. this.updateVector4 = this._updateVector4ForEffect;
  31449. this.updateColor3 = this._updateColor3ForEffect;
  31450. this.updateColor4 = this._updateColor4ForEffect;
  31451. }
  31452. else {
  31453. this._engine._uniformBuffers.push(this);
  31454. this.updateMatrix3x3 = this._updateMatrix3x3ForUniform;
  31455. this.updateMatrix2x2 = this._updateMatrix2x2ForUniform;
  31456. this.updateFloat = this._updateFloatForUniform;
  31457. this.updateFloat2 = this._updateFloat2ForUniform;
  31458. this.updateFloat3 = this._updateFloat3ForUniform;
  31459. this.updateFloat4 = this._updateFloat4ForUniform;
  31460. this.updateMatrix = this._updateMatrixForUniform;
  31461. this.updateVector3 = this._updateVector3ForUniform;
  31462. this.updateVector4 = this._updateVector4ForUniform;
  31463. this.updateColor3 = this._updateColor3ForUniform;
  31464. this.updateColor4 = this._updateColor4ForUniform;
  31465. }
  31466. }
  31467. Object.defineProperty(UniformBuffer.prototype, "useUbo", {
  31468. // Properties
  31469. /**
  31470. * Indicates if the buffer is using the WebGL2 UBO implementation,
  31471. * or just falling back on setUniformXXX calls.
  31472. */
  31473. get: function () {
  31474. return !this._noUBO;
  31475. },
  31476. enumerable: true,
  31477. configurable: true
  31478. });
  31479. Object.defineProperty(UniformBuffer.prototype, "isSync", {
  31480. /**
  31481. * Indicates if the WebGL underlying uniform buffer is in sync
  31482. * with the javascript cache data.
  31483. */
  31484. get: function () {
  31485. return !this._needSync;
  31486. },
  31487. enumerable: true,
  31488. configurable: true
  31489. });
  31490. /**
  31491. * Indicates if the WebGL underlying uniform buffer is dynamic.
  31492. * Also, a dynamic UniformBuffer will disable cache verification and always
  31493. * update the underlying WebGL uniform buffer to the GPU.
  31494. */
  31495. UniformBuffer.prototype.isDynamic = function () {
  31496. return this._dynamic !== undefined;
  31497. };
  31498. /**
  31499. * The data cache on JS side.
  31500. */
  31501. UniformBuffer.prototype.getData = function () {
  31502. return this._bufferData;
  31503. };
  31504. /**
  31505. * The underlying WebGL Uniform buffer.
  31506. */
  31507. UniformBuffer.prototype.getBuffer = function () {
  31508. return this._buffer;
  31509. };
  31510. /**
  31511. * std140 layout specifies how to align data within an UBO structure.
  31512. * See https://khronos.org/registry/OpenGL/specs/gl/glspec45.core.pdf#page=159
  31513. * for specs.
  31514. */
  31515. UniformBuffer.prototype._fillAlignment = function (size) {
  31516. // This code has been simplified because we only use floats, vectors of 1, 2, 3, 4 components
  31517. // and 4x4 matrices
  31518. // TODO : change if other types are used
  31519. var alignment;
  31520. if (size <= 2) {
  31521. alignment = size;
  31522. }
  31523. else {
  31524. alignment = 4;
  31525. }
  31526. if ((this._uniformLocationPointer % alignment) !== 0) {
  31527. var oldPointer = this._uniformLocationPointer;
  31528. this._uniformLocationPointer += alignment - (this._uniformLocationPointer % alignment);
  31529. var diff = this._uniformLocationPointer - oldPointer;
  31530. for (var i = 0; i < diff; i++) {
  31531. this._data.push(0);
  31532. }
  31533. }
  31534. };
  31535. /**
  31536. * Adds an uniform in the buffer.
  31537. * Warning : the subsequents calls of this function must be in the same order as declared in the shader
  31538. * for the layout to be correct !
  31539. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  31540. * @param {number|number[]} size Data size, or data directly.
  31541. */
  31542. UniformBuffer.prototype.addUniform = function (name, size) {
  31543. if (this._noUBO) {
  31544. return;
  31545. }
  31546. if (this._uniformLocations[name] !== undefined) {
  31547. // Already existing uniform
  31548. return;
  31549. }
  31550. // This function must be called in the order of the shader layout !
  31551. // size can be the size of the uniform, or data directly
  31552. var data;
  31553. if (size instanceof Array) {
  31554. data = size;
  31555. size = data.length;
  31556. }
  31557. else {
  31558. size = size;
  31559. data = [];
  31560. // Fill with zeros
  31561. for (var i = 0; i < size; i++) {
  31562. data.push(0);
  31563. }
  31564. }
  31565. this._fillAlignment(size);
  31566. this._uniformSizes[name] = size;
  31567. this._uniformLocations[name] = this._uniformLocationPointer;
  31568. this._uniformLocationPointer += size;
  31569. for (var i = 0; i < size; i++) {
  31570. this._data.push(data[i]);
  31571. }
  31572. this._needSync = true;
  31573. };
  31574. /**
  31575. * Wrapper for addUniform.
  31576. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  31577. * @param {Matrix} mat A 4x4 matrix.
  31578. */
  31579. UniformBuffer.prototype.addMatrix = function (name, mat) {
  31580. this.addUniform(name, Array.prototype.slice.call(mat.toArray()));
  31581. };
  31582. /**
  31583. * Wrapper for addUniform.
  31584. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  31585. * @param {number} x
  31586. * @param {number} y
  31587. */
  31588. UniformBuffer.prototype.addFloat2 = function (name, x, y) {
  31589. var temp = [x, y];
  31590. this.addUniform(name, temp);
  31591. };
  31592. /**
  31593. * Wrapper for addUniform.
  31594. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  31595. * @param {number} x
  31596. * @param {number} y
  31597. * @param {number} z
  31598. */
  31599. UniformBuffer.prototype.addFloat3 = function (name, x, y, z) {
  31600. var temp = [x, y, z];
  31601. this.addUniform(name, temp);
  31602. };
  31603. /**
  31604. * Wrapper for addUniform.
  31605. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  31606. * @param {Color3} color
  31607. */
  31608. UniformBuffer.prototype.addColor3 = function (name, color) {
  31609. var temp = new Array();
  31610. color.toArray(temp);
  31611. this.addUniform(name, temp);
  31612. };
  31613. /**
  31614. * Wrapper for addUniform.
  31615. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  31616. * @param {Color3} color
  31617. * @param {number} alpha
  31618. */
  31619. UniformBuffer.prototype.addColor4 = function (name, color, alpha) {
  31620. var temp = new Array();
  31621. color.toArray(temp);
  31622. temp.push(alpha);
  31623. this.addUniform(name, temp);
  31624. };
  31625. /**
  31626. * Wrapper for addUniform.
  31627. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  31628. * @param {Vector3} vector
  31629. */
  31630. UniformBuffer.prototype.addVector3 = function (name, vector) {
  31631. var temp = new Array();
  31632. vector.toArray(temp);
  31633. this.addUniform(name, temp);
  31634. };
  31635. /**
  31636. * Wrapper for addUniform.
  31637. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  31638. */
  31639. UniformBuffer.prototype.addMatrix3x3 = function (name) {
  31640. this.addUniform(name, 12);
  31641. };
  31642. /**
  31643. * Wrapper for addUniform.
  31644. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  31645. */
  31646. UniformBuffer.prototype.addMatrix2x2 = function (name) {
  31647. this.addUniform(name, 8);
  31648. };
  31649. /**
  31650. * Effectively creates the WebGL Uniform Buffer, once layout is completed with `addUniform`.
  31651. */
  31652. UniformBuffer.prototype.create = function () {
  31653. if (this._noUBO) {
  31654. return;
  31655. }
  31656. if (this._buffer) {
  31657. return; // nothing to do
  31658. }
  31659. // See spec, alignment must be filled as a vec4
  31660. this._fillAlignment(4);
  31661. this._bufferData = new Float32Array(this._data);
  31662. this._rebuild();
  31663. this._needSync = true;
  31664. };
  31665. UniformBuffer.prototype._rebuild = function () {
  31666. if (this._noUBO) {
  31667. return;
  31668. }
  31669. if (this._dynamic) {
  31670. this._buffer = this._engine.createDynamicUniformBuffer(this._bufferData);
  31671. }
  31672. else {
  31673. this._buffer = this._engine.createUniformBuffer(this._bufferData);
  31674. }
  31675. };
  31676. /**
  31677. * Updates the WebGL Uniform Buffer on the GPU.
  31678. * If the `dynamic` flag is set to true, no cache comparison is done.
  31679. * Otherwise, the buffer will be updated only if the cache differs.
  31680. */
  31681. UniformBuffer.prototype.update = function () {
  31682. if (!this._buffer) {
  31683. this.create();
  31684. return;
  31685. }
  31686. if (!this._dynamic && !this._needSync) {
  31687. return;
  31688. }
  31689. this._engine.updateUniformBuffer(this._buffer, this._bufferData);
  31690. this._needSync = false;
  31691. };
  31692. /**
  31693. * Updates the value of an uniform. The `update` method must be called afterwards to make it effective in the GPU.
  31694. * @param {string} uniformName Name of the uniform, as used in the uniform block in the shader.
  31695. * @param {number[]|Float32Array} data Flattened data
  31696. * @param {number} size Size of the data.
  31697. */
  31698. UniformBuffer.prototype.updateUniform = function (uniformName, data, size) {
  31699. var location = this._uniformLocations[uniformName];
  31700. if (location === undefined) {
  31701. if (this._buffer) {
  31702. // Cannot add an uniform if the buffer is already created
  31703. BABYLON.Tools.Error("Cannot add an uniform after UBO has been created.");
  31704. return;
  31705. }
  31706. this.addUniform(uniformName, size);
  31707. location = this._uniformLocations[uniformName];
  31708. }
  31709. if (!this._buffer) {
  31710. this.create();
  31711. }
  31712. if (!this._dynamic) {
  31713. // Cache for static uniform buffers
  31714. var changed = false;
  31715. for (var i = 0; i < size; i++) {
  31716. if (this._bufferData[location + i] !== data[i]) {
  31717. changed = true;
  31718. this._bufferData[location + i] = data[i];
  31719. }
  31720. }
  31721. this._needSync = this._needSync || changed;
  31722. }
  31723. else {
  31724. // No cache for dynamic
  31725. for (var i = 0; i < size; i++) {
  31726. this._bufferData[location + i] = data[i];
  31727. }
  31728. }
  31729. };
  31730. // Update methods
  31731. UniformBuffer.prototype._updateMatrix3x3ForUniform = function (name, matrix) {
  31732. // To match std140, matrix must be realigned
  31733. for (var i = 0; i < 3; i++) {
  31734. UniformBuffer._tempBuffer[i * 4] = matrix[i * 3];
  31735. UniformBuffer._tempBuffer[i * 4 + 1] = matrix[i * 3 + 1];
  31736. UniformBuffer._tempBuffer[i * 4 + 2] = matrix[i * 3 + 2];
  31737. UniformBuffer._tempBuffer[i * 4 + 3] = 0.0;
  31738. }
  31739. this.updateUniform(name, UniformBuffer._tempBuffer, 12);
  31740. };
  31741. UniformBuffer.prototype._updateMatrix3x3ForEffect = function (name, matrix) {
  31742. this._currentEffect.setMatrix3x3(name, matrix);
  31743. };
  31744. UniformBuffer.prototype._updateMatrix2x2ForEffect = function (name, matrix) {
  31745. this._currentEffect.setMatrix2x2(name, matrix);
  31746. };
  31747. UniformBuffer.prototype._updateMatrix2x2ForUniform = function (name, matrix) {
  31748. // To match std140, matrix must be realigned
  31749. for (var i = 0; i < 2; i++) {
  31750. UniformBuffer._tempBuffer[i * 4] = matrix[i * 2];
  31751. UniformBuffer._tempBuffer[i * 4 + 1] = matrix[i * 2 + 1];
  31752. UniformBuffer._tempBuffer[i * 4 + 2] = 0.0;
  31753. UniformBuffer._tempBuffer[i * 4 + 3] = 0.0;
  31754. }
  31755. this.updateUniform(name, UniformBuffer._tempBuffer, 8);
  31756. };
  31757. UniformBuffer.prototype._updateFloatForEffect = function (name, x) {
  31758. this._currentEffect.setFloat(name, x);
  31759. };
  31760. UniformBuffer.prototype._updateFloatForUniform = function (name, x) {
  31761. UniformBuffer._tempBuffer[0] = x;
  31762. this.updateUniform(name, UniformBuffer._tempBuffer, 1);
  31763. };
  31764. UniformBuffer.prototype._updateFloat2ForEffect = function (name, x, y, suffix) {
  31765. if (suffix === void 0) { suffix = ""; }
  31766. this._currentEffect.setFloat2(name + suffix, x, y);
  31767. };
  31768. UniformBuffer.prototype._updateFloat2ForUniform = function (name, x, y, suffix) {
  31769. if (suffix === void 0) { suffix = ""; }
  31770. UniformBuffer._tempBuffer[0] = x;
  31771. UniformBuffer._tempBuffer[1] = y;
  31772. this.updateUniform(name, UniformBuffer._tempBuffer, 2);
  31773. };
  31774. UniformBuffer.prototype._updateFloat3ForEffect = function (name, x, y, z, suffix) {
  31775. if (suffix === void 0) { suffix = ""; }
  31776. this._currentEffect.setFloat3(name + suffix, x, y, z);
  31777. };
  31778. UniformBuffer.prototype._updateFloat3ForUniform = function (name, x, y, z, suffix) {
  31779. if (suffix === void 0) { suffix = ""; }
  31780. UniformBuffer._tempBuffer[0] = x;
  31781. UniformBuffer._tempBuffer[1] = y;
  31782. UniformBuffer._tempBuffer[2] = z;
  31783. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  31784. };
  31785. UniformBuffer.prototype._updateFloat4ForEffect = function (name, x, y, z, w, suffix) {
  31786. if (suffix === void 0) { suffix = ""; }
  31787. this._currentEffect.setFloat4(name + suffix, x, y, z, w);
  31788. };
  31789. UniformBuffer.prototype._updateFloat4ForUniform = function (name, x, y, z, w, suffix) {
  31790. if (suffix === void 0) { suffix = ""; }
  31791. UniformBuffer._tempBuffer[0] = x;
  31792. UniformBuffer._tempBuffer[1] = y;
  31793. UniformBuffer._tempBuffer[2] = z;
  31794. UniformBuffer._tempBuffer[3] = w;
  31795. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  31796. };
  31797. UniformBuffer.prototype._updateMatrixForEffect = function (name, mat) {
  31798. this._currentEffect.setMatrix(name, mat);
  31799. };
  31800. UniformBuffer.prototype._updateMatrixForUniform = function (name, mat) {
  31801. this.updateUniform(name, mat.toArray(), 16);
  31802. };
  31803. UniformBuffer.prototype._updateVector3ForEffect = function (name, vector) {
  31804. this._currentEffect.setVector3(name, vector);
  31805. };
  31806. UniformBuffer.prototype._updateVector3ForUniform = function (name, vector) {
  31807. vector.toArray(UniformBuffer._tempBuffer);
  31808. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  31809. };
  31810. UniformBuffer.prototype._updateVector4ForEffect = function (name, vector) {
  31811. this._currentEffect.setVector4(name, vector);
  31812. };
  31813. UniformBuffer.prototype._updateVector4ForUniform = function (name, vector) {
  31814. vector.toArray(UniformBuffer._tempBuffer);
  31815. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  31816. };
  31817. UniformBuffer.prototype._updateColor3ForEffect = function (name, color, suffix) {
  31818. if (suffix === void 0) { suffix = ""; }
  31819. this._currentEffect.setColor3(name + suffix, color);
  31820. };
  31821. UniformBuffer.prototype._updateColor3ForUniform = function (name, color, suffix) {
  31822. if (suffix === void 0) { suffix = ""; }
  31823. color.toArray(UniformBuffer._tempBuffer);
  31824. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  31825. };
  31826. UniformBuffer.prototype._updateColor4ForEffect = function (name, color, alpha, suffix) {
  31827. if (suffix === void 0) { suffix = ""; }
  31828. this._currentEffect.setColor4(name + suffix, color, alpha);
  31829. };
  31830. UniformBuffer.prototype._updateColor4ForUniform = function (name, color, alpha, suffix) {
  31831. if (suffix === void 0) { suffix = ""; }
  31832. color.toArray(UniformBuffer._tempBuffer);
  31833. UniformBuffer._tempBuffer[3] = alpha;
  31834. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  31835. };
  31836. /**
  31837. * Sets a sampler uniform on the effect.
  31838. * @param {string} name Name of the sampler.
  31839. * @param {Texture} texture
  31840. */
  31841. UniformBuffer.prototype.setTexture = function (name, texture) {
  31842. this._currentEffect.setTexture(name, texture);
  31843. };
  31844. /**
  31845. * Directly updates the value of the uniform in the cache AND on the GPU.
  31846. * @param {string} uniformName Name of the uniform, as used in the uniform block in the shader.
  31847. * @param {number[]|Float32Array} data Flattened data
  31848. */
  31849. UniformBuffer.prototype.updateUniformDirectly = function (uniformName, data) {
  31850. this.updateUniform(uniformName, data, data.length);
  31851. this.update();
  31852. };
  31853. /**
  31854. * Binds this uniform buffer to an effect.
  31855. * @param {Effect} effect
  31856. * @param {string} name Name of the uniform block in the shader.
  31857. */
  31858. UniformBuffer.prototype.bindToEffect = function (effect, name) {
  31859. this._currentEffect = effect;
  31860. if (this._noUBO || !this._buffer) {
  31861. return;
  31862. }
  31863. effect.bindUniformBuffer(this._buffer, name);
  31864. };
  31865. /**
  31866. * Disposes the uniform buffer.
  31867. */
  31868. UniformBuffer.prototype.dispose = function () {
  31869. if (this._noUBO) {
  31870. return;
  31871. }
  31872. var index = this._engine._uniformBuffers.indexOf(this);
  31873. if (index !== -1) {
  31874. this._engine._uniformBuffers.splice(index, 1);
  31875. }
  31876. if (!this._buffer) {
  31877. return;
  31878. }
  31879. if (this._engine._releaseBuffer(this._buffer)) {
  31880. this._buffer = null;
  31881. }
  31882. };
  31883. // Pool for avoiding memory leaks
  31884. UniformBuffer._MAX_UNIFORM_SIZE = 256;
  31885. UniformBuffer._tempBuffer = new Float32Array(UniformBuffer._MAX_UNIFORM_SIZE);
  31886. return UniformBuffer;
  31887. }());
  31888. BABYLON.UniformBuffer = UniformBuffer;
  31889. })(BABYLON || (BABYLON = {}));
  31890. //# sourceMappingURL=babylon.uniformBuffer.js.map
  31891. var BABYLON;
  31892. (function (BABYLON) {
  31893. var VertexData = /** @class */ (function () {
  31894. function VertexData() {
  31895. }
  31896. VertexData.prototype.set = function (data, kind) {
  31897. switch (kind) {
  31898. case BABYLON.VertexBuffer.PositionKind:
  31899. this.positions = data;
  31900. break;
  31901. case BABYLON.VertexBuffer.NormalKind:
  31902. this.normals = data;
  31903. break;
  31904. case BABYLON.VertexBuffer.TangentKind:
  31905. this.tangents = data;
  31906. break;
  31907. case BABYLON.VertexBuffer.UVKind:
  31908. this.uvs = data;
  31909. break;
  31910. case BABYLON.VertexBuffer.UV2Kind:
  31911. this.uvs2 = data;
  31912. break;
  31913. case BABYLON.VertexBuffer.UV3Kind:
  31914. this.uvs3 = data;
  31915. break;
  31916. case BABYLON.VertexBuffer.UV4Kind:
  31917. this.uvs4 = data;
  31918. break;
  31919. case BABYLON.VertexBuffer.UV5Kind:
  31920. this.uvs5 = data;
  31921. break;
  31922. case BABYLON.VertexBuffer.UV6Kind:
  31923. this.uvs6 = data;
  31924. break;
  31925. case BABYLON.VertexBuffer.ColorKind:
  31926. this.colors = data;
  31927. break;
  31928. case BABYLON.VertexBuffer.MatricesIndicesKind:
  31929. this.matricesIndices = data;
  31930. break;
  31931. case BABYLON.VertexBuffer.MatricesWeightsKind:
  31932. this.matricesWeights = data;
  31933. break;
  31934. case BABYLON.VertexBuffer.MatricesIndicesExtraKind:
  31935. this.matricesIndicesExtra = data;
  31936. break;
  31937. case BABYLON.VertexBuffer.MatricesWeightsExtraKind:
  31938. this.matricesWeightsExtra = data;
  31939. break;
  31940. }
  31941. };
  31942. /**
  31943. * Associates the vertexData to the passed Mesh.
  31944. * Sets it as updatable or not (default `false`).
  31945. * Returns the VertexData.
  31946. */
  31947. VertexData.prototype.applyToMesh = function (mesh, updatable) {
  31948. this._applyTo(mesh, updatable);
  31949. return this;
  31950. };
  31951. /**
  31952. * Associates the vertexData to the passed Geometry.
  31953. * Sets it as updatable or not (default `false`).
  31954. * Returns the VertexData.
  31955. */
  31956. VertexData.prototype.applyToGeometry = function (geometry, updatable) {
  31957. this._applyTo(geometry, updatable);
  31958. return this;
  31959. };
  31960. /**
  31961. * Updates the associated mesh.
  31962. * Returns the VertexData.
  31963. */
  31964. VertexData.prototype.updateMesh = function (mesh, updateExtends, makeItUnique) {
  31965. this._update(mesh);
  31966. return this;
  31967. };
  31968. /**
  31969. * Updates the associated geometry.
  31970. * Returns the VertexData.
  31971. */
  31972. VertexData.prototype.updateGeometry = function (geometry, updateExtends, makeItUnique) {
  31973. this._update(geometry);
  31974. return this;
  31975. };
  31976. VertexData.prototype._applyTo = function (meshOrGeometry, updatable) {
  31977. if (updatable === void 0) { updatable = false; }
  31978. if (this.positions) {
  31979. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updatable);
  31980. }
  31981. if (this.normals) {
  31982. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updatable);
  31983. }
  31984. if (this.tangents) {
  31985. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.TangentKind, this.tangents, updatable);
  31986. }
  31987. if (this.uvs) {
  31988. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updatable);
  31989. }
  31990. if (this.uvs2) {
  31991. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updatable);
  31992. }
  31993. if (this.uvs3) {
  31994. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updatable);
  31995. }
  31996. if (this.uvs4) {
  31997. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updatable);
  31998. }
  31999. if (this.uvs5) {
  32000. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updatable);
  32001. }
  32002. if (this.uvs6) {
  32003. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updatable);
  32004. }
  32005. if (this.colors) {
  32006. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updatable);
  32007. }
  32008. if (this.matricesIndices) {
  32009. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updatable);
  32010. }
  32011. if (this.matricesWeights) {
  32012. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updatable);
  32013. }
  32014. if (this.matricesIndicesExtra) {
  32015. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updatable);
  32016. }
  32017. if (this.matricesWeightsExtra) {
  32018. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updatable);
  32019. }
  32020. if (this.indices) {
  32021. meshOrGeometry.setIndices(this.indices, null, updatable);
  32022. }
  32023. return this;
  32024. };
  32025. VertexData.prototype._update = function (meshOrGeometry, updateExtends, makeItUnique) {
  32026. if (this.positions) {
  32027. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updateExtends, makeItUnique);
  32028. }
  32029. if (this.normals) {
  32030. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updateExtends, makeItUnique);
  32031. }
  32032. if (this.tangents) {
  32033. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.TangentKind, this.tangents, updateExtends, makeItUnique);
  32034. }
  32035. if (this.uvs) {
  32036. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updateExtends, makeItUnique);
  32037. }
  32038. if (this.uvs2) {
  32039. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updateExtends, makeItUnique);
  32040. }
  32041. if (this.uvs3) {
  32042. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updateExtends, makeItUnique);
  32043. }
  32044. if (this.uvs4) {
  32045. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updateExtends, makeItUnique);
  32046. }
  32047. if (this.uvs5) {
  32048. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updateExtends, makeItUnique);
  32049. }
  32050. if (this.uvs6) {
  32051. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updateExtends, makeItUnique);
  32052. }
  32053. if (this.colors) {
  32054. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updateExtends, makeItUnique);
  32055. }
  32056. if (this.matricesIndices) {
  32057. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updateExtends, makeItUnique);
  32058. }
  32059. if (this.matricesWeights) {
  32060. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updateExtends, makeItUnique);
  32061. }
  32062. if (this.matricesIndicesExtra) {
  32063. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updateExtends, makeItUnique);
  32064. }
  32065. if (this.matricesWeightsExtra) {
  32066. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updateExtends, makeItUnique);
  32067. }
  32068. if (this.indices) {
  32069. meshOrGeometry.setIndices(this.indices, null);
  32070. }
  32071. return this;
  32072. };
  32073. /**
  32074. * Transforms each position and each normal of the vertexData according to the passed Matrix.
  32075. * Returns the VertexData.
  32076. */
  32077. VertexData.prototype.transform = function (matrix) {
  32078. var transformed = BABYLON.Vector3.Zero();
  32079. var index;
  32080. if (this.positions) {
  32081. var position = BABYLON.Vector3.Zero();
  32082. for (index = 0; index < this.positions.length; index += 3) {
  32083. BABYLON.Vector3.FromArrayToRef(this.positions, index, position);
  32084. BABYLON.Vector3.TransformCoordinatesToRef(position, matrix, transformed);
  32085. this.positions[index] = transformed.x;
  32086. this.positions[index + 1] = transformed.y;
  32087. this.positions[index + 2] = transformed.z;
  32088. }
  32089. }
  32090. if (this.normals) {
  32091. var normal = BABYLON.Vector3.Zero();
  32092. for (index = 0; index < this.normals.length; index += 3) {
  32093. BABYLON.Vector3.FromArrayToRef(this.normals, index, normal);
  32094. BABYLON.Vector3.TransformNormalToRef(normal, matrix, transformed);
  32095. this.normals[index] = transformed.x;
  32096. this.normals[index + 1] = transformed.y;
  32097. this.normals[index + 2] = transformed.z;
  32098. }
  32099. }
  32100. if (this.tangents) {
  32101. var tangent = BABYLON.Vector4.Zero();
  32102. var tangentTransformed = BABYLON.Vector4.Zero();
  32103. for (index = 0; index < this.tangents.length; index += 4) {
  32104. BABYLON.Vector4.FromArrayToRef(this.tangents, index, tangent);
  32105. BABYLON.Vector4.TransformNormalToRef(tangent, matrix, tangentTransformed);
  32106. this.tangents[index] = tangentTransformed.x;
  32107. this.tangents[index + 1] = tangentTransformed.y;
  32108. this.tangents[index + 2] = tangentTransformed.z;
  32109. this.tangents[index + 3] = tangentTransformed.w;
  32110. }
  32111. }
  32112. return this;
  32113. };
  32114. /**
  32115. * Merges the passed VertexData into the current one.
  32116. * Returns the modified VertexData.
  32117. */
  32118. VertexData.prototype.merge = function (other) {
  32119. this._validate();
  32120. other._validate();
  32121. if (!this.normals !== !other.normals ||
  32122. !this.tangents !== !other.tangents ||
  32123. !this.uvs !== !other.uvs ||
  32124. !this.uvs2 !== !other.uvs2 ||
  32125. !this.uvs3 !== !other.uvs3 ||
  32126. !this.uvs4 !== !other.uvs4 ||
  32127. !this.uvs5 !== !other.uvs5 ||
  32128. !this.uvs6 !== !other.uvs6 ||
  32129. !this.colors !== !other.colors ||
  32130. !this.matricesIndices !== !other.matricesIndices ||
  32131. !this.matricesWeights !== !other.matricesWeights ||
  32132. !this.matricesIndicesExtra !== !other.matricesIndicesExtra ||
  32133. !this.matricesWeightsExtra !== !other.matricesWeightsExtra) {
  32134. throw new Error("Cannot merge vertex data that do not have the same set of attributes");
  32135. }
  32136. if (other.indices) {
  32137. if (!this.indices) {
  32138. this.indices = [];
  32139. }
  32140. var offset = this.positions ? this.positions.length / 3 : 0;
  32141. for (var index = 0; index < other.indices.length; index++) {
  32142. //TODO check type - if Int32Array | Uint32Array | Uint16Array!
  32143. this.indices.push(other.indices[index] + offset);
  32144. }
  32145. }
  32146. this.positions = this._mergeElement(this.positions, other.positions);
  32147. this.normals = this._mergeElement(this.normals, other.normals);
  32148. this.tangents = this._mergeElement(this.tangents, other.tangents);
  32149. this.uvs = this._mergeElement(this.uvs, other.uvs);
  32150. this.uvs2 = this._mergeElement(this.uvs2, other.uvs2);
  32151. this.uvs3 = this._mergeElement(this.uvs3, other.uvs3);
  32152. this.uvs4 = this._mergeElement(this.uvs4, other.uvs4);
  32153. this.uvs5 = this._mergeElement(this.uvs5, other.uvs5);
  32154. this.uvs6 = this._mergeElement(this.uvs6, other.uvs6);
  32155. this.colors = this._mergeElement(this.colors, other.colors);
  32156. this.matricesIndices = this._mergeElement(this.matricesIndices, other.matricesIndices);
  32157. this.matricesWeights = this._mergeElement(this.matricesWeights, other.matricesWeights);
  32158. this.matricesIndicesExtra = this._mergeElement(this.matricesIndicesExtra, other.matricesIndicesExtra);
  32159. this.matricesWeightsExtra = this._mergeElement(this.matricesWeightsExtra, other.matricesWeightsExtra);
  32160. return this;
  32161. };
  32162. VertexData.prototype._mergeElement = function (source, other) {
  32163. if (!source) {
  32164. return other;
  32165. }
  32166. if (!other) {
  32167. return source;
  32168. }
  32169. var len = other.length + source.length;
  32170. var isSrcTypedArray = source instanceof Float32Array;
  32171. var isOthTypedArray = other instanceof Float32Array;
  32172. // use non-loop method when the source is Float32Array
  32173. if (isSrcTypedArray) {
  32174. var ret32 = new Float32Array(len);
  32175. ret32.set(source);
  32176. ret32.set(other, source.length);
  32177. return ret32;
  32178. // source is number[], when other is also use concat
  32179. }
  32180. else if (!isOthTypedArray) {
  32181. return source.concat(other);
  32182. // source is a number[], but other is a Float32Array, loop required
  32183. }
  32184. else {
  32185. var ret = source.slice(0); // copy source to a separate array
  32186. for (var i = 0, len = other.length; i < len; i++) {
  32187. ret.push(other[i]);
  32188. }
  32189. return ret;
  32190. }
  32191. };
  32192. VertexData.prototype._validate = function () {
  32193. if (!this.positions) {
  32194. throw new Error("Positions are required");
  32195. }
  32196. var getElementCount = function (kind, values) {
  32197. var stride = BABYLON.VertexBuffer.DeduceStride(kind);
  32198. if ((values.length % stride) !== 0) {
  32199. throw new Error("The " + kind + "s array count must be a multiple of " + stride);
  32200. }
  32201. return values.length / stride;
  32202. };
  32203. var positionsElementCount = getElementCount(BABYLON.VertexBuffer.PositionKind, this.positions);
  32204. var validateElementCount = function (kind, values) {
  32205. var elementCount = getElementCount(kind, values);
  32206. if (elementCount !== positionsElementCount) {
  32207. throw new Error("The " + kind + "s element count (" + elementCount + ") does not match the positions count (" + positionsElementCount + ")");
  32208. }
  32209. };
  32210. if (this.normals)
  32211. validateElementCount(BABYLON.VertexBuffer.NormalKind, this.normals);
  32212. if (this.tangents)
  32213. validateElementCount(BABYLON.VertexBuffer.TangentKind, this.tangents);
  32214. if (this.uvs)
  32215. validateElementCount(BABYLON.VertexBuffer.UVKind, this.uvs);
  32216. if (this.uvs2)
  32217. validateElementCount(BABYLON.VertexBuffer.UV2Kind, this.uvs2);
  32218. if (this.uvs3)
  32219. validateElementCount(BABYLON.VertexBuffer.UV3Kind, this.uvs3);
  32220. if (this.uvs4)
  32221. validateElementCount(BABYLON.VertexBuffer.UV4Kind, this.uvs4);
  32222. if (this.uvs5)
  32223. validateElementCount(BABYLON.VertexBuffer.UV5Kind, this.uvs5);
  32224. if (this.uvs6)
  32225. validateElementCount(BABYLON.VertexBuffer.UV6Kind, this.uvs6);
  32226. if (this.colors)
  32227. validateElementCount(BABYLON.VertexBuffer.ColorKind, this.colors);
  32228. if (this.matricesIndices)
  32229. validateElementCount(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices);
  32230. if (this.matricesWeights)
  32231. validateElementCount(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights);
  32232. if (this.matricesIndicesExtra)
  32233. validateElementCount(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra);
  32234. if (this.matricesWeightsExtra)
  32235. validateElementCount(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra);
  32236. };
  32237. /**
  32238. * Serializes the VertexData.
  32239. * Returns a serialized object.
  32240. */
  32241. VertexData.prototype.serialize = function () {
  32242. var serializationObject = this.serialize();
  32243. if (this.positions) {
  32244. serializationObject.positions = this.positions;
  32245. }
  32246. if (this.normals) {
  32247. serializationObject.normals = this.normals;
  32248. }
  32249. if (this.tangents) {
  32250. serializationObject.tangents = this.tangents;
  32251. }
  32252. if (this.uvs) {
  32253. serializationObject.uvs = this.uvs;
  32254. }
  32255. if (this.uvs2) {
  32256. serializationObject.uvs2 = this.uvs2;
  32257. }
  32258. if (this.uvs3) {
  32259. serializationObject.uvs3 = this.uvs3;
  32260. }
  32261. if (this.uvs4) {
  32262. serializationObject.uvs4 = this.uvs4;
  32263. }
  32264. if (this.uvs5) {
  32265. serializationObject.uvs5 = this.uvs5;
  32266. }
  32267. if (this.uvs6) {
  32268. serializationObject.uvs6 = this.uvs6;
  32269. }
  32270. if (this.colors) {
  32271. serializationObject.colors = this.colors;
  32272. }
  32273. if (this.matricesIndices) {
  32274. serializationObject.matricesIndices = this.matricesIndices;
  32275. serializationObject.matricesIndices._isExpanded = true;
  32276. }
  32277. if (this.matricesWeights) {
  32278. serializationObject.matricesWeights = this.matricesWeights;
  32279. }
  32280. if (this.matricesIndicesExtra) {
  32281. serializationObject.matricesIndicesExtra = this.matricesIndicesExtra;
  32282. serializationObject.matricesIndicesExtra._isExpanded = true;
  32283. }
  32284. if (this.matricesWeightsExtra) {
  32285. serializationObject.matricesWeightsExtra = this.matricesWeightsExtra;
  32286. }
  32287. serializationObject.indices = this.indices;
  32288. return serializationObject;
  32289. };
  32290. // Statics
  32291. /**
  32292. * Returns the object VertexData associated to the passed mesh.
  32293. */
  32294. VertexData.ExtractFromMesh = function (mesh, copyWhenShared, forceCopy) {
  32295. return VertexData._ExtractFrom(mesh, copyWhenShared, forceCopy);
  32296. };
  32297. /**
  32298. * Returns the object VertexData associated to the passed geometry.
  32299. */
  32300. VertexData.ExtractFromGeometry = function (geometry, copyWhenShared, forceCopy) {
  32301. return VertexData._ExtractFrom(geometry, copyWhenShared, forceCopy);
  32302. };
  32303. VertexData._ExtractFrom = function (meshOrGeometry, copyWhenShared, forceCopy) {
  32304. var result = new VertexData();
  32305. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  32306. result.positions = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.PositionKind, copyWhenShared, forceCopy);
  32307. }
  32308. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  32309. result.normals = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.NormalKind, copyWhenShared, forceCopy);
  32310. }
  32311. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  32312. result.tangents = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.TangentKind, copyWhenShared, forceCopy);
  32313. }
  32314. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  32315. result.uvs = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UVKind, copyWhenShared, forceCopy);
  32316. }
  32317. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  32318. result.uvs2 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV2Kind, copyWhenShared, forceCopy);
  32319. }
  32320. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  32321. result.uvs3 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV3Kind, copyWhenShared, forceCopy);
  32322. }
  32323. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  32324. result.uvs4 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV4Kind, copyWhenShared, forceCopy);
  32325. }
  32326. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  32327. result.uvs5 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV5Kind, copyWhenShared, forceCopy);
  32328. }
  32329. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  32330. result.uvs6 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV6Kind, copyWhenShared, forceCopy);
  32331. }
  32332. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  32333. result.colors = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.ColorKind, copyWhenShared, forceCopy);
  32334. }
  32335. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  32336. result.matricesIndices = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, copyWhenShared, forceCopy);
  32337. }
  32338. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  32339. result.matricesWeights = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, copyWhenShared, forceCopy);
  32340. }
  32341. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesExtraKind)) {
  32342. result.matricesIndicesExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, copyWhenShared, forceCopy);
  32343. }
  32344. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsExtraKind)) {
  32345. result.matricesWeightsExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, copyWhenShared, forceCopy);
  32346. }
  32347. result.indices = meshOrGeometry.getIndices(copyWhenShared);
  32348. return result;
  32349. };
  32350. /**
  32351. * Creates the vertexData of the Ribbon.
  32352. */
  32353. VertexData.CreateRibbon = function (options) {
  32354. var pathArray = options.pathArray;
  32355. var closeArray = options.closeArray || false;
  32356. var closePath = options.closePath || false;
  32357. var invertUV = options.invertUV || false;
  32358. var defaultOffset = Math.floor(pathArray[0].length / 2);
  32359. var offset = options.offset || defaultOffset;
  32360. offset = offset > defaultOffset ? defaultOffset : Math.floor(offset); // offset max allowed : defaultOffset
  32361. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  32362. var customUV = options.uvs;
  32363. var customColors = options.colors;
  32364. var positions = [];
  32365. var indices = [];
  32366. var normals = [];
  32367. var uvs = [];
  32368. var us = []; // us[path_id] = [uDist1, uDist2, uDist3 ... ] distances between points on path path_id
  32369. var vs = []; // vs[i] = [vDist1, vDist2, vDist3, ... ] distances between points i of consecutives paths from pathArray
  32370. var uTotalDistance = []; // uTotalDistance[p] : total distance of path p
  32371. var vTotalDistance = []; // vTotalDistance[i] : total distance between points i of first and last path from pathArray
  32372. var minlg; // minimal length among all paths from pathArray
  32373. var lg = []; // array of path lengths : nb of vertex per path
  32374. var idx = []; // array of path indexes : index of each path (first vertex) in the total vertex number
  32375. var p; // path iterator
  32376. var i; // point iterator
  32377. var j; // point iterator
  32378. // if single path in pathArray
  32379. if (pathArray.length < 2) {
  32380. var ar1 = [];
  32381. var ar2 = [];
  32382. for (i = 0; i < pathArray[0].length - offset; i++) {
  32383. ar1.push(pathArray[0][i]);
  32384. ar2.push(pathArray[0][i + offset]);
  32385. }
  32386. pathArray = [ar1, ar2];
  32387. }
  32388. // positions and horizontal distances (u)
  32389. var idc = 0;
  32390. var closePathCorr = (closePath) ? 1 : 0; // the final index will be +1 if closePath
  32391. var path;
  32392. var l;
  32393. minlg = pathArray[0].length;
  32394. var vectlg;
  32395. var dist;
  32396. for (p = 0; p < pathArray.length; p++) {
  32397. uTotalDistance[p] = 0;
  32398. us[p] = [0];
  32399. path = pathArray[p];
  32400. l = path.length;
  32401. minlg = (minlg < l) ? minlg : l;
  32402. j = 0;
  32403. while (j < l) {
  32404. positions.push(path[j].x, path[j].y, path[j].z);
  32405. if (j > 0) {
  32406. vectlg = path[j].subtract(path[j - 1]).length();
  32407. dist = vectlg + uTotalDistance[p];
  32408. us[p].push(dist);
  32409. uTotalDistance[p] = dist;
  32410. }
  32411. j++;
  32412. }
  32413. if (closePath) {
  32414. j--;
  32415. positions.push(path[0].x, path[0].y, path[0].z);
  32416. vectlg = path[j].subtract(path[0]).length();
  32417. dist = vectlg + uTotalDistance[p];
  32418. us[p].push(dist);
  32419. uTotalDistance[p] = dist;
  32420. }
  32421. lg[p] = l + closePathCorr;
  32422. idx[p] = idc;
  32423. idc += (l + closePathCorr);
  32424. }
  32425. // vertical distances (v)
  32426. var path1;
  32427. var path2;
  32428. var vertex1 = null;
  32429. var vertex2 = null;
  32430. for (i = 0; i < minlg + closePathCorr; i++) {
  32431. vTotalDistance[i] = 0;
  32432. vs[i] = [0];
  32433. for (p = 0; p < pathArray.length - 1; p++) {
  32434. path1 = pathArray[p];
  32435. path2 = pathArray[p + 1];
  32436. if (i === minlg) {
  32437. vertex1 = path1[0];
  32438. vertex2 = path2[0];
  32439. }
  32440. else {
  32441. vertex1 = path1[i];
  32442. vertex2 = path2[i];
  32443. }
  32444. vectlg = vertex2.subtract(vertex1).length();
  32445. dist = vectlg + vTotalDistance[i];
  32446. vs[i].push(dist);
  32447. vTotalDistance[i] = dist;
  32448. }
  32449. if (closeArray && vertex2 && vertex1) {
  32450. path1 = pathArray[p];
  32451. path2 = pathArray[0];
  32452. if (i === minlg) {
  32453. vertex2 = path2[0];
  32454. }
  32455. vectlg = vertex2.subtract(vertex1).length();
  32456. dist = vectlg + vTotalDistance[i];
  32457. vTotalDistance[i] = dist;
  32458. }
  32459. }
  32460. // uvs
  32461. var u;
  32462. var v;
  32463. if (customUV) {
  32464. for (p = 0; p < customUV.length; p++) {
  32465. uvs.push(customUV[p].x, customUV[p].y);
  32466. }
  32467. }
  32468. else {
  32469. for (p = 0; p < pathArray.length; p++) {
  32470. for (i = 0; i < minlg + closePathCorr; i++) {
  32471. u = (uTotalDistance[p] != 0.0) ? us[p][i] / uTotalDistance[p] : 0.0;
  32472. v = (vTotalDistance[i] != 0.0) ? vs[i][p] / vTotalDistance[i] : 0.0;
  32473. if (invertUV) {
  32474. uvs.push(v, u);
  32475. }
  32476. else {
  32477. uvs.push(u, v);
  32478. }
  32479. }
  32480. }
  32481. }
  32482. // indices
  32483. p = 0; // path index
  32484. var pi = 0; // positions array index
  32485. var l1 = lg[p] - 1; // path1 length
  32486. var l2 = lg[p + 1] - 1; // path2 length
  32487. var min = (l1 < l2) ? l1 : l2; // current path stop index
  32488. var shft = idx[1] - idx[0]; // shift
  32489. var path1nb = closeArray ? lg.length : lg.length - 1; // number of path1 to iterate on
  32490. while (pi <= min && p < path1nb) {
  32491. // 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
  32492. indices.push(pi, pi + shft, pi + 1);
  32493. indices.push(pi + shft + 1, pi + 1, pi + shft);
  32494. pi += 1;
  32495. if (pi === min) {
  32496. p++;
  32497. if (p === lg.length - 1) {
  32498. shft = idx[0] - idx[p];
  32499. l1 = lg[p] - 1;
  32500. l2 = lg[0] - 1;
  32501. }
  32502. else {
  32503. shft = idx[p + 1] - idx[p];
  32504. l1 = lg[p] - 1;
  32505. l2 = lg[p + 1] - 1;
  32506. }
  32507. pi = idx[p];
  32508. min = (l1 < l2) ? l1 + pi : l2 + pi;
  32509. }
  32510. }
  32511. // normals
  32512. VertexData.ComputeNormals(positions, indices, normals);
  32513. if (closePath) {
  32514. var indexFirst = 0;
  32515. var indexLast = 0;
  32516. for (p = 0; p < pathArray.length; p++) {
  32517. indexFirst = idx[p] * 3;
  32518. if (p + 1 < pathArray.length) {
  32519. indexLast = (idx[p + 1] - 1) * 3;
  32520. }
  32521. else {
  32522. indexLast = normals.length - 3;
  32523. }
  32524. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  32525. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  32526. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  32527. normals[indexLast] = normals[indexFirst];
  32528. normals[indexLast + 1] = normals[indexFirst + 1];
  32529. normals[indexLast + 2] = normals[indexFirst + 2];
  32530. }
  32531. }
  32532. // sides
  32533. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  32534. // Colors
  32535. var colors = null;
  32536. if (customColors) {
  32537. colors = new Float32Array(customColors.length * 4);
  32538. for (var c = 0; c < customColors.length; c++) {
  32539. colors[c * 4] = customColors[c].r;
  32540. colors[c * 4 + 1] = customColors[c].g;
  32541. colors[c * 4 + 2] = customColors[c].b;
  32542. colors[c * 4 + 3] = customColors[c].a;
  32543. }
  32544. }
  32545. // Result
  32546. var vertexData = new VertexData();
  32547. var positions32 = new Float32Array(positions);
  32548. var normals32 = new Float32Array(normals);
  32549. var uvs32 = new Float32Array(uvs);
  32550. vertexData.indices = indices;
  32551. vertexData.positions = positions32;
  32552. vertexData.normals = normals32;
  32553. vertexData.uvs = uvs32;
  32554. if (colors) {
  32555. vertexData.set(colors, BABYLON.VertexBuffer.ColorKind);
  32556. }
  32557. if (closePath) {
  32558. vertexData._idx = idx;
  32559. }
  32560. return vertexData;
  32561. };
  32562. /**
  32563. * Creates the VertexData of the Box.
  32564. */
  32565. VertexData.CreateBox = function (options) {
  32566. var normalsSource = [
  32567. new BABYLON.Vector3(0, 0, 1),
  32568. new BABYLON.Vector3(0, 0, -1),
  32569. new BABYLON.Vector3(1, 0, 0),
  32570. new BABYLON.Vector3(-1, 0, 0),
  32571. new BABYLON.Vector3(0, 1, 0),
  32572. new BABYLON.Vector3(0, -1, 0)
  32573. ];
  32574. var indices = [];
  32575. var positions = [];
  32576. var normals = [];
  32577. var uvs = [];
  32578. var width = options.width || options.size || 1;
  32579. var height = options.height || options.size || 1;
  32580. var depth = options.depth || options.size || 1;
  32581. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  32582. var faceUV = options.faceUV || new Array(6);
  32583. var faceColors = options.faceColors;
  32584. var colors = [];
  32585. // default face colors and UV if undefined
  32586. for (var f = 0; f < 6; f++) {
  32587. if (faceUV[f] === undefined) {
  32588. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  32589. }
  32590. if (faceColors && faceColors[f] === undefined) {
  32591. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  32592. }
  32593. }
  32594. var scaleVector = new BABYLON.Vector3(width / 2, height / 2, depth / 2);
  32595. // Create each face in turn.
  32596. for (var index = 0; index < normalsSource.length; index++) {
  32597. var normal = normalsSource[index];
  32598. // Get two vectors perpendicular to the face normal and to each other.
  32599. var side1 = new BABYLON.Vector3(normal.y, normal.z, normal.x);
  32600. var side2 = BABYLON.Vector3.Cross(normal, side1);
  32601. // Six indices (two triangles) per face.
  32602. var verticesLength = positions.length / 3;
  32603. indices.push(verticesLength);
  32604. indices.push(verticesLength + 1);
  32605. indices.push(verticesLength + 2);
  32606. indices.push(verticesLength);
  32607. indices.push(verticesLength + 2);
  32608. indices.push(verticesLength + 3);
  32609. // Four vertices per face.
  32610. var vertex = normal.subtract(side1).subtract(side2).multiply(scaleVector);
  32611. positions.push(vertex.x, vertex.y, vertex.z);
  32612. normals.push(normal.x, normal.y, normal.z);
  32613. uvs.push(faceUV[index].z, faceUV[index].w);
  32614. if (faceColors) {
  32615. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  32616. }
  32617. vertex = normal.subtract(side1).add(side2).multiply(scaleVector);
  32618. positions.push(vertex.x, vertex.y, vertex.z);
  32619. normals.push(normal.x, normal.y, normal.z);
  32620. uvs.push(faceUV[index].x, faceUV[index].w);
  32621. if (faceColors) {
  32622. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  32623. }
  32624. vertex = normal.add(side1).add(side2).multiply(scaleVector);
  32625. positions.push(vertex.x, vertex.y, vertex.z);
  32626. normals.push(normal.x, normal.y, normal.z);
  32627. uvs.push(faceUV[index].x, faceUV[index].y);
  32628. if (faceColors) {
  32629. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  32630. }
  32631. vertex = normal.add(side1).subtract(side2).multiply(scaleVector);
  32632. positions.push(vertex.x, vertex.y, vertex.z);
  32633. normals.push(normal.x, normal.y, normal.z);
  32634. uvs.push(faceUV[index].z, faceUV[index].y);
  32635. if (faceColors) {
  32636. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  32637. }
  32638. }
  32639. // sides
  32640. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  32641. // Result
  32642. var vertexData = new VertexData();
  32643. vertexData.indices = indices;
  32644. vertexData.positions = positions;
  32645. vertexData.normals = normals;
  32646. vertexData.uvs = uvs;
  32647. if (faceColors) {
  32648. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  32649. vertexData.colors = totalColors;
  32650. }
  32651. return vertexData;
  32652. };
  32653. /**
  32654. * Creates the VertexData of the Sphere.
  32655. */
  32656. VertexData.CreateSphere = function (options) {
  32657. var segments = options.segments || 32;
  32658. var diameterX = options.diameterX || options.diameter || 1;
  32659. var diameterY = options.diameterY || options.diameter || 1;
  32660. var diameterZ = options.diameterZ || options.diameter || 1;
  32661. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  32662. var slice = options.slice && (options.slice <= 0) ? 1.0 : options.slice || 1.0;
  32663. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  32664. var radius = new BABYLON.Vector3(diameterX / 2, diameterY / 2, diameterZ / 2);
  32665. var totalZRotationSteps = 2 + segments;
  32666. var totalYRotationSteps = 2 * totalZRotationSteps;
  32667. var indices = [];
  32668. var positions = [];
  32669. var normals = [];
  32670. var uvs = [];
  32671. for (var zRotationStep = 0; zRotationStep <= totalZRotationSteps; zRotationStep++) {
  32672. var normalizedZ = zRotationStep / totalZRotationSteps;
  32673. var angleZ = normalizedZ * Math.PI * slice;
  32674. for (var yRotationStep = 0; yRotationStep <= totalYRotationSteps; yRotationStep++) {
  32675. var normalizedY = yRotationStep / totalYRotationSteps;
  32676. var angleY = normalizedY * Math.PI * 2 * arc;
  32677. var rotationZ = BABYLON.Matrix.RotationZ(-angleZ);
  32678. var rotationY = BABYLON.Matrix.RotationY(angleY);
  32679. var afterRotZ = BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.Up(), rotationZ);
  32680. var complete = BABYLON.Vector3.TransformCoordinates(afterRotZ, rotationY);
  32681. var vertex = complete.multiply(radius);
  32682. var normal = complete.divide(radius).normalize();
  32683. positions.push(vertex.x, vertex.y, vertex.z);
  32684. normals.push(normal.x, normal.y, normal.z);
  32685. uvs.push(normalizedY, normalizedZ);
  32686. }
  32687. if (zRotationStep > 0) {
  32688. var verticesCount = positions.length / 3;
  32689. for (var firstIndex = verticesCount - 2 * (totalYRotationSteps + 1); (firstIndex + totalYRotationSteps + 2) < verticesCount; firstIndex++) {
  32690. indices.push((firstIndex));
  32691. indices.push((firstIndex + 1));
  32692. indices.push(firstIndex + totalYRotationSteps + 1);
  32693. indices.push((firstIndex + totalYRotationSteps + 1));
  32694. indices.push((firstIndex + 1));
  32695. indices.push((firstIndex + totalYRotationSteps + 2));
  32696. }
  32697. }
  32698. }
  32699. // Sides
  32700. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  32701. // Result
  32702. var vertexData = new VertexData();
  32703. vertexData.indices = indices;
  32704. vertexData.positions = positions;
  32705. vertexData.normals = normals;
  32706. vertexData.uvs = uvs;
  32707. return vertexData;
  32708. };
  32709. /**
  32710. * Creates the VertexData of the Cylinder or Cone.
  32711. */
  32712. VertexData.CreateCylinder = function (options) {
  32713. var height = options.height || 2;
  32714. var diameterTop = (options.diameterTop === 0) ? 0 : options.diameterTop || options.diameter || 1;
  32715. var diameterBottom = (options.diameterBottom === 0) ? 0 : options.diameterBottom || options.diameter || 1;
  32716. var tessellation = options.tessellation || 24;
  32717. var subdivisions = options.subdivisions || 1;
  32718. var hasRings = options.hasRings ? true : false;
  32719. var enclose = options.enclose ? true : false;
  32720. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  32721. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  32722. var faceUV = options.faceUV || new Array(3);
  32723. var faceColors = options.faceColors;
  32724. // default face colors and UV if undefined
  32725. var quadNb = (arc !== 1 && enclose) ? 2 : 0;
  32726. var ringNb = (hasRings) ? subdivisions : 1;
  32727. var surfaceNb = 2 + (1 + quadNb) * ringNb;
  32728. var f;
  32729. for (f = 0; f < surfaceNb; f++) {
  32730. if (faceColors && faceColors[f] === undefined) {
  32731. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  32732. }
  32733. }
  32734. for (f = 0; f < surfaceNb; f++) {
  32735. if (faceUV && faceUV[f] === undefined) {
  32736. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  32737. }
  32738. }
  32739. var indices = new Array();
  32740. var positions = new Array();
  32741. var normals = new Array();
  32742. var uvs = new Array();
  32743. var colors = new Array();
  32744. var angle_step = Math.PI * 2 * arc / tessellation;
  32745. var angle;
  32746. var h;
  32747. var radius;
  32748. var tan = (diameterBottom - diameterTop) / 2 / height;
  32749. var ringVertex = BABYLON.Vector3.Zero();
  32750. var ringNormal = BABYLON.Vector3.Zero();
  32751. var ringFirstVertex = BABYLON.Vector3.Zero();
  32752. var ringFirstNormal = BABYLON.Vector3.Zero();
  32753. var quadNormal = BABYLON.Vector3.Zero();
  32754. var Y = BABYLON.Axis.Y;
  32755. // positions, normals, uvs
  32756. var i;
  32757. var j;
  32758. var r;
  32759. var ringIdx = 1;
  32760. var s = 1; // surface index
  32761. var cs = 0;
  32762. var v = 0;
  32763. for (i = 0; i <= subdivisions; i++) {
  32764. h = i / subdivisions;
  32765. radius = (h * (diameterTop - diameterBottom) + diameterBottom) / 2;
  32766. ringIdx = (hasRings && i !== 0 && i !== subdivisions) ? 2 : 1;
  32767. for (r = 0; r < ringIdx; r++) {
  32768. if (hasRings) {
  32769. s += r;
  32770. }
  32771. if (enclose) {
  32772. s += 2 * r;
  32773. }
  32774. for (j = 0; j <= tessellation; j++) {
  32775. angle = j * angle_step;
  32776. // position
  32777. ringVertex.x = Math.cos(-angle) * radius;
  32778. ringVertex.y = -height / 2 + h * height;
  32779. ringVertex.z = Math.sin(-angle) * radius;
  32780. // normal
  32781. if (diameterTop === 0 && i === subdivisions) {
  32782. // if no top cap, reuse former normals
  32783. ringNormal.x = normals[normals.length - (tessellation + 1) * 3];
  32784. ringNormal.y = normals[normals.length - (tessellation + 1) * 3 + 1];
  32785. ringNormal.z = normals[normals.length - (tessellation + 1) * 3 + 2];
  32786. }
  32787. else {
  32788. ringNormal.x = ringVertex.x;
  32789. ringNormal.z = ringVertex.z;
  32790. ringNormal.y = Math.sqrt(ringNormal.x * ringNormal.x + ringNormal.z * ringNormal.z) * tan;
  32791. ringNormal.normalize();
  32792. }
  32793. // keep first ring vertex values for enclose
  32794. if (j === 0) {
  32795. ringFirstVertex.copyFrom(ringVertex);
  32796. ringFirstNormal.copyFrom(ringNormal);
  32797. }
  32798. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  32799. normals.push(ringNormal.x, ringNormal.y, ringNormal.z);
  32800. if (hasRings) {
  32801. v = (cs !== s) ? faceUV[s].y : faceUV[s].w;
  32802. }
  32803. else {
  32804. v = faceUV[s].y + (faceUV[s].w - faceUV[s].y) * h;
  32805. }
  32806. uvs.push(faceUV[s].x + (faceUV[s].z - faceUV[s].x) * j / tessellation, v);
  32807. if (faceColors) {
  32808. colors.push(faceColors[s].r, faceColors[s].g, faceColors[s].b, faceColors[s].a);
  32809. }
  32810. }
  32811. // if enclose, add four vertices and their dedicated normals
  32812. if (arc !== 1 && enclose) {
  32813. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  32814. positions.push(0, ringVertex.y, 0);
  32815. positions.push(0, ringVertex.y, 0);
  32816. positions.push(ringFirstVertex.x, ringFirstVertex.y, ringFirstVertex.z);
  32817. BABYLON.Vector3.CrossToRef(Y, ringNormal, quadNormal);
  32818. quadNormal.normalize();
  32819. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  32820. BABYLON.Vector3.CrossToRef(ringFirstNormal, Y, quadNormal);
  32821. quadNormal.normalize();
  32822. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  32823. if (hasRings) {
  32824. v = (cs !== s) ? faceUV[s + 1].y : faceUV[s + 1].w;
  32825. }
  32826. else {
  32827. v = faceUV[s + 1].y + (faceUV[s + 1].w - faceUV[s + 1].y) * h;
  32828. }
  32829. uvs.push(faceUV[s + 1].x, v);
  32830. uvs.push(faceUV[s + 1].z, v);
  32831. if (hasRings) {
  32832. v = (cs !== s) ? faceUV[s + 2].y : faceUV[s + 2].w;
  32833. }
  32834. else {
  32835. v = faceUV[s + 2].y + (faceUV[s + 2].w - faceUV[s + 2].y) * h;
  32836. }
  32837. uvs.push(faceUV[s + 2].x, v);
  32838. uvs.push(faceUV[s + 2].z, v);
  32839. if (faceColors) {
  32840. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  32841. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  32842. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  32843. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  32844. }
  32845. }
  32846. if (cs !== s) {
  32847. cs = s;
  32848. }
  32849. }
  32850. }
  32851. // indices
  32852. var e = (arc !== 1 && enclose) ? tessellation + 4 : tessellation; // correction of number of iteration if enclose
  32853. var s;
  32854. i = 0;
  32855. for (s = 0; s < subdivisions; s++) {
  32856. var i0 = 0;
  32857. var i1 = 0;
  32858. var i2 = 0;
  32859. var i3 = 0;
  32860. for (j = 0; j < tessellation; j++) {
  32861. i0 = i * (e + 1) + j;
  32862. i1 = (i + 1) * (e + 1) + j;
  32863. i2 = i * (e + 1) + (j + 1);
  32864. i3 = (i + 1) * (e + 1) + (j + 1);
  32865. indices.push(i0, i1, i2);
  32866. indices.push(i3, i2, i1);
  32867. }
  32868. if (arc !== 1 && enclose) {
  32869. indices.push(i0 + 2, i1 + 2, i2 + 2);
  32870. indices.push(i3 + 2, i2 + 2, i1 + 2);
  32871. indices.push(i0 + 4, i1 + 4, i2 + 4);
  32872. indices.push(i3 + 4, i2 + 4, i1 + 4);
  32873. }
  32874. i = (hasRings) ? (i + 2) : (i + 1);
  32875. }
  32876. // Caps
  32877. var createCylinderCap = function (isTop) {
  32878. var radius = isTop ? diameterTop / 2 : diameterBottom / 2;
  32879. if (radius === 0) {
  32880. return;
  32881. }
  32882. // Cap positions, normals & uvs
  32883. var angle;
  32884. var circleVector;
  32885. var i;
  32886. var u = (isTop) ? faceUV[surfaceNb - 1] : faceUV[0];
  32887. var c = null;
  32888. if (faceColors) {
  32889. c = (isTop) ? faceColors[surfaceNb - 1] : faceColors[0];
  32890. }
  32891. // cap center
  32892. var vbase = positions.length / 3;
  32893. var offset = isTop ? height / 2 : -height / 2;
  32894. var center = new BABYLON.Vector3(0, offset, 0);
  32895. positions.push(center.x, center.y, center.z);
  32896. normals.push(0, isTop ? 1 : -1, 0);
  32897. uvs.push(u.x + (u.z - u.x) * 0.5, u.y + (u.w - u.y) * 0.5);
  32898. if (c) {
  32899. colors.push(c.r, c.g, c.b, c.a);
  32900. }
  32901. var textureScale = new BABYLON.Vector2(0.5, 0.5);
  32902. for (i = 0; i <= tessellation; i++) {
  32903. angle = Math.PI * 2 * i * arc / tessellation;
  32904. var cos = Math.cos(-angle);
  32905. var sin = Math.sin(-angle);
  32906. circleVector = new BABYLON.Vector3(cos * radius, offset, sin * radius);
  32907. var textureCoordinate = new BABYLON.Vector2(cos * textureScale.x + 0.5, sin * textureScale.y + 0.5);
  32908. positions.push(circleVector.x, circleVector.y, circleVector.z);
  32909. normals.push(0, isTop ? 1 : -1, 0);
  32910. uvs.push(u.x + (u.z - u.x) * textureCoordinate.x, u.y + (u.w - u.y) * textureCoordinate.y);
  32911. if (c) {
  32912. colors.push(c.r, c.g, c.b, c.a);
  32913. }
  32914. }
  32915. // Cap indices
  32916. for (i = 0; i < tessellation; i++) {
  32917. if (!isTop) {
  32918. indices.push(vbase);
  32919. indices.push(vbase + (i + 1));
  32920. indices.push(vbase + (i + 2));
  32921. }
  32922. else {
  32923. indices.push(vbase);
  32924. indices.push(vbase + (i + 2));
  32925. indices.push(vbase + (i + 1));
  32926. }
  32927. }
  32928. };
  32929. // add caps to geometry
  32930. createCylinderCap(false);
  32931. createCylinderCap(true);
  32932. // Sides
  32933. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  32934. var vertexData = new VertexData();
  32935. vertexData.indices = indices;
  32936. vertexData.positions = positions;
  32937. vertexData.normals = normals;
  32938. vertexData.uvs = uvs;
  32939. if (faceColors) {
  32940. vertexData.colors = colors;
  32941. }
  32942. return vertexData;
  32943. };
  32944. /**
  32945. * Creates the VertexData of the Torus.
  32946. */
  32947. VertexData.CreateTorus = function (options) {
  32948. var indices = [];
  32949. var positions = [];
  32950. var normals = [];
  32951. var uvs = [];
  32952. var diameter = options.diameter || 1;
  32953. var thickness = options.thickness || 0.5;
  32954. var tessellation = options.tessellation || 16;
  32955. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  32956. var stride = tessellation + 1;
  32957. for (var i = 0; i <= tessellation; i++) {
  32958. var u = i / tessellation;
  32959. var outerAngle = i * Math.PI * 2.0 / tessellation - Math.PI / 2.0;
  32960. var transform = BABYLON.Matrix.Translation(diameter / 2.0, 0, 0).multiply(BABYLON.Matrix.RotationY(outerAngle));
  32961. for (var j = 0; j <= tessellation; j++) {
  32962. var v = 1 - j / tessellation;
  32963. var innerAngle = j * Math.PI * 2.0 / tessellation + Math.PI;
  32964. var dx = Math.cos(innerAngle);
  32965. var dy = Math.sin(innerAngle);
  32966. // Create a vertex.
  32967. var normal = new BABYLON.Vector3(dx, dy, 0);
  32968. var position = normal.scale(thickness / 2);
  32969. var textureCoordinate = new BABYLON.Vector2(u, v);
  32970. position = BABYLON.Vector3.TransformCoordinates(position, transform);
  32971. normal = BABYLON.Vector3.TransformNormal(normal, transform);
  32972. positions.push(position.x, position.y, position.z);
  32973. normals.push(normal.x, normal.y, normal.z);
  32974. uvs.push(textureCoordinate.x, textureCoordinate.y);
  32975. // And create indices for two triangles.
  32976. var nextI = (i + 1) % stride;
  32977. var nextJ = (j + 1) % stride;
  32978. indices.push(i * stride + j);
  32979. indices.push(i * stride + nextJ);
  32980. indices.push(nextI * stride + j);
  32981. indices.push(i * stride + nextJ);
  32982. indices.push(nextI * stride + nextJ);
  32983. indices.push(nextI * stride + j);
  32984. }
  32985. }
  32986. // Sides
  32987. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  32988. // Result
  32989. var vertexData = new VertexData();
  32990. vertexData.indices = indices;
  32991. vertexData.positions = positions;
  32992. vertexData.normals = normals;
  32993. vertexData.uvs = uvs;
  32994. return vertexData;
  32995. };
  32996. /**
  32997. * Creates the VertexData of the LineSystem.
  32998. */
  32999. VertexData.CreateLineSystem = function (options) {
  33000. var indices = [];
  33001. var positions = [];
  33002. var lines = options.lines;
  33003. var colors = options.colors;
  33004. var vertexColors = [];
  33005. var idx = 0;
  33006. for (var l = 0; l < lines.length; l++) {
  33007. var points = lines[l];
  33008. for (var index = 0; index < points.length; index++) {
  33009. positions.push(points[index].x, points[index].y, points[index].z);
  33010. if (colors) {
  33011. var color = colors[l];
  33012. vertexColors.push(color[index].r, color[index].g, color[index].b, color[index].a);
  33013. }
  33014. if (index > 0) {
  33015. indices.push(idx - 1);
  33016. indices.push(idx);
  33017. }
  33018. idx++;
  33019. }
  33020. }
  33021. var vertexData = new VertexData();
  33022. vertexData.indices = indices;
  33023. vertexData.positions = positions;
  33024. if (colors) {
  33025. vertexData.colors = vertexColors;
  33026. }
  33027. return vertexData;
  33028. };
  33029. /**
  33030. * Create the VertexData of the DashedLines.
  33031. */
  33032. VertexData.CreateDashedLines = function (options) {
  33033. var dashSize = options.dashSize || 3;
  33034. var gapSize = options.gapSize || 1;
  33035. var dashNb = options.dashNb || 200;
  33036. var points = options.points;
  33037. var positions = new Array();
  33038. var indices = new Array();
  33039. var curvect = BABYLON.Vector3.Zero();
  33040. var lg = 0;
  33041. var nb = 0;
  33042. var shft = 0;
  33043. var dashshft = 0;
  33044. var curshft = 0;
  33045. var idx = 0;
  33046. var i = 0;
  33047. for (i = 0; i < points.length - 1; i++) {
  33048. points[i + 1].subtractToRef(points[i], curvect);
  33049. lg += curvect.length();
  33050. }
  33051. shft = lg / dashNb;
  33052. dashshft = dashSize * shft / (dashSize + gapSize);
  33053. for (i = 0; i < points.length - 1; i++) {
  33054. points[i + 1].subtractToRef(points[i], curvect);
  33055. nb = Math.floor(curvect.length() / shft);
  33056. curvect.normalize();
  33057. for (var j = 0; j < nb; j++) {
  33058. curshft = shft * j;
  33059. positions.push(points[i].x + curshft * curvect.x, points[i].y + curshft * curvect.y, points[i].z + curshft * curvect.z);
  33060. positions.push(points[i].x + (curshft + dashshft) * curvect.x, points[i].y + (curshft + dashshft) * curvect.y, points[i].z + (curshft + dashshft) * curvect.z);
  33061. indices.push(idx, idx + 1);
  33062. idx += 2;
  33063. }
  33064. }
  33065. // Result
  33066. var vertexData = new VertexData();
  33067. vertexData.positions = positions;
  33068. vertexData.indices = indices;
  33069. return vertexData;
  33070. };
  33071. /**
  33072. * Creates the VertexData of the Ground.
  33073. */
  33074. VertexData.CreateGround = function (options) {
  33075. var indices = [];
  33076. var positions = [];
  33077. var normals = [];
  33078. var uvs = [];
  33079. var row, col;
  33080. var width = options.width || 1;
  33081. var height = options.height || 1;
  33082. var subdivisionsX = options.subdivisionsX || options.subdivisions || 1;
  33083. var subdivisionsY = options.subdivisionsY || options.subdivisions || 1;
  33084. for (row = 0; row <= subdivisionsY; row++) {
  33085. for (col = 0; col <= subdivisionsX; col++) {
  33086. var position = new BABYLON.Vector3((col * width) / subdivisionsX - (width / 2.0), 0, ((subdivisionsY - row) * height) / subdivisionsY - (height / 2.0));
  33087. var normal = new BABYLON.Vector3(0, 1.0, 0);
  33088. positions.push(position.x, position.y, position.z);
  33089. normals.push(normal.x, normal.y, normal.z);
  33090. uvs.push(col / subdivisionsX, 1.0 - row / subdivisionsY);
  33091. }
  33092. }
  33093. for (row = 0; row < subdivisionsY; row++) {
  33094. for (col = 0; col < subdivisionsX; col++) {
  33095. indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));
  33096. indices.push(col + 1 + row * (subdivisionsX + 1));
  33097. indices.push(col + row * (subdivisionsX + 1));
  33098. indices.push(col + (row + 1) * (subdivisionsX + 1));
  33099. indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));
  33100. indices.push(col + row * (subdivisionsX + 1));
  33101. }
  33102. }
  33103. // Result
  33104. var vertexData = new VertexData();
  33105. vertexData.indices = indices;
  33106. vertexData.positions = positions;
  33107. vertexData.normals = normals;
  33108. vertexData.uvs = uvs;
  33109. return vertexData;
  33110. };
  33111. /**
  33112. * Creates the VertexData of the TiledGround.
  33113. */
  33114. VertexData.CreateTiledGround = function (options) {
  33115. var xmin = (options.xmin !== undefined && options.xmin !== null) ? options.xmin : -1.0;
  33116. var zmin = (options.zmin !== undefined && options.zmin !== null) ? options.zmin : -1.0;
  33117. var xmax = (options.xmax !== undefined && options.xmax !== null) ? options.xmax : 1.0;
  33118. var zmax = (options.zmax !== undefined && options.zmax !== null) ? options.zmax : 1.0;
  33119. var subdivisions = options.subdivisions || { w: 1, h: 1 };
  33120. var precision = options.precision || { w: 1, h: 1 };
  33121. var indices = new Array();
  33122. var positions = new Array();
  33123. var normals = new Array();
  33124. var uvs = new Array();
  33125. var row, col, tileRow, tileCol;
  33126. subdivisions.h = (subdivisions.h < 1) ? 1 : subdivisions.h;
  33127. subdivisions.w = (subdivisions.w < 1) ? 1 : subdivisions.w;
  33128. precision.w = (precision.w < 1) ? 1 : precision.w;
  33129. precision.h = (precision.h < 1) ? 1 : precision.h;
  33130. var tileSize = {
  33131. 'w': (xmax - xmin) / subdivisions.w,
  33132. 'h': (zmax - zmin) / subdivisions.h
  33133. };
  33134. function applyTile(xTileMin, zTileMin, xTileMax, zTileMax) {
  33135. // Indices
  33136. var base = positions.length / 3;
  33137. var rowLength = precision.w + 1;
  33138. for (row = 0; row < precision.h; row++) {
  33139. for (col = 0; col < precision.w; col++) {
  33140. var square = [
  33141. base + col + row * rowLength,
  33142. base + (col + 1) + row * rowLength,
  33143. base + (col + 1) + (row + 1) * rowLength,
  33144. base + col + (row + 1) * rowLength
  33145. ];
  33146. indices.push(square[1]);
  33147. indices.push(square[2]);
  33148. indices.push(square[3]);
  33149. indices.push(square[0]);
  33150. indices.push(square[1]);
  33151. indices.push(square[3]);
  33152. }
  33153. }
  33154. // Position, normals and uvs
  33155. var position = BABYLON.Vector3.Zero();
  33156. var normal = new BABYLON.Vector3(0, 1.0, 0);
  33157. for (row = 0; row <= precision.h; row++) {
  33158. position.z = (row * (zTileMax - zTileMin)) / precision.h + zTileMin;
  33159. for (col = 0; col <= precision.w; col++) {
  33160. position.x = (col * (xTileMax - xTileMin)) / precision.w + xTileMin;
  33161. position.y = 0;
  33162. positions.push(position.x, position.y, position.z);
  33163. normals.push(normal.x, normal.y, normal.z);
  33164. uvs.push(col / precision.w, row / precision.h);
  33165. }
  33166. }
  33167. }
  33168. for (tileRow = 0; tileRow < subdivisions.h; tileRow++) {
  33169. for (tileCol = 0; tileCol < subdivisions.w; tileCol++) {
  33170. applyTile(xmin + tileCol * tileSize.w, zmin + tileRow * tileSize.h, xmin + (tileCol + 1) * tileSize.w, zmin + (tileRow + 1) * tileSize.h);
  33171. }
  33172. }
  33173. // Result
  33174. var vertexData = new VertexData();
  33175. vertexData.indices = indices;
  33176. vertexData.positions = positions;
  33177. vertexData.normals = normals;
  33178. vertexData.uvs = uvs;
  33179. return vertexData;
  33180. };
  33181. /**
  33182. * Creates the VertexData of the Ground designed from a heightmap.
  33183. */
  33184. VertexData.CreateGroundFromHeightMap = function (options) {
  33185. var indices = [];
  33186. var positions = [];
  33187. var normals = [];
  33188. var uvs = [];
  33189. var row, col;
  33190. var filter = options.colorFilter || new BABYLON.Color3(0.3, 0.59, 0.11);
  33191. // Vertices
  33192. for (row = 0; row <= options.subdivisions; row++) {
  33193. for (col = 0; col <= options.subdivisions; col++) {
  33194. 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));
  33195. // Compute height
  33196. var heightMapX = (((position.x + options.width / 2) / options.width) * (options.bufferWidth - 1)) | 0;
  33197. var heightMapY = ((1.0 - (position.z + options.height / 2) / options.height) * (options.bufferHeight - 1)) | 0;
  33198. var pos = (heightMapX + heightMapY * options.bufferWidth) * 4;
  33199. var r = options.buffer[pos] / 255.0;
  33200. var g = options.buffer[pos + 1] / 255.0;
  33201. var b = options.buffer[pos + 2] / 255.0;
  33202. var gradient = r * filter.r + g * filter.g + b * filter.b;
  33203. position.y = options.minHeight + (options.maxHeight - options.minHeight) * gradient;
  33204. // Add vertex
  33205. positions.push(position.x, position.y, position.z);
  33206. normals.push(0, 0, 0);
  33207. uvs.push(col / options.subdivisions, 1.0 - row / options.subdivisions);
  33208. }
  33209. }
  33210. // Indices
  33211. for (row = 0; row < options.subdivisions; row++) {
  33212. for (col = 0; col < options.subdivisions; col++) {
  33213. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  33214. indices.push(col + 1 + row * (options.subdivisions + 1));
  33215. indices.push(col + row * (options.subdivisions + 1));
  33216. indices.push(col + (row + 1) * (options.subdivisions + 1));
  33217. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  33218. indices.push(col + row * (options.subdivisions + 1));
  33219. }
  33220. }
  33221. // Normals
  33222. VertexData.ComputeNormals(positions, indices, normals);
  33223. // Result
  33224. var vertexData = new VertexData();
  33225. vertexData.indices = indices;
  33226. vertexData.positions = positions;
  33227. vertexData.normals = normals;
  33228. vertexData.uvs = uvs;
  33229. return vertexData;
  33230. };
  33231. /**
  33232. * Creates the VertexData of the Plane.
  33233. */
  33234. VertexData.CreatePlane = function (options) {
  33235. var indices = [];
  33236. var positions = [];
  33237. var normals = [];
  33238. var uvs = [];
  33239. var width = options.width || options.size || 1;
  33240. var height = options.height || options.size || 1;
  33241. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  33242. // Vertices
  33243. var halfWidth = width / 2.0;
  33244. var halfHeight = height / 2.0;
  33245. positions.push(-halfWidth, -halfHeight, 0);
  33246. normals.push(0, 0, -1.0);
  33247. uvs.push(0.0, 0.0);
  33248. positions.push(halfWidth, -halfHeight, 0);
  33249. normals.push(0, 0, -1.0);
  33250. uvs.push(1.0, 0.0);
  33251. positions.push(halfWidth, halfHeight, 0);
  33252. normals.push(0, 0, -1.0);
  33253. uvs.push(1.0, 1.0);
  33254. positions.push(-halfWidth, halfHeight, 0);
  33255. normals.push(0, 0, -1.0);
  33256. uvs.push(0.0, 1.0);
  33257. // Indices
  33258. indices.push(0);
  33259. indices.push(1);
  33260. indices.push(2);
  33261. indices.push(0);
  33262. indices.push(2);
  33263. indices.push(3);
  33264. // Sides
  33265. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  33266. // Result
  33267. var vertexData = new VertexData();
  33268. vertexData.indices = indices;
  33269. vertexData.positions = positions;
  33270. vertexData.normals = normals;
  33271. vertexData.uvs = uvs;
  33272. return vertexData;
  33273. };
  33274. /**
  33275. * Creates the VertexData of the Disc or regular Polygon.
  33276. */
  33277. VertexData.CreateDisc = function (options) {
  33278. var positions = new Array();
  33279. var indices = new Array();
  33280. var normals = new Array();
  33281. var uvs = new Array();
  33282. var radius = options.radius || 0.5;
  33283. var tessellation = options.tessellation || 64;
  33284. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  33285. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  33286. // positions and uvs
  33287. positions.push(0, 0, 0); // disc center first
  33288. uvs.push(0.5, 0.5);
  33289. var theta = Math.PI * 2 * arc;
  33290. var step = theta / tessellation;
  33291. for (var a = 0; a < theta; a += step) {
  33292. var x = Math.cos(a);
  33293. var y = Math.sin(a);
  33294. var u = (x + 1) / 2;
  33295. var v = (1 - y) / 2;
  33296. positions.push(radius * x, radius * y, 0);
  33297. uvs.push(u, v);
  33298. }
  33299. if (arc === 1) {
  33300. positions.push(positions[3], positions[4], positions[5]); // close the circle
  33301. uvs.push(uvs[2], uvs[3]);
  33302. }
  33303. //indices
  33304. var vertexNb = positions.length / 3;
  33305. for (var i = 1; i < vertexNb - 1; i++) {
  33306. indices.push(i + 1, 0, i);
  33307. }
  33308. // result
  33309. VertexData.ComputeNormals(positions, indices, normals);
  33310. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  33311. var vertexData = new VertexData();
  33312. vertexData.indices = indices;
  33313. vertexData.positions = positions;
  33314. vertexData.normals = normals;
  33315. vertexData.uvs = uvs;
  33316. return vertexData;
  33317. };
  33318. /**
  33319. * Re-creates the VertexData of the Polygon for sideOrientation.
  33320. */
  33321. VertexData.CreatePolygon = function (polygon, sideOrientation, fUV, fColors, frontUVs, backUVs) {
  33322. var faceUV = fUV || new Array(3);
  33323. var faceColors = fColors;
  33324. var colors = [];
  33325. // default face colors and UV if undefined
  33326. for (var f = 0; f < 3; f++) {
  33327. if (faceUV[f] === undefined) {
  33328. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  33329. }
  33330. if (faceColors && faceColors[f] === undefined) {
  33331. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  33332. }
  33333. }
  33334. var positions = polygon.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  33335. var normals = polygon.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  33336. var uvs = polygon.getVerticesData(BABYLON.VertexBuffer.UVKind);
  33337. var indices = polygon.getIndices();
  33338. // set face colours and textures
  33339. var idx = 0;
  33340. var face = 0;
  33341. for (var index = 0; index < normals.length; index += 3) {
  33342. //Edge Face no. 1
  33343. if (Math.abs(normals[index + 1]) < 0.001) {
  33344. face = 1;
  33345. }
  33346. //Top Face no. 0
  33347. if (Math.abs(normals[index + 1] - 1) < 0.001) {
  33348. face = 0;
  33349. }
  33350. //Bottom Face no. 2
  33351. if (Math.abs(normals[index + 1] + 1) < 0.001) {
  33352. face = 2;
  33353. }
  33354. idx = index / 3;
  33355. uvs[2 * idx] = (1 - uvs[2 * idx]) * faceUV[face].x + uvs[2 * idx] * faceUV[face].z;
  33356. uvs[2 * idx + 1] = (1 - uvs[2 * idx + 1]) * faceUV[face].y + uvs[2 * idx + 1] * faceUV[face].w;
  33357. if (faceColors) {
  33358. colors.push(faceColors[face].r, faceColors[face].g, faceColors[face].b, faceColors[face].a);
  33359. }
  33360. }
  33361. // sides
  33362. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, frontUVs, backUVs);
  33363. // Result
  33364. var vertexData = new VertexData();
  33365. vertexData.indices = indices;
  33366. vertexData.positions = positions;
  33367. vertexData.normals = normals;
  33368. vertexData.uvs = uvs;
  33369. if (faceColors) {
  33370. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  33371. vertexData.colors = totalColors;
  33372. }
  33373. return vertexData;
  33374. };
  33375. /**
  33376. * Creates the VertexData of the IcoSphere.
  33377. */
  33378. VertexData.CreateIcoSphere = function (options) {
  33379. var sideOrientation = options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  33380. var radius = options.radius || 1;
  33381. var flat = (options.flat === undefined) ? true : options.flat;
  33382. var subdivisions = options.subdivisions || 4;
  33383. var radiusX = options.radiusX || radius;
  33384. var radiusY = options.radiusY || radius;
  33385. var radiusZ = options.radiusZ || radius;
  33386. var t = (1 + Math.sqrt(5)) / 2;
  33387. // 12 vertex x,y,z
  33388. var ico_vertices = [
  33389. -1, t, -0, 1, t, 0, -1, -t, 0, 1, -t, 0,
  33390. 0, -1, -t, 0, 1, -t, 0, -1, t, 0, 1, t,
  33391. t, 0, 1, t, 0, -1, -t, 0, 1, -t, 0, -1 // v8-11
  33392. ];
  33393. // index of 3 vertex makes a face of icopshere
  33394. var ico_indices = [
  33395. 0, 11, 5, 0, 5, 1, 0, 1, 7, 0, 7, 10, 12, 22, 23,
  33396. 1, 5, 20, 5, 11, 4, 23, 22, 13, 22, 18, 6, 7, 1, 8,
  33397. 14, 21, 4, 14, 4, 2, 16, 13, 6, 15, 6, 19, 3, 8, 9,
  33398. 4, 21, 5, 13, 17, 23, 6, 13, 22, 19, 6, 18, 9, 8, 1
  33399. ];
  33400. // vertex for uv have aliased position, not for UV
  33401. var vertices_unalias_id = [
  33402. 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11,
  33403. // vertex alias
  33404. 0,
  33405. 2,
  33406. 3,
  33407. 3,
  33408. 3,
  33409. 4,
  33410. 7,
  33411. 8,
  33412. 9,
  33413. 9,
  33414. 10,
  33415. 11 // 23: B + 12
  33416. ];
  33417. // uv as integer step (not pixels !)
  33418. var ico_vertexuv = [
  33419. 5, 1, 3, 1, 6, 4, 0, 0,
  33420. 5, 3, 4, 2, 2, 2, 4, 0,
  33421. 2, 0, 1, 1, 6, 0, 6, 2,
  33422. // vertex alias (for same vertex on different faces)
  33423. 0, 4,
  33424. 3, 3,
  33425. 4, 4,
  33426. 3, 1,
  33427. 4, 2,
  33428. 4, 4,
  33429. 0, 2,
  33430. 1, 1,
  33431. 2, 2,
  33432. 3, 3,
  33433. 1, 3,
  33434. 2, 4 // 23: B + 12
  33435. ];
  33436. // Vertices[0, 1, ...9, A, B] : position on UV plane
  33437. // '+' indicate duplicate position to be fixed (3,9:0,2,3,4,7,8,A,B)
  33438. // First island of uv mapping
  33439. // v = 4h 3+ 2
  33440. // v = 3h 9+ 4
  33441. // v = 2h 9+ 5 B
  33442. // v = 1h 9 1 0
  33443. // v = 0h 3 8 7 A
  33444. // u = 0 1 2 3 4 5 6 *a
  33445. // Second island of uv mapping
  33446. // v = 4h 0+ B+ 4+
  33447. // v = 3h A+ 2+
  33448. // v = 2h 7+ 6 3+
  33449. // v = 1h 8+ 3+
  33450. // v = 0h
  33451. // u = 0 1 2 3 4 5 6 *a
  33452. // Face layout on texture UV mapping
  33453. // ============
  33454. // \ 4 /\ 16 / ======
  33455. // \ / \ / /\ 11 /
  33456. // \/ 7 \/ / \ /
  33457. // ======= / 10 \/
  33458. // /\ 17 /\ =======
  33459. // / \ / \ \ 15 /\
  33460. // / 8 \/ 12 \ \ / \
  33461. // ============ \/ 6 \
  33462. // \ 18 /\ ============
  33463. // \ / \ \ 5 /\ 0 /
  33464. // \/ 13 \ \ / \ /
  33465. // ======= \/ 1 \/
  33466. // =============
  33467. // /\ 19 /\ 2 /\
  33468. // / \ / \ / \
  33469. // / 14 \/ 9 \/ 3 \
  33470. // ===================
  33471. // uv step is u:1 or 0.5, v:cos(30)=sqrt(3)/2, ratio approx is 84/97
  33472. var ustep = 138 / 1024;
  33473. var vstep = 239 / 1024;
  33474. var uoffset = 60 / 1024;
  33475. var voffset = 26 / 1024;
  33476. // Second island should have margin, not to touch the first island
  33477. // avoid any borderline artefact in pixel rounding
  33478. var island_u_offset = -40 / 1024;
  33479. var island_v_offset = +20 / 1024;
  33480. // face is either island 0 or 1 :
  33481. // second island is for faces : [4, 7, 8, 12, 13, 16, 17, 18]
  33482. var island = [
  33483. 0, 0, 0, 0, 1,
  33484. 0, 0, 1, 1, 0,
  33485. 0, 0, 1, 1, 0,
  33486. 0, 1, 1, 1, 0 // 15 - 19
  33487. ];
  33488. var indices = new Array();
  33489. var positions = new Array();
  33490. var normals = new Array();
  33491. var uvs = new Array();
  33492. var current_indice = 0;
  33493. // prepare array of 3 vector (empty) (to be worked in place, shared for each face)
  33494. var face_vertex_pos = new Array(3);
  33495. var face_vertex_uv = new Array(3);
  33496. var v012;
  33497. for (v012 = 0; v012 < 3; v012++) {
  33498. face_vertex_pos[v012] = BABYLON.Vector3.Zero();
  33499. face_vertex_uv[v012] = BABYLON.Vector2.Zero();
  33500. }
  33501. // create all with normals
  33502. for (var face = 0; face < 20; face++) {
  33503. // 3 vertex per face
  33504. for (v012 = 0; v012 < 3; v012++) {
  33505. // look up vertex 0,1,2 to its index in 0 to 11 (or 23 including alias)
  33506. var v_id = ico_indices[3 * face + v012];
  33507. // vertex have 3D position (x,y,z)
  33508. 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]);
  33509. // Normalize to get normal, then scale to radius
  33510. face_vertex_pos[v012].normalize().scaleInPlace(radius);
  33511. // uv Coordinates from vertex ID
  33512. 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);
  33513. }
  33514. // Subdivide the face (interpolate pos, norm, uv)
  33515. // - pos is linear interpolation, then projected to sphere (converge polyhedron to sphere)
  33516. // - norm is linear interpolation of vertex corner normal
  33517. // (to be checked if better to re-calc from face vertex, or if approximation is OK ??? )
  33518. // - uv is linear interpolation
  33519. //
  33520. // Topology is as below for sub-divide by 2
  33521. // vertex shown as v0,v1,v2
  33522. // interp index is i1 to progress in range [v0,v1[
  33523. // interp index is i2 to progress in range [v0,v2[
  33524. // face index as (i1,i2) for /\ : (i1,i2),(i1+1,i2),(i1,i2+1)
  33525. // and (i1,i2)' for \/ : (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  33526. //
  33527. //
  33528. // i2 v2
  33529. // ^ ^
  33530. // / / \
  33531. // / / \
  33532. // / / \
  33533. // / / (0,1) \
  33534. // / #---------\
  33535. // / / \ (0,0)'/ \
  33536. // / / \ / \
  33537. // / / \ / \
  33538. // / / (0,0) \ / (1,0) \
  33539. // / #---------#---------\
  33540. // v0 v1
  33541. //
  33542. // --------------------> i1
  33543. //
  33544. // interp of (i1,i2):
  33545. // along i2 : x0=lerp(v0,v2, i2/S) <---> x1=lerp(v1,v2, i2/S)
  33546. // along i1 : lerp(x0,x1, i1/(S-i2))
  33547. //
  33548. // centroid of triangle is needed to get help normal computation
  33549. // (c1,c2) are used for centroid location
  33550. var interp_vertex = function (i1, i2, c1, c2) {
  33551. // vertex is interpolated from
  33552. // - face_vertex_pos[0..2]
  33553. // - face_vertex_uv[0..2]
  33554. var pos_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], i2 / subdivisions);
  33555. var pos_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], i2 / subdivisions);
  33556. var pos_interp = (subdivisions === i2) ? face_vertex_pos[2] : BABYLON.Vector3.Lerp(pos_x0, pos_x1, i1 / (subdivisions - i2));
  33557. pos_interp.normalize();
  33558. var vertex_normal;
  33559. if (flat) {
  33560. // in flat mode, recalculate normal as face centroid normal
  33561. var centroid_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], c2 / subdivisions);
  33562. var centroid_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], c2 / subdivisions);
  33563. vertex_normal = BABYLON.Vector3.Lerp(centroid_x0, centroid_x1, c1 / (subdivisions - c2));
  33564. }
  33565. else {
  33566. // in smooth mode, recalculate normal from each single vertex position
  33567. vertex_normal = new BABYLON.Vector3(pos_interp.x, pos_interp.y, pos_interp.z);
  33568. }
  33569. // Vertex normal need correction due to X,Y,Z radius scaling
  33570. vertex_normal.x /= radiusX;
  33571. vertex_normal.y /= radiusY;
  33572. vertex_normal.z /= radiusZ;
  33573. vertex_normal.normalize();
  33574. var uv_x0 = BABYLON.Vector2.Lerp(face_vertex_uv[0], face_vertex_uv[2], i2 / subdivisions);
  33575. var uv_x1 = BABYLON.Vector2.Lerp(face_vertex_uv[1], face_vertex_uv[2], i2 / subdivisions);
  33576. var uv_interp = (subdivisions === i2) ? face_vertex_uv[2] : BABYLON.Vector2.Lerp(uv_x0, uv_x1, i1 / (subdivisions - i2));
  33577. positions.push(pos_interp.x * radiusX, pos_interp.y * radiusY, pos_interp.z * radiusZ);
  33578. normals.push(vertex_normal.x, vertex_normal.y, vertex_normal.z);
  33579. uvs.push(uv_interp.x, uv_interp.y);
  33580. // push each vertex has member of a face
  33581. // Same vertex can bleong to multiple face, it is pushed multiple time (duplicate vertex are present)
  33582. indices.push(current_indice);
  33583. current_indice++;
  33584. };
  33585. for (var i2 = 0; i2 < subdivisions; i2++) {
  33586. for (var i1 = 0; i1 + i2 < subdivisions; i1++) {
  33587. // face : (i1,i2) for /\ :
  33588. // interp for : (i1,i2),(i1+1,i2),(i1,i2+1)
  33589. interp_vertex(i1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  33590. interp_vertex(i1 + 1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  33591. interp_vertex(i1, i2 + 1, i1 + 1.0 / 3, i2 + 1.0 / 3);
  33592. if (i1 + i2 + 1 < subdivisions) {
  33593. // face : (i1,i2)' for \/ :
  33594. // interp for (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  33595. interp_vertex(i1 + 1, i2, i1 + 2.0 / 3, i2 + 2.0 / 3);
  33596. interp_vertex(i1 + 1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  33597. interp_vertex(i1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  33598. }
  33599. }
  33600. }
  33601. }
  33602. // Sides
  33603. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  33604. // Result
  33605. var vertexData = new VertexData();
  33606. vertexData.indices = indices;
  33607. vertexData.positions = positions;
  33608. vertexData.normals = normals;
  33609. vertexData.uvs = uvs;
  33610. return vertexData;
  33611. };
  33612. // inspired from // http://stemkoski.github.io/Three.js/Polyhedra.html
  33613. /**
  33614. * Creates the VertexData of the Polyhedron.
  33615. */
  33616. VertexData.CreatePolyhedron = function (options) {
  33617. // provided polyhedron types :
  33618. // 0 : Tetrahedron, 1 : Octahedron, 2 : Dodecahedron, 3 : Icosahedron, 4 : Rhombicuboctahedron, 5 : Triangular Prism, 6 : Pentagonal Prism, 7 : Hexagonal Prism, 8 : Square Pyramid (J1)
  33619. // 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)
  33620. var polyhedra = [];
  33621. 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]] };
  33622. 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]] };
  33623. polyhedra[2] = {
  33624. 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]],
  33625. 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]]
  33626. };
  33627. polyhedra[3] = {
  33628. 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]],
  33629. 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]]
  33630. };
  33631. polyhedra[4] = {
  33632. 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]],
  33633. 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]]
  33634. };
  33635. 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]] };
  33636. 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]] };
  33637. 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]] };
  33638. 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]] };
  33639. 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]] };
  33640. 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]] };
  33641. 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]] };
  33642. 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]] };
  33643. 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]] };
  33644. polyhedra[14] = {
  33645. 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]],
  33646. 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]]
  33647. };
  33648. var type = options.type && (options.type < 0 || options.type >= polyhedra.length) ? 0 : options.type || 0;
  33649. var size = options.size;
  33650. var sizeX = options.sizeX || size || 1;
  33651. var sizeY = options.sizeY || size || 1;
  33652. var sizeZ = options.sizeZ || size || 1;
  33653. var data = options.custom || polyhedra[type];
  33654. var nbfaces = data.face.length;
  33655. var faceUV = options.faceUV || new Array(nbfaces);
  33656. var faceColors = options.faceColors;
  33657. var flat = (options.flat === undefined) ? true : options.flat;
  33658. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  33659. var positions = new Array();
  33660. var indices = new Array();
  33661. var normals = new Array();
  33662. var uvs = new Array();
  33663. var colors = new Array();
  33664. var index = 0;
  33665. var faceIdx = 0; // face cursor in the array "indexes"
  33666. var indexes = new Array();
  33667. var i = 0;
  33668. var f = 0;
  33669. var u, v, ang, x, y, tmp;
  33670. // default face colors and UV if undefined
  33671. if (flat) {
  33672. for (f = 0; f < nbfaces; f++) {
  33673. if (faceColors && faceColors[f] === undefined) {
  33674. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  33675. }
  33676. if (faceUV && faceUV[f] === undefined) {
  33677. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  33678. }
  33679. }
  33680. }
  33681. if (!flat) {
  33682. for (i = 0; i < data.vertex.length; i++) {
  33683. positions.push(data.vertex[i][0] * sizeX, data.vertex[i][1] * sizeY, data.vertex[i][2] * sizeZ);
  33684. uvs.push(0, 0);
  33685. }
  33686. for (f = 0; f < nbfaces; f++) {
  33687. for (i = 0; i < data.face[f].length - 2; i++) {
  33688. indices.push(data.face[f][0], data.face[f][i + 2], data.face[f][i + 1]);
  33689. }
  33690. }
  33691. }
  33692. else {
  33693. for (f = 0; f < nbfaces; f++) {
  33694. var fl = data.face[f].length; // number of vertices of the current face
  33695. ang = 2 * Math.PI / fl;
  33696. x = 0.5 * Math.tan(ang / 2);
  33697. y = 0.5;
  33698. // positions, uvs, colors
  33699. for (i = 0; i < fl; i++) {
  33700. // positions
  33701. 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);
  33702. indexes.push(index);
  33703. index++;
  33704. // uvs
  33705. u = faceUV[f].x + (faceUV[f].z - faceUV[f].x) * (0.5 + x);
  33706. v = faceUV[f].y + (faceUV[f].w - faceUV[f].y) * (y - 0.5);
  33707. uvs.push(u, v);
  33708. tmp = x * Math.cos(ang) - y * Math.sin(ang);
  33709. y = x * Math.sin(ang) + y * Math.cos(ang);
  33710. x = tmp;
  33711. // colors
  33712. if (faceColors) {
  33713. colors.push(faceColors[f].r, faceColors[f].g, faceColors[f].b, faceColors[f].a);
  33714. }
  33715. }
  33716. // indices from indexes
  33717. for (i = 0; i < fl - 2; i++) {
  33718. indices.push(indexes[0 + faceIdx], indexes[i + 2 + faceIdx], indexes[i + 1 + faceIdx]);
  33719. }
  33720. faceIdx += fl;
  33721. }
  33722. }
  33723. VertexData.ComputeNormals(positions, indices, normals);
  33724. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  33725. var vertexData = new VertexData();
  33726. vertexData.positions = positions;
  33727. vertexData.indices = indices;
  33728. vertexData.normals = normals;
  33729. vertexData.uvs = uvs;
  33730. if (faceColors && flat) {
  33731. vertexData.colors = colors;
  33732. }
  33733. return vertexData;
  33734. };
  33735. // based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3D/src/away3d/primitives/TorusKnot.as?spec=svn2473&r=2473
  33736. /**
  33737. * Creates the VertexData of the Torus Knot.
  33738. */
  33739. VertexData.CreateTorusKnot = function (options) {
  33740. var indices = new Array();
  33741. var positions = new Array();
  33742. var normals = new Array();
  33743. var uvs = new Array();
  33744. var radius = options.radius || 2;
  33745. var tube = options.tube || 0.5;
  33746. var radialSegments = options.radialSegments || 32;
  33747. var tubularSegments = options.tubularSegments || 32;
  33748. var p = options.p || 2;
  33749. var q = options.q || 3;
  33750. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  33751. // Helper
  33752. var getPos = function (angle) {
  33753. var cu = Math.cos(angle);
  33754. var su = Math.sin(angle);
  33755. var quOverP = q / p * angle;
  33756. var cs = Math.cos(quOverP);
  33757. var tx = radius * (2 + cs) * 0.5 * cu;
  33758. var ty = radius * (2 + cs) * su * 0.5;
  33759. var tz = radius * Math.sin(quOverP) * 0.5;
  33760. return new BABYLON.Vector3(tx, ty, tz);
  33761. };
  33762. // Vertices
  33763. var i;
  33764. var j;
  33765. for (i = 0; i <= radialSegments; i++) {
  33766. var modI = i % radialSegments;
  33767. var u = modI / radialSegments * 2 * p * Math.PI;
  33768. var p1 = getPos(u);
  33769. var p2 = getPos(u + 0.01);
  33770. var tang = p2.subtract(p1);
  33771. var n = p2.add(p1);
  33772. var bitan = BABYLON.Vector3.Cross(tang, n);
  33773. n = BABYLON.Vector3.Cross(bitan, tang);
  33774. bitan.normalize();
  33775. n.normalize();
  33776. for (j = 0; j < tubularSegments; j++) {
  33777. var modJ = j % tubularSegments;
  33778. var v = modJ / tubularSegments * 2 * Math.PI;
  33779. var cx = -tube * Math.cos(v);
  33780. var cy = tube * Math.sin(v);
  33781. positions.push(p1.x + cx * n.x + cy * bitan.x);
  33782. positions.push(p1.y + cx * n.y + cy * bitan.y);
  33783. positions.push(p1.z + cx * n.z + cy * bitan.z);
  33784. uvs.push(i / radialSegments);
  33785. uvs.push(j / tubularSegments);
  33786. }
  33787. }
  33788. for (i = 0; i < radialSegments; i++) {
  33789. for (j = 0; j < tubularSegments; j++) {
  33790. var jNext = (j + 1) % tubularSegments;
  33791. var a = i * tubularSegments + j;
  33792. var b = (i + 1) * tubularSegments + j;
  33793. var c = (i + 1) * tubularSegments + jNext;
  33794. var d = i * tubularSegments + jNext;
  33795. indices.push(d);
  33796. indices.push(b);
  33797. indices.push(a);
  33798. indices.push(d);
  33799. indices.push(c);
  33800. indices.push(b);
  33801. }
  33802. }
  33803. // Normals
  33804. VertexData.ComputeNormals(positions, indices, normals);
  33805. // Sides
  33806. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  33807. // Result
  33808. var vertexData = new VertexData();
  33809. vertexData.indices = indices;
  33810. vertexData.positions = positions;
  33811. vertexData.normals = normals;
  33812. vertexData.uvs = uvs;
  33813. return vertexData;
  33814. };
  33815. // Tools
  33816. /**
  33817. * @param {any} - positions (number[] or Float32Array)
  33818. * @param {any} - indices (number[] or Uint16Array)
  33819. * @param {any} - normals (number[] or Float32Array)
  33820. * options (optional) :
  33821. * facetPositions : optional array of facet positions (vector3)
  33822. * facetNormals : optional array of facet normals (vector3)
  33823. * facetPartitioning : optional partitioning array. facetPositions is required for facetPartitioning computation
  33824. * subDiv : optional partitioning data about subdivsions on each axis (int), required for facetPartitioning computation
  33825. * ratio : optional partitioning ratio / bounding box, required for facetPartitioning computation
  33826. * bbSize : optional bounding box size data, required for facetPartitioning computation
  33827. * bInfo : optional bounding info, required for facetPartitioning computation
  33828. * useRightHandedSystem: optional boolean to for right handed system computation
  33829. * depthSort : optional boolean to enable the facet depth sort computation
  33830. * distanceTo : optional Vector3 to compute the facet depth from this location
  33831. * depthSortedFacets : optional array of depthSortedFacets to store the facet distances from the reference location
  33832. */
  33833. VertexData.ComputeNormals = function (positions, indices, normals, options) {
  33834. // temporary scalar variables
  33835. var index = 0; // facet index
  33836. var p1p2x = 0.0; // p1p2 vector x coordinate
  33837. var p1p2y = 0.0; // p1p2 vector y coordinate
  33838. var p1p2z = 0.0; // p1p2 vector z coordinate
  33839. var p3p2x = 0.0; // p3p2 vector x coordinate
  33840. var p3p2y = 0.0; // p3p2 vector y coordinate
  33841. var p3p2z = 0.0; // p3p2 vector z coordinate
  33842. var faceNormalx = 0.0; // facet normal x coordinate
  33843. var faceNormaly = 0.0; // facet normal y coordinate
  33844. var faceNormalz = 0.0; // facet normal z coordinate
  33845. var length = 0.0; // facet normal length before normalization
  33846. var v1x = 0; // vector1 x index in the positions array
  33847. var v1y = 0; // vector1 y index in the positions array
  33848. var v1z = 0; // vector1 z index in the positions array
  33849. var v2x = 0; // vector2 x index in the positions array
  33850. var v2y = 0; // vector2 y index in the positions array
  33851. var v2z = 0; // vector2 z index in the positions array
  33852. var v3x = 0; // vector3 x index in the positions array
  33853. var v3y = 0; // vector3 y index in the positions array
  33854. var v3z = 0; // vector3 z index in the positions array
  33855. var computeFacetNormals = false;
  33856. var computeFacetPositions = false;
  33857. var computeFacetPartitioning = false;
  33858. var computeDepthSort = false;
  33859. var faceNormalSign = 1;
  33860. var ratio = 0;
  33861. var distanceTo = null;
  33862. if (options) {
  33863. computeFacetNormals = (options.facetNormals) ? true : false;
  33864. computeFacetPositions = (options.facetPositions) ? true : false;
  33865. computeFacetPartitioning = (options.facetPartitioning) ? true : false;
  33866. faceNormalSign = (options.useRightHandedSystem === true) ? -1 : 1;
  33867. ratio = options.ratio || 0;
  33868. computeDepthSort = (options.depthSort) ? true : false;
  33869. distanceTo = (options.distanceTo);
  33870. if (computeDepthSort) {
  33871. if (distanceTo === undefined) {
  33872. distanceTo = BABYLON.Vector3.Zero();
  33873. }
  33874. var depthSortedFacets = options.depthSortedFacets;
  33875. }
  33876. }
  33877. // facetPartitioning reinit if needed
  33878. var xSubRatio = 0;
  33879. var ySubRatio = 0;
  33880. var zSubRatio = 0;
  33881. var subSq = 0;
  33882. if (computeFacetPartitioning && options && options.bbSize) {
  33883. var ox = 0; // X partitioning index for facet position
  33884. var oy = 0; // Y partinioning index for facet position
  33885. var oz = 0; // Z partinioning index for facet position
  33886. var b1x = 0; // X partitioning index for facet v1 vertex
  33887. var b1y = 0; // Y partitioning index for facet v1 vertex
  33888. var b1z = 0; // z partitioning index for facet v1 vertex
  33889. var b2x = 0; // X partitioning index for facet v2 vertex
  33890. var b2y = 0; // Y partitioning index for facet v2 vertex
  33891. var b2z = 0; // Z partitioning index for facet v2 vertex
  33892. var b3x = 0; // X partitioning index for facet v3 vertex
  33893. var b3y = 0; // Y partitioning index for facet v3 vertex
  33894. var b3z = 0; // Z partitioning index for facet v3 vertex
  33895. var block_idx_o = 0; // facet barycenter block index
  33896. var block_idx_v1 = 0; // v1 vertex block index
  33897. var block_idx_v2 = 0; // v2 vertex block index
  33898. var block_idx_v3 = 0; // v3 vertex block index
  33899. var bbSizeMax = (options.bbSize.x > options.bbSize.y) ? options.bbSize.x : options.bbSize.y;
  33900. bbSizeMax = (bbSizeMax > options.bbSize.z) ? bbSizeMax : options.bbSize.z;
  33901. xSubRatio = options.subDiv.X * ratio / options.bbSize.x;
  33902. ySubRatio = options.subDiv.Y * ratio / options.bbSize.y;
  33903. zSubRatio = options.subDiv.Z * ratio / options.bbSize.z;
  33904. subSq = options.subDiv.max * options.subDiv.max;
  33905. options.facetPartitioning.length = 0;
  33906. }
  33907. // reset the normals
  33908. for (index = 0; index < positions.length; index++) {
  33909. normals[index] = 0.0;
  33910. }
  33911. // Loop : 1 indice triplet = 1 facet
  33912. var nbFaces = (indices.length / 3) | 0;
  33913. for (index = 0; index < nbFaces; index++) {
  33914. // get the indexes of the coordinates of each vertex of the facet
  33915. v1x = indices[index * 3] * 3;
  33916. v1y = v1x + 1;
  33917. v1z = v1x + 2;
  33918. v2x = indices[index * 3 + 1] * 3;
  33919. v2y = v2x + 1;
  33920. v2z = v2x + 2;
  33921. v3x = indices[index * 3 + 2] * 3;
  33922. v3y = v3x + 1;
  33923. v3z = v3x + 2;
  33924. p1p2x = positions[v1x] - positions[v2x]; // compute two vectors per facet : p1p2 and p3p2
  33925. p1p2y = positions[v1y] - positions[v2y];
  33926. p1p2z = positions[v1z] - positions[v2z];
  33927. p3p2x = positions[v3x] - positions[v2x];
  33928. p3p2y = positions[v3y] - positions[v2y];
  33929. p3p2z = positions[v3z] - positions[v2z];
  33930. // compute the face normal with the cross product
  33931. faceNormalx = faceNormalSign * (p1p2y * p3p2z - p1p2z * p3p2y);
  33932. faceNormaly = faceNormalSign * (p1p2z * p3p2x - p1p2x * p3p2z);
  33933. faceNormalz = faceNormalSign * (p1p2x * p3p2y - p1p2y * p3p2x);
  33934. // normalize this normal and store it in the array facetData
  33935. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  33936. length = (length === 0) ? 1.0 : length;
  33937. faceNormalx /= length;
  33938. faceNormaly /= length;
  33939. faceNormalz /= length;
  33940. if (computeFacetNormals && options) {
  33941. options.facetNormals[index].x = faceNormalx;
  33942. options.facetNormals[index].y = faceNormaly;
  33943. options.facetNormals[index].z = faceNormalz;
  33944. }
  33945. if (computeFacetPositions && options) {
  33946. // compute and the facet barycenter coordinates in the array facetPositions
  33947. options.facetPositions[index].x = (positions[v1x] + positions[v2x] + positions[v3x]) / 3.0;
  33948. options.facetPositions[index].y = (positions[v1y] + positions[v2y] + positions[v3y]) / 3.0;
  33949. options.facetPositions[index].z = (positions[v1z] + positions[v2z] + positions[v3z]) / 3.0;
  33950. }
  33951. if (computeFacetPartitioning && options) {
  33952. // store the facet indexes in arrays in the main facetPartitioning array :
  33953. // compute each facet vertex (+ facet barycenter) index in the partiniong array
  33954. ox = Math.floor((options.facetPositions[index].x - options.bInfo.minimum.x * ratio) * xSubRatio);
  33955. oy = Math.floor((options.facetPositions[index].y - options.bInfo.minimum.y * ratio) * ySubRatio);
  33956. oz = Math.floor((options.facetPositions[index].z - options.bInfo.minimum.z * ratio) * zSubRatio);
  33957. b1x = Math.floor((positions[v1x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  33958. b1y = Math.floor((positions[v1y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  33959. b1z = Math.floor((positions[v1z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  33960. b2x = Math.floor((positions[v2x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  33961. b2y = Math.floor((positions[v2y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  33962. b2z = Math.floor((positions[v2z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  33963. b3x = Math.floor((positions[v3x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  33964. b3y = Math.floor((positions[v3y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  33965. b3z = Math.floor((positions[v3z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  33966. block_idx_v1 = b1x + options.subDiv.max * b1y + subSq * b1z;
  33967. block_idx_v2 = b2x + options.subDiv.max * b2y + subSq * b2z;
  33968. block_idx_v3 = b3x + options.subDiv.max * b3y + subSq * b3z;
  33969. block_idx_o = ox + options.subDiv.max * oy + subSq * oz;
  33970. options.facetPartitioning[block_idx_o] = options.facetPartitioning[block_idx_o] ? options.facetPartitioning[block_idx_o] : new Array();
  33971. options.facetPartitioning[block_idx_v1] = options.facetPartitioning[block_idx_v1] ? options.facetPartitioning[block_idx_v1] : new Array();
  33972. options.facetPartitioning[block_idx_v2] = options.facetPartitioning[block_idx_v2] ? options.facetPartitioning[block_idx_v2] : new Array();
  33973. options.facetPartitioning[block_idx_v3] = options.facetPartitioning[block_idx_v3] ? options.facetPartitioning[block_idx_v3] : new Array();
  33974. // push each facet index in each block containing the vertex
  33975. options.facetPartitioning[block_idx_v1].push(index);
  33976. if (block_idx_v2 != block_idx_v1) {
  33977. options.facetPartitioning[block_idx_v2].push(index);
  33978. }
  33979. if (!(block_idx_v3 == block_idx_v2 || block_idx_v3 == block_idx_v1)) {
  33980. options.facetPartitioning[block_idx_v3].push(index);
  33981. }
  33982. if (!(block_idx_o == block_idx_v1 || block_idx_o == block_idx_v2 || block_idx_o == block_idx_v3)) {
  33983. options.facetPartitioning[block_idx_o].push(index);
  33984. }
  33985. }
  33986. if (computeDepthSort && options && options.facetPositions) {
  33987. var dsf = depthSortedFacets[index];
  33988. dsf.ind = index * 3;
  33989. dsf.sqDistance = BABYLON.Vector3.DistanceSquared(options.facetPositions[index], distanceTo);
  33990. }
  33991. // compute the normals anyway
  33992. normals[v1x] += faceNormalx; // accumulate all the normals per face
  33993. normals[v1y] += faceNormaly;
  33994. normals[v1z] += faceNormalz;
  33995. normals[v2x] += faceNormalx;
  33996. normals[v2y] += faceNormaly;
  33997. normals[v2z] += faceNormalz;
  33998. normals[v3x] += faceNormalx;
  33999. normals[v3y] += faceNormaly;
  34000. normals[v3z] += faceNormalz;
  34001. }
  34002. // last normalization of each normal
  34003. for (index = 0; index < normals.length / 3; index++) {
  34004. faceNormalx = normals[index * 3];
  34005. faceNormaly = normals[index * 3 + 1];
  34006. faceNormalz = normals[index * 3 + 2];
  34007. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  34008. length = (length === 0) ? 1.0 : length;
  34009. faceNormalx /= length;
  34010. faceNormaly /= length;
  34011. faceNormalz /= length;
  34012. normals[index * 3] = faceNormalx;
  34013. normals[index * 3 + 1] = faceNormaly;
  34014. normals[index * 3 + 2] = faceNormalz;
  34015. }
  34016. };
  34017. VertexData._ComputeSides = function (sideOrientation, positions, indices, normals, uvs, frontUVs, backUVs) {
  34018. var li = indices.length;
  34019. var ln = normals.length;
  34020. var i;
  34021. var n;
  34022. sideOrientation = sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  34023. switch (sideOrientation) {
  34024. case BABYLON.Mesh.FRONTSIDE:
  34025. // nothing changed
  34026. break;
  34027. case BABYLON.Mesh.BACKSIDE:
  34028. var tmp;
  34029. // indices
  34030. for (i = 0; i < li; i += 3) {
  34031. tmp = indices[i];
  34032. indices[i] = indices[i + 2];
  34033. indices[i + 2] = tmp;
  34034. }
  34035. // normals
  34036. for (n = 0; n < ln; n++) {
  34037. normals[n] = -normals[n];
  34038. }
  34039. break;
  34040. case BABYLON.Mesh.DOUBLESIDE:
  34041. // positions
  34042. var lp = positions.length;
  34043. var l = lp / 3;
  34044. for (var p = 0; p < lp; p++) {
  34045. positions[lp + p] = positions[p];
  34046. }
  34047. // indices
  34048. for (i = 0; i < li; i += 3) {
  34049. indices[i + li] = indices[i + 2] + l;
  34050. indices[i + 1 + li] = indices[i + 1] + l;
  34051. indices[i + 2 + li] = indices[i] + l;
  34052. }
  34053. // normals
  34054. for (n = 0; n < ln; n++) {
  34055. normals[ln + n] = -normals[n];
  34056. }
  34057. // uvs
  34058. var lu = uvs.length;
  34059. var u = 0;
  34060. for (u = 0; u < lu; u++) {
  34061. uvs[u + lu] = uvs[u];
  34062. }
  34063. frontUVs = frontUVs ? frontUVs : new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  34064. backUVs = backUVs ? backUVs : new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  34065. u = 0;
  34066. for (i = 0; i < lu / 2; i++) {
  34067. uvs[u] = frontUVs.x + (frontUVs.z - frontUVs.x) * uvs[u];
  34068. uvs[u + 1] = frontUVs.y + (frontUVs.w - frontUVs.y) * uvs[u + 1];
  34069. uvs[u + lu] = backUVs.x + (backUVs.z - backUVs.x) * uvs[u + lu];
  34070. uvs[u + lu + 1] = backUVs.y + (backUVs.w - backUVs.y) * uvs[u + lu + 1];
  34071. u += 2;
  34072. }
  34073. break;
  34074. }
  34075. };
  34076. /**
  34077. * Creates a new VertexData from the imported parameters.
  34078. */
  34079. VertexData.ImportVertexData = function (parsedVertexData, geometry) {
  34080. var vertexData = new VertexData();
  34081. // positions
  34082. var positions = parsedVertexData.positions;
  34083. if (positions) {
  34084. vertexData.set(positions, BABYLON.VertexBuffer.PositionKind);
  34085. }
  34086. // normals
  34087. var normals = parsedVertexData.normals;
  34088. if (normals) {
  34089. vertexData.set(normals, BABYLON.VertexBuffer.NormalKind);
  34090. }
  34091. // tangents
  34092. var tangents = parsedVertexData.tangents;
  34093. if (tangents) {
  34094. vertexData.set(tangents, BABYLON.VertexBuffer.TangentKind);
  34095. }
  34096. // uvs
  34097. var uvs = parsedVertexData.uvs;
  34098. if (uvs) {
  34099. vertexData.set(uvs, BABYLON.VertexBuffer.UVKind);
  34100. }
  34101. // uv2s
  34102. var uv2s = parsedVertexData.uv2s;
  34103. if (uv2s) {
  34104. vertexData.set(uv2s, BABYLON.VertexBuffer.UV2Kind);
  34105. }
  34106. // uv3s
  34107. var uv3s = parsedVertexData.uv3s;
  34108. if (uv3s) {
  34109. vertexData.set(uv3s, BABYLON.VertexBuffer.UV3Kind);
  34110. }
  34111. // uv4s
  34112. var uv4s = parsedVertexData.uv4s;
  34113. if (uv4s) {
  34114. vertexData.set(uv4s, BABYLON.VertexBuffer.UV4Kind);
  34115. }
  34116. // uv5s
  34117. var uv5s = parsedVertexData.uv5s;
  34118. if (uv5s) {
  34119. vertexData.set(uv5s, BABYLON.VertexBuffer.UV5Kind);
  34120. }
  34121. // uv6s
  34122. var uv6s = parsedVertexData.uv6s;
  34123. if (uv6s) {
  34124. vertexData.set(uv6s, BABYLON.VertexBuffer.UV6Kind);
  34125. }
  34126. // colors
  34127. var colors = parsedVertexData.colors;
  34128. if (colors) {
  34129. vertexData.set(BABYLON.Color4.CheckColors4(colors, positions.length / 3), BABYLON.VertexBuffer.ColorKind);
  34130. }
  34131. // matricesIndices
  34132. var matricesIndices = parsedVertexData.matricesIndices;
  34133. if (matricesIndices) {
  34134. vertexData.set(matricesIndices, BABYLON.VertexBuffer.MatricesIndicesKind);
  34135. }
  34136. // matricesWeights
  34137. var matricesWeights = parsedVertexData.matricesWeights;
  34138. if (matricesWeights) {
  34139. vertexData.set(matricesWeights, BABYLON.VertexBuffer.MatricesWeightsKind);
  34140. }
  34141. // indices
  34142. var indices = parsedVertexData.indices;
  34143. if (indices) {
  34144. vertexData.indices = indices;
  34145. }
  34146. geometry.setAllVerticesData(vertexData, parsedVertexData.updatable);
  34147. };
  34148. return VertexData;
  34149. }());
  34150. BABYLON.VertexData = VertexData;
  34151. })(BABYLON || (BABYLON = {}));
  34152. //# sourceMappingURL=babylon.mesh.vertexData.js.map
  34153. var BABYLON;
  34154. (function (BABYLON) {
  34155. /**
  34156. * Class used to store geometry data (vertex buffers + index buffer)
  34157. */
  34158. var Geometry = /** @class */ (function () {
  34159. /**
  34160. * Creates a new geometry
  34161. * @param id defines the unique ID
  34162. * @param scene defines the hosting scene
  34163. * @param vertexData defines the {BABYLON.VertexData} used to get geometry data
  34164. * @param updatable defines if geometry must be updatable (false by default)
  34165. * @param mesh defines the mesh that will be associated with the geometry
  34166. */
  34167. function Geometry(id, scene, vertexData, updatable, mesh) {
  34168. if (updatable === void 0) { updatable = false; }
  34169. if (mesh === void 0) { mesh = null; }
  34170. /**
  34171. * Gets the delay loading state of the geometry (none by default which means not delayed)
  34172. */
  34173. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  34174. this._totalVertices = 0;
  34175. this._isDisposed = false;
  34176. this._indexBufferIsUpdatable = false;
  34177. this.id = id;
  34178. this._engine = scene.getEngine();
  34179. this._meshes = [];
  34180. this._scene = scene;
  34181. //Init vertex buffer cache
  34182. this._vertexBuffers = {};
  34183. this._indices = [];
  34184. this._updatable = updatable;
  34185. // vertexData
  34186. if (vertexData) {
  34187. this.setAllVerticesData(vertexData, updatable);
  34188. }
  34189. else {
  34190. this._totalVertices = 0;
  34191. this._indices = [];
  34192. }
  34193. if (this._engine.getCaps().vertexArrayObject) {
  34194. this._vertexArrayObjects = {};
  34195. }
  34196. // applyToMesh
  34197. if (mesh) {
  34198. if (mesh.getClassName() === "LinesMesh") {
  34199. this.boundingBias = new BABYLON.Vector2(0, mesh.intersectionThreshold);
  34200. this.updateExtend();
  34201. }
  34202. this.applyToMesh(mesh);
  34203. mesh.computeWorldMatrix(true);
  34204. }
  34205. }
  34206. Object.defineProperty(Geometry.prototype, "boundingBias", {
  34207. /**
  34208. * 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
  34209. */
  34210. get: function () {
  34211. return this._boundingBias;
  34212. },
  34213. /**
  34214. * 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
  34215. */
  34216. set: function (value) {
  34217. if (this._boundingBias && this._boundingBias.equals(value)) {
  34218. return;
  34219. }
  34220. this._boundingBias = value.clone();
  34221. this.updateBoundingInfo(true, null);
  34222. },
  34223. enumerable: true,
  34224. configurable: true
  34225. });
  34226. /**
  34227. * Static function used to attach a new empty geometry to a mesh
  34228. * @param mesh defines the mesh to attach the geometry to
  34229. * @returns the new {BABYLON.Geometry}
  34230. */
  34231. Geometry.CreateGeometryForMesh = function (mesh) {
  34232. var geometry = new Geometry(Geometry.RandomId(), mesh.getScene());
  34233. geometry.applyToMesh(mesh);
  34234. return geometry;
  34235. };
  34236. Object.defineProperty(Geometry.prototype, "extend", {
  34237. /**
  34238. * Gets the current extend of the geometry
  34239. */
  34240. get: function () {
  34241. return this._extend;
  34242. },
  34243. enumerable: true,
  34244. configurable: true
  34245. });
  34246. /**
  34247. * Gets the hosting scene
  34248. * @returns the hosting {BABYLON.Scene}
  34249. */
  34250. Geometry.prototype.getScene = function () {
  34251. return this._scene;
  34252. };
  34253. /**
  34254. * Gets the hosting engine
  34255. * @returns the hosting {BABYLON.Engine}
  34256. */
  34257. Geometry.prototype.getEngine = function () {
  34258. return this._engine;
  34259. };
  34260. /**
  34261. * Defines if the geometry is ready to use
  34262. * @returns true if the geometry is ready to be used
  34263. */
  34264. Geometry.prototype.isReady = function () {
  34265. return this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE;
  34266. };
  34267. Object.defineProperty(Geometry.prototype, "doNotSerialize", {
  34268. /**
  34269. * Gets a value indicating that the geometry should not be serialized
  34270. */
  34271. get: function () {
  34272. for (var index = 0; index < this._meshes.length; index++) {
  34273. if (!this._meshes[index].doNotSerialize) {
  34274. return false;
  34275. }
  34276. }
  34277. return true;
  34278. },
  34279. enumerable: true,
  34280. configurable: true
  34281. });
  34282. /** @ignore */
  34283. Geometry.prototype._rebuild = function () {
  34284. if (this._vertexArrayObjects) {
  34285. this._vertexArrayObjects = {};
  34286. }
  34287. // Index buffer
  34288. if (this._meshes.length !== 0 && this._indices) {
  34289. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  34290. }
  34291. // Vertex buffers
  34292. for (var key in this._vertexBuffers) {
  34293. var vertexBuffer = this._vertexBuffers[key];
  34294. vertexBuffer._rebuild();
  34295. }
  34296. };
  34297. /**
  34298. * Affects all gemetry data in one call
  34299. * @param vertexData defines the geometry data
  34300. * @param updatable defines if the geometry must be flagged as updatable (false as default)
  34301. */
  34302. Geometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  34303. vertexData.applyToGeometry(this, updatable);
  34304. this.notifyUpdate();
  34305. };
  34306. /**
  34307. * Set specific vertex data
  34308. * @param kind defines the data kind (Position, normal, etc...)
  34309. * @param data defines the vertex data to use
  34310. * @param updatable defines if the vertex must be flagged as updatable (false as default)
  34311. * @param stride defines the stride to use (0 by default). This value is deduced from the kind value if not specified
  34312. */
  34313. Geometry.prototype.setVerticesData = function (kind, data, updatable, stride) {
  34314. if (updatable === void 0) { updatable = false; }
  34315. var buffer = new BABYLON.VertexBuffer(this._engine, data, kind, updatable, this._meshes.length === 0, stride);
  34316. this.setVerticesBuffer(buffer);
  34317. };
  34318. /**
  34319. * Removes a specific vertex data
  34320. * @param kind defines the data kind (Position, normal, etc...)
  34321. */
  34322. Geometry.prototype.removeVerticesData = function (kind) {
  34323. if (this._vertexBuffers[kind]) {
  34324. this._vertexBuffers[kind].dispose();
  34325. delete this._vertexBuffers[kind];
  34326. }
  34327. };
  34328. /**
  34329. * Affect a vertex buffer to the geometry. the vertexBuffer.getKind() function is used to determine where to store the data
  34330. * @param buffer defines the vertex buffer to use
  34331. */
  34332. Geometry.prototype.setVerticesBuffer = function (buffer) {
  34333. var kind = buffer.getKind();
  34334. if (this._vertexBuffers[kind]) {
  34335. this._vertexBuffers[kind].dispose();
  34336. }
  34337. this._vertexBuffers[kind] = buffer;
  34338. if (kind === BABYLON.VertexBuffer.PositionKind) {
  34339. var data = buffer.getData();
  34340. var stride = buffer.getStrideSize();
  34341. this._totalVertices = data.length / stride;
  34342. this.updateExtend(data, stride);
  34343. this._resetPointsArrayCache();
  34344. var meshes = this._meshes;
  34345. var numOfMeshes = meshes.length;
  34346. for (var index = 0; index < numOfMeshes; index++) {
  34347. var mesh = meshes[index];
  34348. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  34349. mesh._createGlobalSubMesh(false);
  34350. mesh.computeWorldMatrix(true);
  34351. }
  34352. }
  34353. this.notifyUpdate(kind);
  34354. if (this._vertexArrayObjects) {
  34355. this._disposeVertexArrayObjects();
  34356. this._vertexArrayObjects = {}; // Will trigger a rebuild of the VAO if supported
  34357. }
  34358. };
  34359. /**
  34360. * Update a specific vertex buffer
  34361. * This function will directly update the underlying WebGLBuffer according to the passed numeric array or Float32Array
  34362. * It will do nothing if the buffer is not updatable
  34363. * @param kind defines the data kind (Position, normal, etc...)
  34364. * @param data defines the data to use
  34365. * @param offset defines the offset in the target buffer where to store the data
  34366. */
  34367. Geometry.prototype.updateVerticesDataDirectly = function (kind, data, offset) {
  34368. var vertexBuffer = this.getVertexBuffer(kind);
  34369. if (!vertexBuffer) {
  34370. return;
  34371. }
  34372. vertexBuffer.updateDirectly(data, offset);
  34373. this.notifyUpdate(kind);
  34374. };
  34375. /**
  34376. * Update a specific vertex buffer
  34377. * This function will create a new buffer if the current one is not updatable
  34378. * @param kind defines the data kind (Position, normal, etc...)
  34379. * @param data defines the data to use
  34380. * @param updateExtends defines if the geometry extends must be recomputed (false by default)
  34381. */
  34382. Geometry.prototype.updateVerticesData = function (kind, data, updateExtends) {
  34383. if (updateExtends === void 0) { updateExtends = false; }
  34384. var vertexBuffer = this.getVertexBuffer(kind);
  34385. if (!vertexBuffer) {
  34386. return;
  34387. }
  34388. vertexBuffer.update(data);
  34389. if (kind === BABYLON.VertexBuffer.PositionKind) {
  34390. var stride = vertexBuffer.getStrideSize();
  34391. this._totalVertices = data.length / stride;
  34392. this.updateBoundingInfo(updateExtends, data);
  34393. }
  34394. this.notifyUpdate(kind);
  34395. };
  34396. Geometry.prototype.updateBoundingInfo = function (updateExtends, data) {
  34397. if (updateExtends) {
  34398. this.updateExtend(data);
  34399. }
  34400. var meshes = this._meshes;
  34401. var numOfMeshes = meshes.length;
  34402. this._resetPointsArrayCache();
  34403. for (var index = 0; index < numOfMeshes; index++) {
  34404. var mesh = meshes[index];
  34405. if (updateExtends) {
  34406. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  34407. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  34408. var subMesh = mesh.subMeshes[subIndex];
  34409. subMesh.refreshBoundingInfo();
  34410. }
  34411. }
  34412. }
  34413. };
  34414. /** @ignore */
  34415. Geometry.prototype._bind = function (effect, indexToBind) {
  34416. if (!effect) {
  34417. return;
  34418. }
  34419. if (indexToBind === undefined) {
  34420. indexToBind = this._indexBuffer;
  34421. }
  34422. var vbs = this.getVertexBuffers();
  34423. if (!vbs) {
  34424. return;
  34425. }
  34426. if (indexToBind != this._indexBuffer || !this._vertexArrayObjects) {
  34427. this._engine.bindBuffers(vbs, indexToBind, effect);
  34428. return;
  34429. }
  34430. // Using VAO
  34431. if (!this._vertexArrayObjects[effect.key]) {
  34432. this._vertexArrayObjects[effect.key] = this._engine.recordVertexArrayObject(vbs, indexToBind, effect);
  34433. }
  34434. this._engine.bindVertexArrayObject(this._vertexArrayObjects[effect.key], indexToBind);
  34435. };
  34436. /**
  34437. * Gets total number of vertices
  34438. * @returns the total number of vertices
  34439. */
  34440. Geometry.prototype.getTotalVertices = function () {
  34441. if (!this.isReady()) {
  34442. return 0;
  34443. }
  34444. return this._totalVertices;
  34445. };
  34446. /**
  34447. * Gets a specific vertex data attached to this geometry
  34448. * @param kind defines the data kind (Position, normal, etc...)
  34449. * @param copyWhenShared defines if the returned array must be cloned upon returning it if the current geometry is shared between multiple meshes
  34450. * @param forceCopy defines a boolean indicating that the returned array must be cloned upon returning it
  34451. * @returns a float array containing vertex data
  34452. */
  34453. Geometry.prototype.getVerticesData = function (kind, copyWhenShared, forceCopy) {
  34454. var vertexBuffer = this.getVertexBuffer(kind);
  34455. if (!vertexBuffer) {
  34456. return null;
  34457. }
  34458. var orig = vertexBuffer.getData();
  34459. if (!forceCopy && (!copyWhenShared || this._meshes.length === 1)) {
  34460. return orig;
  34461. }
  34462. else {
  34463. var len = orig.length;
  34464. var copy = [];
  34465. for (var i = 0; i < len; i++) {
  34466. copy.push(orig[i]);
  34467. }
  34468. return copy;
  34469. }
  34470. };
  34471. /**
  34472. * Returns a boolean defining if the vertex data for the requested `kind` is updatable
  34473. * @param kind defines the data kind (Position, normal, etc...)
  34474. * @returns true if the vertex buffer with the specified kind is updatable
  34475. */
  34476. Geometry.prototype.isVertexBufferUpdatable = function (kind) {
  34477. var vb = this._vertexBuffers[kind];
  34478. if (!vb) {
  34479. return false;
  34480. }
  34481. return vb.isUpdatable();
  34482. };
  34483. /**
  34484. * Gets a specific vertex buffer
  34485. * @param kind defines the data kind (Position, normal, etc...)
  34486. * @returns a {BABYLON.VertexBuffer}
  34487. */
  34488. Geometry.prototype.getVertexBuffer = function (kind) {
  34489. if (!this.isReady()) {
  34490. return null;
  34491. }
  34492. return this._vertexBuffers[kind];
  34493. };
  34494. /**
  34495. * Returns all vertex buffers
  34496. * @return an object holding all vertex buffers indexed by kind
  34497. */
  34498. Geometry.prototype.getVertexBuffers = function () {
  34499. if (!this.isReady()) {
  34500. return null;
  34501. }
  34502. return this._vertexBuffers;
  34503. };
  34504. /**
  34505. * Gets a boolean indicating if specific vertex buffer is present
  34506. * @param kind defines the data kind (Position, normal, etc...)
  34507. * @returns true if data is present
  34508. */
  34509. Geometry.prototype.isVerticesDataPresent = function (kind) {
  34510. if (!this._vertexBuffers) {
  34511. if (this._delayInfo) {
  34512. return this._delayInfo.indexOf(kind) !== -1;
  34513. }
  34514. return false;
  34515. }
  34516. return this._vertexBuffers[kind] !== undefined;
  34517. };
  34518. /**
  34519. * Gets a list of all attached data kinds (Position, normal, etc...)
  34520. * @returns a list of string containing all kinds
  34521. */
  34522. Geometry.prototype.getVerticesDataKinds = function () {
  34523. var result = [];
  34524. var kind;
  34525. if (!this._vertexBuffers && this._delayInfo) {
  34526. for (kind in this._delayInfo) {
  34527. result.push(kind);
  34528. }
  34529. }
  34530. else {
  34531. for (kind in this._vertexBuffers) {
  34532. result.push(kind);
  34533. }
  34534. }
  34535. return result;
  34536. };
  34537. /**
  34538. * Update index buffer
  34539. * @param indices defines the indices to store in the index buffer
  34540. * @param offset defines the offset in the target buffer where to store the data
  34541. */
  34542. Geometry.prototype.updateIndices = function (indices, offset) {
  34543. if (!this._indexBuffer) {
  34544. return;
  34545. }
  34546. if (!this._indexBufferIsUpdatable) {
  34547. this.setIndices(indices, null, true);
  34548. }
  34549. else {
  34550. this._engine.updateDynamicIndexBuffer(this._indexBuffer, indices, offset);
  34551. }
  34552. };
  34553. /**
  34554. * Creates a new index buffer
  34555. * @param indices defines the indices to store in the index buffer
  34556. * @param totalVertices defines the total number of vertices (could be null)
  34557. * @param updatable defines if the index buffer must be flagged as updatable (false by default)
  34558. */
  34559. Geometry.prototype.setIndices = function (indices, totalVertices, updatable) {
  34560. if (totalVertices === void 0) { totalVertices = null; }
  34561. if (updatable === void 0) { updatable = false; }
  34562. if (this._indexBuffer) {
  34563. this._engine._releaseBuffer(this._indexBuffer);
  34564. }
  34565. this._disposeVertexArrayObjects();
  34566. this._indices = indices;
  34567. this._indexBufferIsUpdatable = updatable;
  34568. if (this._meshes.length !== 0 && this._indices) {
  34569. this._indexBuffer = this._engine.createIndexBuffer(this._indices, updatable);
  34570. }
  34571. if (totalVertices != undefined) {
  34572. this._totalVertices = totalVertices;
  34573. }
  34574. var meshes = this._meshes;
  34575. var numOfMeshes = meshes.length;
  34576. for (var index = 0; index < numOfMeshes; index++) {
  34577. meshes[index]._createGlobalSubMesh(true);
  34578. }
  34579. this.notifyUpdate();
  34580. };
  34581. /**
  34582. * Return the total number of indices
  34583. * @returns the total number of indices
  34584. */
  34585. Geometry.prototype.getTotalIndices = function () {
  34586. if (!this.isReady()) {
  34587. return 0;
  34588. }
  34589. return this._indices.length;
  34590. };
  34591. /**
  34592. * Gets the index buffer array
  34593. * @param copyWhenShared defines if the returned array must be cloned upon returning it if the current geometry is shared between multiple meshes
  34594. * @returns the index buffer array
  34595. */
  34596. Geometry.prototype.getIndices = function (copyWhenShared) {
  34597. if (!this.isReady()) {
  34598. return null;
  34599. }
  34600. var orig = this._indices;
  34601. if (!copyWhenShared || this._meshes.length === 1) {
  34602. return orig;
  34603. }
  34604. else {
  34605. var len = orig.length;
  34606. var copy = [];
  34607. for (var i = 0; i < len; i++) {
  34608. copy.push(orig[i]);
  34609. }
  34610. return copy;
  34611. }
  34612. };
  34613. /**
  34614. * Gets the index buffer
  34615. * @return the index buffer
  34616. */
  34617. Geometry.prototype.getIndexBuffer = function () {
  34618. if (!this.isReady()) {
  34619. return null;
  34620. }
  34621. return this._indexBuffer;
  34622. };
  34623. /** @ignore */
  34624. Geometry.prototype._releaseVertexArrayObject = function (effect) {
  34625. if (effect === void 0) { effect = null; }
  34626. if (!effect || !this._vertexArrayObjects) {
  34627. return;
  34628. }
  34629. if (this._vertexArrayObjects[effect.key]) {
  34630. this._engine.releaseVertexArrayObject(this._vertexArrayObjects[effect.key]);
  34631. delete this._vertexArrayObjects[effect.key];
  34632. }
  34633. };
  34634. /**
  34635. * Release the associated resources for a specific mesh
  34636. * @param mesh defines the source mesh
  34637. * @param shouldDispose defines if the geometry must be disposed if there is no more mesh pointing to it
  34638. */
  34639. Geometry.prototype.releaseForMesh = function (mesh, shouldDispose) {
  34640. var meshes = this._meshes;
  34641. var index = meshes.indexOf(mesh);
  34642. if (index === -1) {
  34643. return;
  34644. }
  34645. meshes.splice(index, 1);
  34646. mesh._geometry = null;
  34647. if (meshes.length === 0 && shouldDispose) {
  34648. this.dispose();
  34649. }
  34650. };
  34651. /**
  34652. * Apply current geometry to a given mesh
  34653. * @param mesh defines the mesh to apply geometry to
  34654. */
  34655. Geometry.prototype.applyToMesh = function (mesh) {
  34656. if (mesh._geometry === this) {
  34657. return;
  34658. }
  34659. var previousGeometry = mesh._geometry;
  34660. if (previousGeometry) {
  34661. previousGeometry.releaseForMesh(mesh);
  34662. }
  34663. var meshes = this._meshes;
  34664. // must be done before setting vertexBuffers because of mesh._createGlobalSubMesh()
  34665. mesh._geometry = this;
  34666. this._scene.pushGeometry(this);
  34667. meshes.push(mesh);
  34668. if (this.isReady()) {
  34669. this._applyToMesh(mesh);
  34670. }
  34671. else {
  34672. mesh._boundingInfo = this._boundingInfo;
  34673. }
  34674. };
  34675. Geometry.prototype.updateExtend = function (data, stride) {
  34676. if (data === void 0) { data = null; }
  34677. if (!data) {
  34678. data = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind].getData();
  34679. }
  34680. this._extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._totalVertices, this.boundingBias, stride);
  34681. };
  34682. Geometry.prototype._applyToMesh = function (mesh) {
  34683. var numOfMeshes = this._meshes.length;
  34684. // vertexBuffers
  34685. for (var kind in this._vertexBuffers) {
  34686. if (numOfMeshes === 1) {
  34687. this._vertexBuffers[kind].create();
  34688. }
  34689. var buffer = this._vertexBuffers[kind].getBuffer();
  34690. if (buffer)
  34691. buffer.references = numOfMeshes;
  34692. if (kind === BABYLON.VertexBuffer.PositionKind) {
  34693. if (!this._extend) {
  34694. this.updateExtend(this._vertexBuffers[kind].getData());
  34695. }
  34696. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  34697. mesh._createGlobalSubMesh(false);
  34698. //bounding info was just created again, world matrix should be applied again.
  34699. mesh._updateBoundingInfo();
  34700. }
  34701. }
  34702. // indexBuffer
  34703. if (numOfMeshes === 1 && this._indices && this._indices.length > 0) {
  34704. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  34705. }
  34706. if (this._indexBuffer) {
  34707. this._indexBuffer.references = numOfMeshes;
  34708. }
  34709. };
  34710. Geometry.prototype.notifyUpdate = function (kind) {
  34711. if (this.onGeometryUpdated) {
  34712. this.onGeometryUpdated(this, kind);
  34713. }
  34714. for (var _i = 0, _a = this._meshes; _i < _a.length; _i++) {
  34715. var mesh = _a[_i];
  34716. mesh._markSubMeshesAsAttributesDirty();
  34717. }
  34718. };
  34719. /**
  34720. * Load the geometry if it was flagged as delay loaded
  34721. * @param scene defines the hosting scene
  34722. * @param onLoaded defines a callback called when the geometry is loaded
  34723. */
  34724. Geometry.prototype.load = function (scene, onLoaded) {
  34725. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  34726. return;
  34727. }
  34728. if (this.isReady()) {
  34729. if (onLoaded) {
  34730. onLoaded();
  34731. }
  34732. return;
  34733. }
  34734. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  34735. this._queueLoad(scene, onLoaded);
  34736. };
  34737. Geometry.prototype._queueLoad = function (scene, onLoaded) {
  34738. var _this = this;
  34739. if (!this.delayLoadingFile) {
  34740. return;
  34741. }
  34742. scene._addPendingData(this);
  34743. scene._loadFile(this.delayLoadingFile, function (data) {
  34744. if (!_this._delayLoadingFunction) {
  34745. return;
  34746. }
  34747. _this._delayLoadingFunction(JSON.parse(data), _this);
  34748. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  34749. _this._delayInfo = [];
  34750. scene._removePendingData(_this);
  34751. var meshes = _this._meshes;
  34752. var numOfMeshes = meshes.length;
  34753. for (var index = 0; index < numOfMeshes; index++) {
  34754. _this._applyToMesh(meshes[index]);
  34755. }
  34756. if (onLoaded) {
  34757. onLoaded();
  34758. }
  34759. }, undefined, true);
  34760. };
  34761. /**
  34762. * Invert the geometry to move from a right handed system to a left handed one.
  34763. */
  34764. Geometry.prototype.toLeftHanded = function () {
  34765. // Flip faces
  34766. var tIndices = this.getIndices(false);
  34767. if (tIndices != null && tIndices.length > 0) {
  34768. for (var i = 0; i < tIndices.length; i += 3) {
  34769. var tTemp = tIndices[i + 0];
  34770. tIndices[i + 0] = tIndices[i + 2];
  34771. tIndices[i + 2] = tTemp;
  34772. }
  34773. this.setIndices(tIndices);
  34774. }
  34775. // Negate position.z
  34776. var tPositions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind, false);
  34777. if (tPositions != null && tPositions.length > 0) {
  34778. for (var i = 0; i < tPositions.length; i += 3) {
  34779. tPositions[i + 2] = -tPositions[i + 2];
  34780. }
  34781. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, tPositions, false);
  34782. }
  34783. // Negate normal.z
  34784. var tNormals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind, false);
  34785. if (tNormals != null && tNormals.length > 0) {
  34786. for (var i = 0; i < tNormals.length; i += 3) {
  34787. tNormals[i + 2] = -tNormals[i + 2];
  34788. }
  34789. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, tNormals, false);
  34790. }
  34791. };
  34792. // Cache
  34793. /** @ignore */
  34794. Geometry.prototype._resetPointsArrayCache = function () {
  34795. this._positions = null;
  34796. };
  34797. /** @ignore */
  34798. Geometry.prototype._generatePointsArray = function () {
  34799. if (this._positions)
  34800. return true;
  34801. this._positions = [];
  34802. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  34803. if (!data) {
  34804. return false;
  34805. }
  34806. for (var index = 0; index < data.length; index += 3) {
  34807. this._positions.push(BABYLON.Vector3.FromArray(data, index));
  34808. }
  34809. return true;
  34810. };
  34811. /**
  34812. * Gets a value indicating if the geometry is disposed
  34813. * @returns true if the geometry was disposed
  34814. */
  34815. Geometry.prototype.isDisposed = function () {
  34816. return this._isDisposed;
  34817. };
  34818. Geometry.prototype._disposeVertexArrayObjects = function () {
  34819. if (this._vertexArrayObjects) {
  34820. for (var kind in this._vertexArrayObjects) {
  34821. this._engine.releaseVertexArrayObject(this._vertexArrayObjects[kind]);
  34822. }
  34823. this._vertexArrayObjects = {};
  34824. }
  34825. };
  34826. /**
  34827. * Free all associated resources
  34828. */
  34829. Geometry.prototype.dispose = function () {
  34830. var meshes = this._meshes;
  34831. var numOfMeshes = meshes.length;
  34832. var index;
  34833. for (index = 0; index < numOfMeshes; index++) {
  34834. this.releaseForMesh(meshes[index]);
  34835. }
  34836. this._meshes = [];
  34837. this._disposeVertexArrayObjects();
  34838. for (var kind in this._vertexBuffers) {
  34839. this._vertexBuffers[kind].dispose();
  34840. }
  34841. this._vertexBuffers = {};
  34842. this._totalVertices = 0;
  34843. if (this._indexBuffer) {
  34844. this._engine._releaseBuffer(this._indexBuffer);
  34845. }
  34846. this._indexBuffer = null;
  34847. this._indices = [];
  34848. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  34849. this.delayLoadingFile = null;
  34850. this._delayLoadingFunction = null;
  34851. this._delayInfo = [];
  34852. this._boundingInfo = null;
  34853. this._scene.removeGeometry(this);
  34854. this._isDisposed = true;
  34855. };
  34856. /**
  34857. * Clone the current geometry into a new geometry
  34858. * @param id defines the unique ID of the new geometry
  34859. * @returns a new geometry object
  34860. */
  34861. Geometry.prototype.copy = function (id) {
  34862. var vertexData = new BABYLON.VertexData();
  34863. vertexData.indices = [];
  34864. var indices = this.getIndices();
  34865. if (indices) {
  34866. for (var index = 0; index < indices.length; index++) {
  34867. vertexData.indices.push(indices[index]);
  34868. }
  34869. }
  34870. var updatable = false;
  34871. var stopChecking = false;
  34872. var kind;
  34873. for (kind in this._vertexBuffers) {
  34874. // using slice() to make a copy of the array and not just reference it
  34875. var data = this.getVerticesData(kind);
  34876. if (data instanceof Float32Array) {
  34877. vertexData.set(new Float32Array(data), kind);
  34878. }
  34879. else {
  34880. vertexData.set(data.slice(0), kind);
  34881. }
  34882. if (!stopChecking) {
  34883. var vb = this.getVertexBuffer(kind);
  34884. if (vb) {
  34885. updatable = vb.isUpdatable();
  34886. stopChecking = !updatable;
  34887. }
  34888. }
  34889. }
  34890. var geometry = new Geometry(id, this._scene, vertexData, updatable);
  34891. geometry.delayLoadState = this.delayLoadState;
  34892. geometry.delayLoadingFile = this.delayLoadingFile;
  34893. geometry._delayLoadingFunction = this._delayLoadingFunction;
  34894. for (kind in this._delayInfo) {
  34895. geometry._delayInfo = geometry._delayInfo || [];
  34896. geometry._delayInfo.push(kind);
  34897. }
  34898. // Bounding info
  34899. geometry._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  34900. return geometry;
  34901. };
  34902. /**
  34903. * Serialize the current geometry info (and not the vertices data) into a JSON object
  34904. * @return a JSON representation of the current geometry data (without the vertices data)
  34905. */
  34906. Geometry.prototype.serialize = function () {
  34907. var serializationObject = {};
  34908. serializationObject.id = this.id;
  34909. serializationObject.updatable = this._updatable;
  34910. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  34911. serializationObject.tags = BABYLON.Tags.GetTags(this);
  34912. }
  34913. return serializationObject;
  34914. };
  34915. Geometry.prototype.toNumberArray = function (origin) {
  34916. if (Array.isArray(origin)) {
  34917. return origin;
  34918. }
  34919. else {
  34920. return Array.prototype.slice.call(origin);
  34921. }
  34922. };
  34923. /**
  34924. * Serialize all vertices data into a JSON oject
  34925. * @returns a JSON representation of the current geometry data
  34926. */
  34927. Geometry.prototype.serializeVerticeData = function () {
  34928. var serializationObject = this.serialize();
  34929. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  34930. serializationObject.positions = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  34931. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.PositionKind)) {
  34932. serializationObject.positions._updatable = true;
  34933. }
  34934. }
  34935. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  34936. serializationObject.normals = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.NormalKind));
  34937. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.NormalKind)) {
  34938. serializationObject.normals._updatable = true;
  34939. }
  34940. }
  34941. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  34942. serializationObject.tangets = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.TangentKind));
  34943. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.TangentKind)) {
  34944. serializationObject.tangets._updatable = true;
  34945. }
  34946. }
  34947. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  34948. serializationObject.uvs = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UVKind));
  34949. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UVKind)) {
  34950. serializationObject.uvs._updatable = true;
  34951. }
  34952. }
  34953. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  34954. serializationObject.uv2s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV2Kind));
  34955. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV2Kind)) {
  34956. serializationObject.uv2s._updatable = true;
  34957. }
  34958. }
  34959. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  34960. serializationObject.uv3s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV3Kind));
  34961. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV3Kind)) {
  34962. serializationObject.uv3s._updatable = true;
  34963. }
  34964. }
  34965. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  34966. serializationObject.uv4s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV4Kind));
  34967. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV4Kind)) {
  34968. serializationObject.uv4s._updatable = true;
  34969. }
  34970. }
  34971. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  34972. serializationObject.uv5s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV5Kind));
  34973. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV5Kind)) {
  34974. serializationObject.uv5s._updatable = true;
  34975. }
  34976. }
  34977. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  34978. serializationObject.uv6s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV6Kind));
  34979. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV6Kind)) {
  34980. serializationObject.uv6s._updatable = true;
  34981. }
  34982. }
  34983. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  34984. serializationObject.colors = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.ColorKind));
  34985. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.ColorKind)) {
  34986. serializationObject.colors._updatable = true;
  34987. }
  34988. }
  34989. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  34990. serializationObject.matricesIndices = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind));
  34991. serializationObject.matricesIndices._isExpanded = true;
  34992. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  34993. serializationObject.matricesIndices._updatable = true;
  34994. }
  34995. }
  34996. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  34997. serializationObject.matricesWeights = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind));
  34998. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  34999. serializationObject.matricesWeights._updatable = true;
  35000. }
  35001. }
  35002. serializationObject.indices = this.toNumberArray(this.getIndices());
  35003. return serializationObject;
  35004. };
  35005. // Statics
  35006. /**
  35007. * Extracts a clone of a mesh geometry
  35008. * @param mesh defines the source mesh
  35009. * @param id defines the unique ID of the new geometry object
  35010. * @returns the new geometry object
  35011. */
  35012. Geometry.ExtractFromMesh = function (mesh, id) {
  35013. var geometry = mesh._geometry;
  35014. if (!geometry) {
  35015. return null;
  35016. }
  35017. return geometry.copy(id);
  35018. };
  35019. /**
  35020. * You should now use Tools.RandomId(), this method is still here for legacy reasons.
  35021. * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  35022. * Be aware Math.random() could cause collisions, but:
  35023. * "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"
  35024. * @returns a string containing a new GUID
  35025. */
  35026. Geometry.RandomId = function () {
  35027. return BABYLON.Tools.RandomId();
  35028. };
  35029. /** @ignore */
  35030. Geometry._ImportGeometry = function (parsedGeometry, mesh) {
  35031. var scene = mesh.getScene();
  35032. // Geometry
  35033. var geometryId = parsedGeometry.geometryId;
  35034. if (geometryId) {
  35035. var geometry = scene.getGeometryByID(geometryId);
  35036. if (geometry) {
  35037. geometry.applyToMesh(mesh);
  35038. }
  35039. }
  35040. else if (parsedGeometry instanceof ArrayBuffer) {
  35041. var binaryInfo = mesh._binaryInfo;
  35042. if (binaryInfo.positionsAttrDesc && binaryInfo.positionsAttrDesc.count > 0) {
  35043. var positionsData = new Float32Array(parsedGeometry, binaryInfo.positionsAttrDesc.offset, binaryInfo.positionsAttrDesc.count);
  35044. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData, false);
  35045. }
  35046. if (binaryInfo.normalsAttrDesc && binaryInfo.normalsAttrDesc.count > 0) {
  35047. var normalsData = new Float32Array(parsedGeometry, binaryInfo.normalsAttrDesc.offset, binaryInfo.normalsAttrDesc.count);
  35048. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData, false);
  35049. }
  35050. if (binaryInfo.tangetsAttrDesc && binaryInfo.tangetsAttrDesc.count > 0) {
  35051. var tangentsData = new Float32Array(parsedGeometry, binaryInfo.tangetsAttrDesc.offset, binaryInfo.tangetsAttrDesc.count);
  35052. mesh.setVerticesData(BABYLON.VertexBuffer.TangentKind, tangentsData, false);
  35053. }
  35054. if (binaryInfo.uvsAttrDesc && binaryInfo.uvsAttrDesc.count > 0) {
  35055. var uvsData = new Float32Array(parsedGeometry, binaryInfo.uvsAttrDesc.offset, binaryInfo.uvsAttrDesc.count);
  35056. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvsData, false);
  35057. }
  35058. if (binaryInfo.uvs2AttrDesc && binaryInfo.uvs2AttrDesc.count > 0) {
  35059. var uvs2Data = new Float32Array(parsedGeometry, binaryInfo.uvs2AttrDesc.offset, binaryInfo.uvs2AttrDesc.count);
  35060. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, uvs2Data, false);
  35061. }
  35062. if (binaryInfo.uvs3AttrDesc && binaryInfo.uvs3AttrDesc.count > 0) {
  35063. var uvs3Data = new Float32Array(parsedGeometry, binaryInfo.uvs3AttrDesc.offset, binaryInfo.uvs3AttrDesc.count);
  35064. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, uvs3Data, false);
  35065. }
  35066. if (binaryInfo.uvs4AttrDesc && binaryInfo.uvs4AttrDesc.count > 0) {
  35067. var uvs4Data = new Float32Array(parsedGeometry, binaryInfo.uvs4AttrDesc.offset, binaryInfo.uvs4AttrDesc.count);
  35068. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, uvs4Data, false);
  35069. }
  35070. if (binaryInfo.uvs5AttrDesc && binaryInfo.uvs5AttrDesc.count > 0) {
  35071. var uvs5Data = new Float32Array(parsedGeometry, binaryInfo.uvs5AttrDesc.offset, binaryInfo.uvs5AttrDesc.count);
  35072. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, uvs5Data, false);
  35073. }
  35074. if (binaryInfo.uvs6AttrDesc && binaryInfo.uvs6AttrDesc.count > 0) {
  35075. var uvs6Data = new Float32Array(parsedGeometry, binaryInfo.uvs6AttrDesc.offset, binaryInfo.uvs6AttrDesc.count);
  35076. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, uvs6Data, false);
  35077. }
  35078. if (binaryInfo.colorsAttrDesc && binaryInfo.colorsAttrDesc.count > 0) {
  35079. var colorsData = new Float32Array(parsedGeometry, binaryInfo.colorsAttrDesc.offset, binaryInfo.colorsAttrDesc.count);
  35080. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, colorsData, false, binaryInfo.colorsAttrDesc.stride);
  35081. }
  35082. if (binaryInfo.matricesIndicesAttrDesc && binaryInfo.matricesIndicesAttrDesc.count > 0) {
  35083. var matricesIndicesData = new Int32Array(parsedGeometry, binaryInfo.matricesIndicesAttrDesc.offset, binaryInfo.matricesIndicesAttrDesc.count);
  35084. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndicesData, false);
  35085. }
  35086. if (binaryInfo.matricesWeightsAttrDesc && binaryInfo.matricesWeightsAttrDesc.count > 0) {
  35087. var matricesWeightsData = new Float32Array(parsedGeometry, binaryInfo.matricesWeightsAttrDesc.offset, binaryInfo.matricesWeightsAttrDesc.count);
  35088. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, matricesWeightsData, false);
  35089. }
  35090. if (binaryInfo.indicesAttrDesc && binaryInfo.indicesAttrDesc.count > 0) {
  35091. var indicesData = new Int32Array(parsedGeometry, binaryInfo.indicesAttrDesc.offset, binaryInfo.indicesAttrDesc.count);
  35092. mesh.setIndices(indicesData, null);
  35093. }
  35094. if (binaryInfo.subMeshesAttrDesc && binaryInfo.subMeshesAttrDesc.count > 0) {
  35095. var subMeshesData = new Int32Array(parsedGeometry, binaryInfo.subMeshesAttrDesc.offset, binaryInfo.subMeshesAttrDesc.count * 5);
  35096. mesh.subMeshes = [];
  35097. for (var i = 0; i < binaryInfo.subMeshesAttrDesc.count; i++) {
  35098. var materialIndex = subMeshesData[(i * 5) + 0];
  35099. var verticesStart = subMeshesData[(i * 5) + 1];
  35100. var verticesCount = subMeshesData[(i * 5) + 2];
  35101. var indexStart = subMeshesData[(i * 5) + 3];
  35102. var indexCount = subMeshesData[(i * 5) + 4];
  35103. BABYLON.SubMesh.AddToMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh);
  35104. }
  35105. }
  35106. }
  35107. else if (parsedGeometry.positions && parsedGeometry.normals && parsedGeometry.indices) {
  35108. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, parsedGeometry.positions, parsedGeometry.positions._updatable);
  35109. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, parsedGeometry.normals, parsedGeometry.normals._updatable);
  35110. if (parsedGeometry.tangents) {
  35111. mesh.setVerticesData(BABYLON.VertexBuffer.TangentKind, parsedGeometry.tangents, parsedGeometry.tangents._updatable);
  35112. }
  35113. if (parsedGeometry.uvs) {
  35114. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, parsedGeometry.uvs, parsedGeometry.uvs._updatable);
  35115. }
  35116. if (parsedGeometry.uvs2) {
  35117. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, parsedGeometry.uvs2, parsedGeometry.uvs2._updatable);
  35118. }
  35119. if (parsedGeometry.uvs3) {
  35120. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, parsedGeometry.uvs3, parsedGeometry.uvs3._updatable);
  35121. }
  35122. if (parsedGeometry.uvs4) {
  35123. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, parsedGeometry.uvs4, parsedGeometry.uvs4._updatable);
  35124. }
  35125. if (parsedGeometry.uvs5) {
  35126. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, parsedGeometry.uvs5, parsedGeometry.uvs5._updatable);
  35127. }
  35128. if (parsedGeometry.uvs6) {
  35129. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, parsedGeometry.uvs6, parsedGeometry.uvs6._updatable);
  35130. }
  35131. if (parsedGeometry.colors) {
  35132. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, BABYLON.Color4.CheckColors4(parsedGeometry.colors, parsedGeometry.positions.length / 3), parsedGeometry.colors._updatable);
  35133. }
  35134. if (parsedGeometry.matricesIndices) {
  35135. if (!parsedGeometry.matricesIndices._isExpanded) {
  35136. var floatIndices = [];
  35137. for (var i = 0; i < parsedGeometry.matricesIndices.length; i++) {
  35138. var matricesIndex = parsedGeometry.matricesIndices[i];
  35139. floatIndices.push(matricesIndex & 0x000000FF);
  35140. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  35141. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  35142. floatIndices.push(matricesIndex >> 24);
  35143. }
  35144. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, floatIndices, parsedGeometry.matricesIndices._updatable);
  35145. }
  35146. else {
  35147. delete parsedGeometry.matricesIndices._isExpanded;
  35148. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, parsedGeometry.matricesIndices, parsedGeometry.matricesIndices._updatable);
  35149. }
  35150. }
  35151. if (parsedGeometry.matricesIndicesExtra) {
  35152. if (!parsedGeometry.matricesIndicesExtra._isExpanded) {
  35153. var floatIndices = [];
  35154. for (var i = 0; i < parsedGeometry.matricesIndicesExtra.length; i++) {
  35155. var matricesIndex = parsedGeometry.matricesIndicesExtra[i];
  35156. floatIndices.push(matricesIndex & 0x000000FF);
  35157. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  35158. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  35159. floatIndices.push(matricesIndex >> 24);
  35160. }
  35161. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, floatIndices, parsedGeometry.matricesIndicesExtra._updatable);
  35162. }
  35163. else {
  35164. delete parsedGeometry.matricesIndices._isExpanded;
  35165. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, parsedGeometry.matricesIndicesExtra, parsedGeometry.matricesIndicesExtra._updatable);
  35166. }
  35167. }
  35168. if (parsedGeometry.matricesWeights) {
  35169. Geometry._CleanMatricesWeights(parsedGeometry, mesh);
  35170. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, parsedGeometry.matricesWeights, parsedGeometry.matricesWeights._updatable);
  35171. }
  35172. if (parsedGeometry.matricesWeightsExtra) {
  35173. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, parsedGeometry.matricesWeightsExtra, parsedGeometry.matricesWeights._updatable);
  35174. }
  35175. mesh.setIndices(parsedGeometry.indices, null);
  35176. }
  35177. // SubMeshes
  35178. if (parsedGeometry.subMeshes) {
  35179. mesh.subMeshes = [];
  35180. for (var subIndex = 0; subIndex < parsedGeometry.subMeshes.length; subIndex++) {
  35181. var parsedSubMesh = parsedGeometry.subMeshes[subIndex];
  35182. BABYLON.SubMesh.AddToMesh(parsedSubMesh.materialIndex, parsedSubMesh.verticesStart, parsedSubMesh.verticesCount, parsedSubMesh.indexStart, parsedSubMesh.indexCount, mesh);
  35183. }
  35184. }
  35185. // Flat shading
  35186. if (mesh._shouldGenerateFlatShading) {
  35187. mesh.convertToFlatShadedMesh();
  35188. delete mesh._shouldGenerateFlatShading;
  35189. }
  35190. // Update
  35191. mesh.computeWorldMatrix(true);
  35192. // Octree
  35193. var sceneOctree = scene.selectionOctree;
  35194. if (sceneOctree !== undefined && sceneOctree !== null) {
  35195. sceneOctree.addMesh(mesh);
  35196. }
  35197. };
  35198. Geometry._CleanMatricesWeights = function (parsedGeometry, mesh) {
  35199. var epsilon = 1e-3;
  35200. if (!BABYLON.SceneLoader.CleanBoneMatrixWeights) {
  35201. return;
  35202. }
  35203. var noInfluenceBoneIndex = 0.0;
  35204. if (parsedGeometry.skeletonId > -1) {
  35205. var skeleton = mesh.getScene().getLastSkeletonByID(parsedGeometry.skeletonId);
  35206. if (!skeleton) {
  35207. return;
  35208. }
  35209. noInfluenceBoneIndex = skeleton.bones.length;
  35210. }
  35211. else {
  35212. return;
  35213. }
  35214. var matricesIndices = mesh.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  35215. var matricesIndicesExtra = mesh.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  35216. var matricesWeights = parsedGeometry.matricesWeights;
  35217. var matricesWeightsExtra = parsedGeometry.matricesWeightsExtra;
  35218. var influencers = parsedGeometry.numBoneInfluencer;
  35219. var size = matricesWeights.length;
  35220. for (var i = 0; i < size; i += 4) {
  35221. var weight = 0.0;
  35222. var firstZeroWeight = -1;
  35223. for (var j = 0; j < 4; j++) {
  35224. var w = matricesWeights[i + j];
  35225. weight += w;
  35226. if (w < epsilon && firstZeroWeight < 0) {
  35227. firstZeroWeight = j;
  35228. }
  35229. }
  35230. if (matricesWeightsExtra) {
  35231. for (var j = 0; j < 4; j++) {
  35232. var w = matricesWeightsExtra[i + j];
  35233. weight += w;
  35234. if (w < epsilon && firstZeroWeight < 0) {
  35235. firstZeroWeight = j + 4;
  35236. }
  35237. }
  35238. }
  35239. if (firstZeroWeight < 0 || firstZeroWeight > (influencers - 1)) {
  35240. firstZeroWeight = influencers - 1;
  35241. }
  35242. if (weight > epsilon) {
  35243. var mweight = 1.0 / weight;
  35244. for (var j = 0; j < 4; j++) {
  35245. matricesWeights[i + j] *= mweight;
  35246. }
  35247. if (matricesWeightsExtra) {
  35248. for (var j = 0; j < 4; j++) {
  35249. matricesWeightsExtra[i + j] *= mweight;
  35250. }
  35251. }
  35252. }
  35253. else {
  35254. if (firstZeroWeight >= 4) {
  35255. matricesWeightsExtra[i + firstZeroWeight - 4] = 1.0 - weight;
  35256. matricesIndicesExtra[i + firstZeroWeight - 4] = noInfluenceBoneIndex;
  35257. }
  35258. else {
  35259. matricesWeights[i + firstZeroWeight] = 1.0 - weight;
  35260. matricesIndices[i + firstZeroWeight] = noInfluenceBoneIndex;
  35261. }
  35262. }
  35263. }
  35264. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndices);
  35265. if (parsedGeometry.matricesWeightsExtra) {
  35266. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, matricesIndicesExtra);
  35267. }
  35268. };
  35269. /**
  35270. * Create a new geometry from persisted data (Using .babylon file format)
  35271. * @param parsedVertexData defines the persisted data
  35272. * @param scene defines the hosting scene
  35273. * @param rootUrl defines the root url to use to load assets (like delayed data)
  35274. * @returns the new geometry object
  35275. */
  35276. Geometry.Parse = function (parsedVertexData, scene, rootUrl) {
  35277. if (scene.getGeometryByID(parsedVertexData.id)) {
  35278. return null; // null since geometry could be something else than a box...
  35279. }
  35280. var geometry = new Geometry(parsedVertexData.id, scene, undefined, parsedVertexData.updatable);
  35281. if (BABYLON.Tags) {
  35282. BABYLON.Tags.AddTagsTo(geometry, parsedVertexData.tags);
  35283. }
  35284. if (parsedVertexData.delayLoadingFile) {
  35285. geometry.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  35286. geometry.delayLoadingFile = rootUrl + parsedVertexData.delayLoadingFile;
  35287. geometry._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMaximum));
  35288. geometry._delayInfo = [];
  35289. if (parsedVertexData.hasUVs) {
  35290. geometry._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  35291. }
  35292. if (parsedVertexData.hasUVs2) {
  35293. geometry._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  35294. }
  35295. if (parsedVertexData.hasUVs3) {
  35296. geometry._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  35297. }
  35298. if (parsedVertexData.hasUVs4) {
  35299. geometry._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  35300. }
  35301. if (parsedVertexData.hasUVs5) {
  35302. geometry._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  35303. }
  35304. if (parsedVertexData.hasUVs6) {
  35305. geometry._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  35306. }
  35307. if (parsedVertexData.hasColors) {
  35308. geometry._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  35309. }
  35310. if (parsedVertexData.hasMatricesIndices) {
  35311. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  35312. }
  35313. if (parsedVertexData.hasMatricesWeights) {
  35314. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  35315. }
  35316. geometry._delayLoadingFunction = BABYLON.VertexData.ImportVertexData;
  35317. }
  35318. else {
  35319. BABYLON.VertexData.ImportVertexData(parsedVertexData, geometry);
  35320. }
  35321. scene.pushGeometry(geometry, true);
  35322. return geometry;
  35323. };
  35324. return Geometry;
  35325. }());
  35326. BABYLON.Geometry = Geometry;
  35327. // Primitives
  35328. /// Abstract class
  35329. /**
  35330. * Abstract class used to provide common services for all typed geometries
  35331. */
  35332. var _PrimitiveGeometry = /** @class */ (function (_super) {
  35333. __extends(_PrimitiveGeometry, _super);
  35334. /**
  35335. * Creates a new typed geometry
  35336. * @param id defines the unique ID of the geometry
  35337. * @param scene defines the hosting scene
  35338. * @param _canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  35339. * @param mesh defines the hosting mesh (can be null)
  35340. */
  35341. function _PrimitiveGeometry(id, scene, _canBeRegenerated, mesh) {
  35342. if (_canBeRegenerated === void 0) { _canBeRegenerated = false; }
  35343. if (mesh === void 0) { mesh = null; }
  35344. var _this = _super.call(this, id, scene, undefined, false, mesh) || this;
  35345. _this._canBeRegenerated = _canBeRegenerated;
  35346. _this._beingRegenerated = true;
  35347. _this.regenerate();
  35348. _this._beingRegenerated = false;
  35349. return _this;
  35350. }
  35351. /**
  35352. * Gets a value indicating if the geometry supports being regenerated with new parameters (false by default)
  35353. * @returns true if the geometry can be regenerated
  35354. */
  35355. _PrimitiveGeometry.prototype.canBeRegenerated = function () {
  35356. return this._canBeRegenerated;
  35357. };
  35358. /**
  35359. * If the geometry supports regeneration, the function will recreates the geometry with updated parameter values
  35360. */
  35361. _PrimitiveGeometry.prototype.regenerate = function () {
  35362. if (!this._canBeRegenerated) {
  35363. return;
  35364. }
  35365. this._beingRegenerated = true;
  35366. this.setAllVerticesData(this._regenerateVertexData(), false);
  35367. this._beingRegenerated = false;
  35368. };
  35369. /**
  35370. * Clone the geometry
  35371. * @param id defines the unique ID of the new geometry
  35372. * @returns the new geometry
  35373. */
  35374. _PrimitiveGeometry.prototype.asNewGeometry = function (id) {
  35375. return _super.prototype.copy.call(this, id);
  35376. };
  35377. // overrides
  35378. _PrimitiveGeometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  35379. if (!this._beingRegenerated) {
  35380. return;
  35381. }
  35382. _super.prototype.setAllVerticesData.call(this, vertexData, false);
  35383. };
  35384. _PrimitiveGeometry.prototype.setVerticesData = function (kind, data, updatable) {
  35385. if (!this._beingRegenerated) {
  35386. return;
  35387. }
  35388. _super.prototype.setVerticesData.call(this, kind, data, false);
  35389. };
  35390. // to override
  35391. /** @ignore */
  35392. _PrimitiveGeometry.prototype._regenerateVertexData = function () {
  35393. throw new Error("Abstract method");
  35394. };
  35395. _PrimitiveGeometry.prototype.copy = function (id) {
  35396. throw new Error("Must be overriden in sub-classes.");
  35397. };
  35398. _PrimitiveGeometry.prototype.serialize = function () {
  35399. var serializationObject = _super.prototype.serialize.call(this);
  35400. serializationObject.canBeRegenerated = this.canBeRegenerated();
  35401. return serializationObject;
  35402. };
  35403. return _PrimitiveGeometry;
  35404. }(Geometry));
  35405. BABYLON._PrimitiveGeometry = _PrimitiveGeometry;
  35406. /**
  35407. * Creates a ribbon geometry
  35408. * @description See http://doc.babylonjs.com/how_to/ribbon_tutorial, http://doc.babylonjs.com/resources/maths_make_ribbons
  35409. */
  35410. var RibbonGeometry = /** @class */ (function (_super) {
  35411. __extends(RibbonGeometry, _super);
  35412. /**
  35413. * Creates a ribbon geometry
  35414. * @param id defines the unique ID of the geometry
  35415. * @param scene defines the hosting scene
  35416. * @param pathArray defines the array of paths to use
  35417. * @param closeArray defines if the last path and the first path must be joined
  35418. * @param closePath defines if the last and first points of each path in your pathArray must be joined
  35419. * @param offset defines the offset between points
  35420. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  35421. * @param mesh defines the hosting mesh (can be null)
  35422. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  35423. */
  35424. function RibbonGeometry(id, scene,
  35425. /**
  35426. * Defines the array of paths to use
  35427. */
  35428. pathArray,
  35429. /**
  35430. * Defines if the last and first points of each path in your pathArray must be joined
  35431. */
  35432. closeArray,
  35433. /**
  35434. * Defines if the last and first points of each path in your pathArray must be joined
  35435. */
  35436. closePath,
  35437. /**
  35438. * Defines the offset between points
  35439. */
  35440. offset, canBeRegenerated, mesh,
  35441. /**
  35442. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  35443. */
  35444. side) {
  35445. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  35446. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  35447. _this.pathArray = pathArray;
  35448. _this.closeArray = closeArray;
  35449. _this.closePath = closePath;
  35450. _this.offset = offset;
  35451. _this.side = side;
  35452. return _this;
  35453. }
  35454. /** @ignore */
  35455. RibbonGeometry.prototype._regenerateVertexData = function () {
  35456. return BABYLON.VertexData.CreateRibbon({ pathArray: this.pathArray, closeArray: this.closeArray, closePath: this.closePath, offset: this.offset, sideOrientation: this.side });
  35457. };
  35458. RibbonGeometry.prototype.copy = function (id) {
  35459. return new RibbonGeometry(id, this.getScene(), this.pathArray, this.closeArray, this.closePath, this.offset, this.canBeRegenerated(), undefined, this.side);
  35460. };
  35461. return RibbonGeometry;
  35462. }(_PrimitiveGeometry));
  35463. BABYLON.RibbonGeometry = RibbonGeometry;
  35464. /**
  35465. * Creates a box geometry
  35466. * @description see http://doc.babylonjs.com/how_to/set_shapes#box
  35467. */
  35468. var BoxGeometry = /** @class */ (function (_super) {
  35469. __extends(BoxGeometry, _super);
  35470. /**
  35471. * Creates a box geometry
  35472. * @param id defines the unique ID of the geometry
  35473. * @param scene defines the hosting scene
  35474. * @param size defines the zise of the box (width, height and depth are the same)
  35475. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  35476. * @param mesh defines the hosting mesh (can be null)
  35477. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  35478. */
  35479. function BoxGeometry(id, scene,
  35480. /**
  35481. * Defines the zise of the box (width, height and depth are the same)
  35482. */
  35483. size, canBeRegenerated, mesh,
  35484. /**
  35485. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  35486. */
  35487. side) {
  35488. if (mesh === void 0) { mesh = null; }
  35489. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  35490. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  35491. _this.size = size;
  35492. _this.side = side;
  35493. return _this;
  35494. }
  35495. BoxGeometry.prototype._regenerateVertexData = function () {
  35496. return BABYLON.VertexData.CreateBox({ size: this.size, sideOrientation: this.side });
  35497. };
  35498. BoxGeometry.prototype.copy = function (id) {
  35499. return new BoxGeometry(id, this.getScene(), this.size, this.canBeRegenerated(), undefined, this.side);
  35500. };
  35501. BoxGeometry.prototype.serialize = function () {
  35502. var serializationObject = _super.prototype.serialize.call(this);
  35503. serializationObject.size = this.size;
  35504. return serializationObject;
  35505. };
  35506. BoxGeometry.Parse = function (parsedBox, scene) {
  35507. if (scene.getGeometryByID(parsedBox.id)) {
  35508. return null; // null since geometry could be something else than a box...
  35509. }
  35510. var box = new BoxGeometry(parsedBox.id, scene, parsedBox.size, parsedBox.canBeRegenerated, null);
  35511. if (BABYLON.Tags) {
  35512. BABYLON.Tags.AddTagsTo(box, parsedBox.tags);
  35513. }
  35514. scene.pushGeometry(box, true);
  35515. return box;
  35516. };
  35517. return BoxGeometry;
  35518. }(_PrimitiveGeometry));
  35519. BABYLON.BoxGeometry = BoxGeometry;
  35520. /**
  35521. * Creates a sphere geometry
  35522. * @description see http://doc.babylonjs.com/how_to/set_shapes#sphere
  35523. */
  35524. var SphereGeometry = /** @class */ (function (_super) {
  35525. __extends(SphereGeometry, _super);
  35526. /**
  35527. * Create a new sphere geometry
  35528. * @param id defines the unique ID of the geometry
  35529. * @param scene defines the hosting scene
  35530. * @param segments defines the number of segments to use to create the sphere
  35531. * @param diameter defines the diameter of the sphere
  35532. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  35533. * @param mesh defines the hosting mesh (can be null)
  35534. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  35535. */
  35536. function SphereGeometry(id, scene,
  35537. /**
  35538. * Defines the number of segments to use to create the sphere
  35539. */
  35540. segments,
  35541. /**
  35542. * Defines the diameter of the sphere
  35543. */
  35544. diameter, canBeRegenerated, mesh,
  35545. /**
  35546. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  35547. */
  35548. side) {
  35549. if (mesh === void 0) { mesh = null; }
  35550. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  35551. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  35552. _this.segments = segments;
  35553. _this.diameter = diameter;
  35554. _this.side = side;
  35555. return _this;
  35556. }
  35557. SphereGeometry.prototype._regenerateVertexData = function () {
  35558. return BABYLON.VertexData.CreateSphere({ segments: this.segments, diameter: this.diameter, sideOrientation: this.side });
  35559. };
  35560. SphereGeometry.prototype.copy = function (id) {
  35561. return new SphereGeometry(id, this.getScene(), this.segments, this.diameter, this.canBeRegenerated(), null, this.side);
  35562. };
  35563. SphereGeometry.prototype.serialize = function () {
  35564. var serializationObject = _super.prototype.serialize.call(this);
  35565. serializationObject.segments = this.segments;
  35566. serializationObject.diameter = this.diameter;
  35567. return serializationObject;
  35568. };
  35569. SphereGeometry.Parse = function (parsedSphere, scene) {
  35570. if (scene.getGeometryByID(parsedSphere.id)) {
  35571. return null; // null since geometry could be something else than a sphere...
  35572. }
  35573. var sphere = new SphereGeometry(parsedSphere.id, scene, parsedSphere.segments, parsedSphere.diameter, parsedSphere.canBeRegenerated, null);
  35574. if (BABYLON.Tags) {
  35575. BABYLON.Tags.AddTagsTo(sphere, parsedSphere.tags);
  35576. }
  35577. scene.pushGeometry(sphere, true);
  35578. return sphere;
  35579. };
  35580. return SphereGeometry;
  35581. }(_PrimitiveGeometry));
  35582. BABYLON.SphereGeometry = SphereGeometry;
  35583. /**
  35584. * Creates a disc geometry
  35585. * @description see http://doc.babylonjs.com/how_to/set_shapes#disc-or-regular-polygon
  35586. */
  35587. var DiscGeometry = /** @class */ (function (_super) {
  35588. __extends(DiscGeometry, _super);
  35589. /**
  35590. * Creates a new disc geometry
  35591. * @param id defines the unique ID of the geometry
  35592. * @param scene defines the hosting scene
  35593. * @param radius defines the radius of the disc
  35594. * @param tessellation defines the tesselation factor to apply to the disc
  35595. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  35596. * @param mesh defines the hosting mesh (can be null)
  35597. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  35598. */
  35599. function DiscGeometry(id, scene,
  35600. /**
  35601. * Defines the radius of the disc
  35602. */
  35603. radius,
  35604. /**
  35605. * Defines the tesselation factor to apply to the disc
  35606. */
  35607. tessellation, canBeRegenerated, mesh,
  35608. /**
  35609. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  35610. */
  35611. side) {
  35612. if (mesh === void 0) { mesh = null; }
  35613. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  35614. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  35615. _this.radius = radius;
  35616. _this.tessellation = tessellation;
  35617. _this.side = side;
  35618. return _this;
  35619. }
  35620. DiscGeometry.prototype._regenerateVertexData = function () {
  35621. return BABYLON.VertexData.CreateDisc({ radius: this.radius, tessellation: this.tessellation, sideOrientation: this.side });
  35622. };
  35623. DiscGeometry.prototype.copy = function (id) {
  35624. return new DiscGeometry(id, this.getScene(), this.radius, this.tessellation, this.canBeRegenerated(), null, this.side);
  35625. };
  35626. return DiscGeometry;
  35627. }(_PrimitiveGeometry));
  35628. BABYLON.DiscGeometry = DiscGeometry;
  35629. /**
  35630. * Creates a new cylinder geometry
  35631. * @description see http://doc.babylonjs.com/how_to/set_shapes#cylinder-or-cone
  35632. */
  35633. var CylinderGeometry = /** @class */ (function (_super) {
  35634. __extends(CylinderGeometry, _super);
  35635. /**
  35636. * Creates a new cylinder geometry
  35637. * @param id defines the unique ID of the geometry
  35638. * @param scene defines the hosting scene
  35639. * @param height defines the height of the cylinder
  35640. * @param diameterTop defines the diameter of the cylinder's top cap
  35641. * @param diameterBottom defines the diameter of the cylinder's bottom cap
  35642. * @param tessellation defines the tessellation factor to apply to the cylinder (number of radial sides)
  35643. * @param subdivisions defines the number of subdivisions to apply to the cylinder (number of rings) (1 by default)
  35644. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  35645. * @param mesh defines the hosting mesh (can be null)
  35646. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  35647. */
  35648. function CylinderGeometry(id, scene,
  35649. /**
  35650. * Defines the height of the cylinder
  35651. */
  35652. height,
  35653. /**
  35654. * Defines the diameter of the cylinder's top cap
  35655. */
  35656. diameterTop,
  35657. /**
  35658. * Defines the diameter of the cylinder's bottom cap
  35659. */
  35660. diameterBottom,
  35661. /**
  35662. * Defines the tessellation factor to apply to the cylinder
  35663. */
  35664. tessellation,
  35665. /**
  35666. * Defines the number of subdivisions to apply to the cylinder (1 by default)
  35667. */
  35668. subdivisions, canBeRegenerated, mesh,
  35669. /**
  35670. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  35671. */
  35672. side) {
  35673. if (subdivisions === void 0) { subdivisions = 1; }
  35674. if (mesh === void 0) { mesh = null; }
  35675. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  35676. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  35677. _this.height = height;
  35678. _this.diameterTop = diameterTop;
  35679. _this.diameterBottom = diameterBottom;
  35680. _this.tessellation = tessellation;
  35681. _this.subdivisions = subdivisions;
  35682. _this.side = side;
  35683. return _this;
  35684. }
  35685. CylinderGeometry.prototype._regenerateVertexData = function () {
  35686. return BABYLON.VertexData.CreateCylinder({ height: this.height, diameterTop: this.diameterTop, diameterBottom: this.diameterBottom, tessellation: this.tessellation, subdivisions: this.subdivisions, sideOrientation: this.side });
  35687. };
  35688. CylinderGeometry.prototype.copy = function (id) {
  35689. return new CylinderGeometry(id, this.getScene(), this.height, this.diameterTop, this.diameterBottom, this.tessellation, this.subdivisions, this.canBeRegenerated(), null, this.side);
  35690. };
  35691. CylinderGeometry.prototype.serialize = function () {
  35692. var serializationObject = _super.prototype.serialize.call(this);
  35693. serializationObject.height = this.height;
  35694. serializationObject.diameterTop = this.diameterTop;
  35695. serializationObject.diameterBottom = this.diameterBottom;
  35696. serializationObject.tessellation = this.tessellation;
  35697. return serializationObject;
  35698. };
  35699. CylinderGeometry.Parse = function (parsedCylinder, scene) {
  35700. if (scene.getGeometryByID(parsedCylinder.id)) {
  35701. return null; // null since geometry could be something else than a cylinder...
  35702. }
  35703. var cylinder = new CylinderGeometry(parsedCylinder.id, scene, parsedCylinder.height, parsedCylinder.diameterTop, parsedCylinder.diameterBottom, parsedCylinder.tessellation, parsedCylinder.subdivisions, parsedCylinder.canBeRegenerated, null);
  35704. if (BABYLON.Tags) {
  35705. BABYLON.Tags.AddTagsTo(cylinder, parsedCylinder.tags);
  35706. }
  35707. scene.pushGeometry(cylinder, true);
  35708. return cylinder;
  35709. };
  35710. return CylinderGeometry;
  35711. }(_PrimitiveGeometry));
  35712. BABYLON.CylinderGeometry = CylinderGeometry;
  35713. /**
  35714. * Creates a new torus geometry
  35715. * @description see http://doc.babylonjs.com/how_to/set_shapes#torus
  35716. */
  35717. var TorusGeometry = /** @class */ (function (_super) {
  35718. __extends(TorusGeometry, _super);
  35719. /**
  35720. * Creates a new torus geometry
  35721. * @param id defines the unique ID of the geometry
  35722. * @param scene defines the hosting scene
  35723. * @param diameter defines the diameter of the torus
  35724. * @param thickness defines the thickness of the torus (ie. internal diameter)
  35725. * @param tessellation defines the tesselation factor to apply to the torus (number of segments along the circle)
  35726. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  35727. * @param mesh defines the hosting mesh (can be null)
  35728. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  35729. */
  35730. function TorusGeometry(id, scene,
  35731. /**
  35732. * Defines the diameter of the torus
  35733. */
  35734. diameter,
  35735. /**
  35736. * Defines the thickness of the torus (ie. internal diameter)
  35737. */
  35738. thickness,
  35739. /**
  35740. * Defines the tesselation factor to apply to the torus
  35741. */
  35742. tessellation, canBeRegenerated, mesh,
  35743. /**
  35744. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  35745. */
  35746. side) {
  35747. if (mesh === void 0) { mesh = null; }
  35748. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  35749. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  35750. _this.diameter = diameter;
  35751. _this.thickness = thickness;
  35752. _this.tessellation = tessellation;
  35753. _this.side = side;
  35754. return _this;
  35755. }
  35756. TorusGeometry.prototype._regenerateVertexData = function () {
  35757. return BABYLON.VertexData.CreateTorus({ diameter: this.diameter, thickness: this.thickness, tessellation: this.tessellation, sideOrientation: this.side });
  35758. };
  35759. TorusGeometry.prototype.copy = function (id) {
  35760. return new TorusGeometry(id, this.getScene(), this.diameter, this.thickness, this.tessellation, this.canBeRegenerated(), null, this.side);
  35761. };
  35762. TorusGeometry.prototype.serialize = function () {
  35763. var serializationObject = _super.prototype.serialize.call(this);
  35764. serializationObject.diameter = this.diameter;
  35765. serializationObject.thickness = this.thickness;
  35766. serializationObject.tessellation = this.tessellation;
  35767. return serializationObject;
  35768. };
  35769. TorusGeometry.Parse = function (parsedTorus, scene) {
  35770. if (scene.getGeometryByID(parsedTorus.id)) {
  35771. return null; // null since geometry could be something else than a torus...
  35772. }
  35773. var torus = new TorusGeometry(parsedTorus.id, scene, parsedTorus.diameter, parsedTorus.thickness, parsedTorus.tessellation, parsedTorus.canBeRegenerated, null);
  35774. if (BABYLON.Tags) {
  35775. BABYLON.Tags.AddTagsTo(torus, parsedTorus.tags);
  35776. }
  35777. scene.pushGeometry(torus, true);
  35778. return torus;
  35779. };
  35780. return TorusGeometry;
  35781. }(_PrimitiveGeometry));
  35782. BABYLON.TorusGeometry = TorusGeometry;
  35783. /**
  35784. * Creates a new ground geometry
  35785. * @description see http://doc.babylonjs.com/how_to/set_shapes#ground
  35786. */
  35787. var GroundGeometry = /** @class */ (function (_super) {
  35788. __extends(GroundGeometry, _super);
  35789. /**
  35790. * Creates a new ground geometry
  35791. * @param id defines the unique ID of the geometry
  35792. * @param scene defines the hosting scene
  35793. * @param width defines the width of the ground
  35794. * @param height defines the height of the ground
  35795. * @param subdivisions defines the subdivisions to apply to the ground
  35796. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  35797. * @param mesh defines the hosting mesh (can be null)
  35798. */
  35799. function GroundGeometry(id, scene,
  35800. /**
  35801. * Defines the width of the ground
  35802. */
  35803. width,
  35804. /**
  35805. * Defines the height of the ground
  35806. */
  35807. height,
  35808. /**
  35809. * Defines the subdivisions to apply to the ground
  35810. */
  35811. subdivisions, canBeRegenerated, mesh) {
  35812. if (mesh === void 0) { mesh = null; }
  35813. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  35814. _this.width = width;
  35815. _this.height = height;
  35816. _this.subdivisions = subdivisions;
  35817. return _this;
  35818. }
  35819. GroundGeometry.prototype._regenerateVertexData = function () {
  35820. return BABYLON.VertexData.CreateGround({ width: this.width, height: this.height, subdivisions: this.subdivisions });
  35821. };
  35822. GroundGeometry.prototype.copy = function (id) {
  35823. return new GroundGeometry(id, this.getScene(), this.width, this.height, this.subdivisions, this.canBeRegenerated(), null);
  35824. };
  35825. GroundGeometry.prototype.serialize = function () {
  35826. var serializationObject = _super.prototype.serialize.call(this);
  35827. serializationObject.width = this.width;
  35828. serializationObject.height = this.height;
  35829. serializationObject.subdivisions = this.subdivisions;
  35830. return serializationObject;
  35831. };
  35832. GroundGeometry.Parse = function (parsedGround, scene) {
  35833. if (scene.getGeometryByID(parsedGround.id)) {
  35834. return null; // null since geometry could be something else than a ground...
  35835. }
  35836. var ground = new GroundGeometry(parsedGround.id, scene, parsedGround.width, parsedGround.height, parsedGround.subdivisions, parsedGround.canBeRegenerated, null);
  35837. if (BABYLON.Tags) {
  35838. BABYLON.Tags.AddTagsTo(ground, parsedGround.tags);
  35839. }
  35840. scene.pushGeometry(ground, true);
  35841. return ground;
  35842. };
  35843. return GroundGeometry;
  35844. }(_PrimitiveGeometry));
  35845. BABYLON.GroundGeometry = GroundGeometry;
  35846. /**
  35847. * Creates a tiled ground geometry
  35848. * @description see http://doc.babylonjs.com/how_to/set_shapes#tiled-ground
  35849. */
  35850. var TiledGroundGeometry = /** @class */ (function (_super) {
  35851. __extends(TiledGroundGeometry, _super);
  35852. /**
  35853. * Creates a tiled ground geometry
  35854. * @param id defines the unique ID of the geometry
  35855. * @param scene defines the hosting scene
  35856. * @param xmin defines the minimum value on X axis
  35857. * @param zmin defines the minimum value on Z axis
  35858. * @param xmax defines the maximum value on X axis
  35859. * @param zmax defines the maximum value on Z axis
  35860. * @param subdivisions defines the subdivisions to apply to the ground (number of subdivisions (tiles) on the height and the width of the map)
  35861. * @param precision defines the precision to use when computing the tiles
  35862. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  35863. * @param mesh defines the hosting mesh (can be null)
  35864. */
  35865. function TiledGroundGeometry(id, scene,
  35866. /**
  35867. * Defines the minimum value on X axis
  35868. */
  35869. xmin,
  35870. /**
  35871. * Defines the minimum value on Z axis
  35872. */
  35873. zmin,
  35874. /**
  35875. * Defines the maximum value on X axis
  35876. */
  35877. xmax,
  35878. /**
  35879. * Defines the maximum value on Z axis
  35880. */
  35881. zmax,
  35882. /**
  35883. * Defines the subdivisions to apply to the ground
  35884. */
  35885. subdivisions,
  35886. /**
  35887. * Defines the precision to use when computing the tiles
  35888. */
  35889. precision, canBeRegenerated, mesh) {
  35890. if (mesh === void 0) { mesh = null; }
  35891. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  35892. _this.xmin = xmin;
  35893. _this.zmin = zmin;
  35894. _this.xmax = xmax;
  35895. _this.zmax = zmax;
  35896. _this.subdivisions = subdivisions;
  35897. _this.precision = precision;
  35898. return _this;
  35899. }
  35900. TiledGroundGeometry.prototype._regenerateVertexData = function () {
  35901. return BABYLON.VertexData.CreateTiledGround({ xmin: this.xmin, zmin: this.zmin, xmax: this.xmax, zmax: this.zmax, subdivisions: this.subdivisions, precision: this.precision });
  35902. };
  35903. TiledGroundGeometry.prototype.copy = function (id) {
  35904. return new TiledGroundGeometry(id, this.getScene(), this.xmin, this.zmin, this.xmax, this.zmax, this.subdivisions, this.precision, this.canBeRegenerated(), null);
  35905. };
  35906. return TiledGroundGeometry;
  35907. }(_PrimitiveGeometry));
  35908. BABYLON.TiledGroundGeometry = TiledGroundGeometry;
  35909. /**
  35910. * Creates a plane geometry
  35911. * @description see http://doc.babylonjs.com/how_to/set_shapes#plane
  35912. */
  35913. var PlaneGeometry = /** @class */ (function (_super) {
  35914. __extends(PlaneGeometry, _super);
  35915. /**
  35916. * Creates a plane geometry
  35917. * @param id defines the unique ID of the geometry
  35918. * @param scene defines the hosting scene
  35919. * @param size defines the size of the plane (width === height)
  35920. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  35921. * @param mesh defines the hosting mesh (can be null)
  35922. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  35923. */
  35924. function PlaneGeometry(id, scene,
  35925. /**
  35926. * Defines the size of the plane (width === height)
  35927. */
  35928. size, canBeRegenerated, mesh,
  35929. /**
  35930. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  35931. */
  35932. side) {
  35933. if (mesh === void 0) { mesh = null; }
  35934. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  35935. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  35936. _this.size = size;
  35937. _this.side = side;
  35938. return _this;
  35939. }
  35940. PlaneGeometry.prototype._regenerateVertexData = function () {
  35941. return BABYLON.VertexData.CreatePlane({ size: this.size, sideOrientation: this.side });
  35942. };
  35943. PlaneGeometry.prototype.copy = function (id) {
  35944. return new PlaneGeometry(id, this.getScene(), this.size, this.canBeRegenerated(), null, this.side);
  35945. };
  35946. PlaneGeometry.prototype.serialize = function () {
  35947. var serializationObject = _super.prototype.serialize.call(this);
  35948. serializationObject.size = this.size;
  35949. return serializationObject;
  35950. };
  35951. PlaneGeometry.Parse = function (parsedPlane, scene) {
  35952. if (scene.getGeometryByID(parsedPlane.id)) {
  35953. return null; // null since geometry could be something else than a ground...
  35954. }
  35955. var plane = new PlaneGeometry(parsedPlane.id, scene, parsedPlane.size, parsedPlane.canBeRegenerated, null);
  35956. if (BABYLON.Tags) {
  35957. BABYLON.Tags.AddTagsTo(plane, parsedPlane.tags);
  35958. }
  35959. scene.pushGeometry(plane, true);
  35960. return plane;
  35961. };
  35962. return PlaneGeometry;
  35963. }(_PrimitiveGeometry));
  35964. BABYLON.PlaneGeometry = PlaneGeometry;
  35965. /**
  35966. * Creates a torus knot geometry
  35967. * @description see http://doc.babylonjs.com/how_to/set_shapes#torus-knot
  35968. */
  35969. var TorusKnotGeometry = /** @class */ (function (_super) {
  35970. __extends(TorusKnotGeometry, _super);
  35971. /**
  35972. * Creates a torus knot geometry
  35973. * @param id defines the unique ID of the geometry
  35974. * @param scene defines the hosting scene
  35975. * @param radius defines the radius of the torus knot
  35976. * @param tube defines the thickness of the torus knot tube
  35977. * @param radialSegments defines the number of radial segments
  35978. * @param tubularSegments defines the number of tubular segments
  35979. * @param p defines the first number of windings
  35980. * @param q defines the second number of windings
  35981. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  35982. * @param mesh defines the hosting mesh (can be null)
  35983. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  35984. */
  35985. function TorusKnotGeometry(id, scene,
  35986. /**
  35987. * Defines the radius of the torus knot
  35988. */
  35989. radius,
  35990. /**
  35991. * Defines the thickness of the torus knot tube
  35992. */
  35993. tube,
  35994. /**
  35995. * Defines the number of radial segments
  35996. */
  35997. radialSegments,
  35998. /**
  35999. * Defines the number of tubular segments
  36000. */
  36001. tubularSegments,
  36002. /**
  36003. * Defines the first number of windings
  36004. */
  36005. p,
  36006. /**
  36007. * Defines the second number of windings
  36008. */
  36009. q, canBeRegenerated, mesh,
  36010. /**
  36011. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  36012. */
  36013. side) {
  36014. if (mesh === void 0) { mesh = null; }
  36015. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  36016. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  36017. _this.radius = radius;
  36018. _this.tube = tube;
  36019. _this.radialSegments = radialSegments;
  36020. _this.tubularSegments = tubularSegments;
  36021. _this.p = p;
  36022. _this.q = q;
  36023. _this.side = side;
  36024. return _this;
  36025. }
  36026. TorusKnotGeometry.prototype._regenerateVertexData = function () {
  36027. 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 });
  36028. };
  36029. TorusKnotGeometry.prototype.copy = function (id) {
  36030. return new TorusKnotGeometry(id, this.getScene(), this.radius, this.tube, this.radialSegments, this.tubularSegments, this.p, this.q, this.canBeRegenerated(), null, this.side);
  36031. };
  36032. TorusKnotGeometry.prototype.serialize = function () {
  36033. var serializationObject = _super.prototype.serialize.call(this);
  36034. serializationObject.radius = this.radius;
  36035. serializationObject.tube = this.tube;
  36036. serializationObject.radialSegments = this.radialSegments;
  36037. serializationObject.tubularSegments = this.tubularSegments;
  36038. serializationObject.p = this.p;
  36039. serializationObject.q = this.q;
  36040. return serializationObject;
  36041. };
  36042. ;
  36043. TorusKnotGeometry.Parse = function (parsedTorusKnot, scene) {
  36044. if (scene.getGeometryByID(parsedTorusKnot.id)) {
  36045. return null; // null since geometry could be something else than a ground...
  36046. }
  36047. var torusKnot = new TorusKnotGeometry(parsedTorusKnot.id, scene, parsedTorusKnot.radius, parsedTorusKnot.tube, parsedTorusKnot.radialSegments, parsedTorusKnot.tubularSegments, parsedTorusKnot.p, parsedTorusKnot.q, parsedTorusKnot.canBeRegenerated, null);
  36048. if (BABYLON.Tags) {
  36049. BABYLON.Tags.AddTagsTo(torusKnot, parsedTorusKnot.tags);
  36050. }
  36051. scene.pushGeometry(torusKnot, true);
  36052. return torusKnot;
  36053. };
  36054. return TorusKnotGeometry;
  36055. }(_PrimitiveGeometry));
  36056. BABYLON.TorusKnotGeometry = TorusKnotGeometry;
  36057. //}
  36058. })(BABYLON || (BABYLON = {}));
  36059. //# sourceMappingURL=babylon.geometry.js.map
  36060. var BABYLON;
  36061. (function (BABYLON) {
  36062. /**
  36063. * PostProcessManager is used to manage one or more post processes or post process pipelines
  36064. * See https://doc.babylonjs.com/how_to/how_to_use_postprocesses
  36065. */
  36066. var PostProcessManager = /** @class */ (function () {
  36067. /**
  36068. * Creates a new instance of @see PostProcess
  36069. * @param scene The scene that the post process is associated with.
  36070. */
  36071. function PostProcessManager(scene) {
  36072. this._vertexBuffers = {};
  36073. this._scene = scene;
  36074. }
  36075. PostProcessManager.prototype._prepareBuffers = function () {
  36076. if (this._vertexBuffers[BABYLON.VertexBuffer.PositionKind]) {
  36077. return;
  36078. }
  36079. // VBO
  36080. var vertices = [];
  36081. vertices.push(1, 1);
  36082. vertices.push(-1, 1);
  36083. vertices.push(-1, -1);
  36084. vertices.push(1, -1);
  36085. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(this._scene.getEngine(), vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  36086. this._buildIndexBuffer();
  36087. };
  36088. PostProcessManager.prototype._buildIndexBuffer = function () {
  36089. // Indices
  36090. var indices = [];
  36091. indices.push(0);
  36092. indices.push(1);
  36093. indices.push(2);
  36094. indices.push(0);
  36095. indices.push(2);
  36096. indices.push(3);
  36097. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  36098. };
  36099. /**
  36100. * Rebuilds the vertex buffers of the manager.
  36101. */
  36102. PostProcessManager.prototype._rebuild = function () {
  36103. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  36104. if (!vb) {
  36105. return;
  36106. }
  36107. vb._rebuild();
  36108. this._buildIndexBuffer();
  36109. };
  36110. // Methods
  36111. /**
  36112. * Prepares a frame to be run through a post process.
  36113. * @param sourceTexture The input texture to the post procesess. (default: null)
  36114. * @param postProcesses An array of post processes to be run. (default: null)
  36115. * @returns True if the post processes were able to be run.
  36116. */
  36117. PostProcessManager.prototype._prepareFrame = function (sourceTexture, postProcesses) {
  36118. if (sourceTexture === void 0) { sourceTexture = null; }
  36119. if (postProcesses === void 0) { postProcesses = null; }
  36120. var camera = this._scene.activeCamera;
  36121. if (!camera) {
  36122. return false;
  36123. }
  36124. var postProcesses = postProcesses || camera._postProcesses;
  36125. if (!postProcesses || postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  36126. return false;
  36127. }
  36128. postProcesses[0].activate(camera, sourceTexture, postProcesses !== null && postProcesses !== undefined);
  36129. return true;
  36130. };
  36131. /**
  36132. * Manually render a set of post processes to a texture.
  36133. * @param postProcesses An array of post processes to be run.
  36134. * @param targetTexture The target texture to render to.
  36135. * @param forceFullscreenViewport force gl.viewport to be full screen eg. 0,0,textureWidth,textureHeight
  36136. */
  36137. PostProcessManager.prototype.directRender = function (postProcesses, targetTexture, forceFullscreenViewport) {
  36138. if (targetTexture === void 0) { targetTexture = null; }
  36139. if (forceFullscreenViewport === void 0) { forceFullscreenViewport = false; }
  36140. var engine = this._scene.getEngine();
  36141. for (var index = 0; index < postProcesses.length; index++) {
  36142. if (index < postProcesses.length - 1) {
  36143. postProcesses[index + 1].activate(this._scene.activeCamera, targetTexture);
  36144. }
  36145. else {
  36146. if (targetTexture) {
  36147. engine.bindFramebuffer(targetTexture, 0, undefined, undefined, forceFullscreenViewport);
  36148. }
  36149. else {
  36150. engine.restoreDefaultFramebuffer();
  36151. }
  36152. }
  36153. var pp = postProcesses[index];
  36154. var effect = pp.apply();
  36155. if (effect) {
  36156. pp.onBeforeRenderObservable.notifyObservers(effect);
  36157. // VBOs
  36158. this._prepareBuffers();
  36159. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  36160. // Draw order
  36161. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  36162. pp.onAfterRenderObservable.notifyObservers(effect);
  36163. }
  36164. }
  36165. // Restore depth buffer
  36166. engine.setDepthBuffer(true);
  36167. engine.setDepthWrite(true);
  36168. };
  36169. /**
  36170. * Finalize the result of the output of the postprocesses.
  36171. * @param doNotPresent If true the result will not be displayed to the screen.
  36172. * @param targetTexture The target texture to render to.
  36173. * @param faceIndex The index of the face to bind the target texture to.
  36174. * @param postProcesses The array of post processes to render.
  36175. * @param forceFullscreenViewport force gl.viewport to be full screen eg. 0,0,textureWidth,textureHeight (default: false)
  36176. */
  36177. PostProcessManager.prototype._finalizeFrame = function (doNotPresent, targetTexture, faceIndex, postProcesses, forceFullscreenViewport) {
  36178. if (forceFullscreenViewport === void 0) { forceFullscreenViewport = false; }
  36179. var camera = this._scene.activeCamera;
  36180. if (!camera) {
  36181. return;
  36182. }
  36183. postProcesses = postProcesses || camera._postProcesses;
  36184. if (postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  36185. return;
  36186. }
  36187. var engine = this._scene.getEngine();
  36188. for (var index = 0, len = postProcesses.length; index < len; index++) {
  36189. if (index < len - 1) {
  36190. postProcesses[index + 1].activate(camera, targetTexture);
  36191. }
  36192. else {
  36193. if (targetTexture) {
  36194. engine.bindFramebuffer(targetTexture, faceIndex, undefined, undefined, forceFullscreenViewport);
  36195. }
  36196. else {
  36197. engine.restoreDefaultFramebuffer();
  36198. }
  36199. }
  36200. if (doNotPresent) {
  36201. break;
  36202. }
  36203. var pp = postProcesses[index];
  36204. var effect = pp.apply();
  36205. if (effect) {
  36206. pp.onBeforeRenderObservable.notifyObservers(effect);
  36207. // VBOs
  36208. this._prepareBuffers();
  36209. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  36210. // Draw order
  36211. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  36212. pp.onAfterRenderObservable.notifyObservers(effect);
  36213. }
  36214. }
  36215. // Restore states
  36216. engine.setDepthBuffer(true);
  36217. engine.setDepthWrite(true);
  36218. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  36219. };
  36220. /**
  36221. * Disposes of the post process manager.
  36222. */
  36223. PostProcessManager.prototype.dispose = function () {
  36224. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  36225. if (buffer) {
  36226. buffer.dispose();
  36227. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  36228. }
  36229. if (this._indexBuffer) {
  36230. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  36231. this._indexBuffer = null;
  36232. }
  36233. };
  36234. return PostProcessManager;
  36235. }());
  36236. BABYLON.PostProcessManager = PostProcessManager;
  36237. })(BABYLON || (BABYLON = {}));
  36238. //# sourceMappingURL=babylon.postProcessManager.js.map
  36239. var BABYLON;
  36240. (function (BABYLON) {
  36241. /**
  36242. * Performance monitor tracks rolling average frame-time and frame-time variance over a user defined sliding-window
  36243. */
  36244. var PerformanceMonitor = /** @class */ (function () {
  36245. /**
  36246. * constructor
  36247. * @param frameSampleSize The number of samples required to saturate the sliding window
  36248. */
  36249. function PerformanceMonitor(frameSampleSize) {
  36250. if (frameSampleSize === void 0) { frameSampleSize = 30; }
  36251. this._enabled = true;
  36252. this._rollingFrameTime = new RollingAverage(frameSampleSize);
  36253. }
  36254. /**
  36255. * Samples current frame
  36256. * @param timeMs A timestamp in milliseconds of the current frame to compare with other frames
  36257. */
  36258. PerformanceMonitor.prototype.sampleFrame = function (timeMs) {
  36259. if (timeMs === void 0) { timeMs = BABYLON.Tools.Now; }
  36260. if (!this._enabled)
  36261. return;
  36262. if (this._lastFrameTimeMs != null) {
  36263. var dt = timeMs - this._lastFrameTimeMs;
  36264. this._rollingFrameTime.add(dt);
  36265. }
  36266. this._lastFrameTimeMs = timeMs;
  36267. };
  36268. Object.defineProperty(PerformanceMonitor.prototype, "averageFrameTime", {
  36269. /**
  36270. * Returns the average frame time in milliseconds over the sliding window (or the subset of frames sampled so far)
  36271. * @return Average frame time in milliseconds
  36272. */
  36273. get: function () {
  36274. return this._rollingFrameTime.average;
  36275. },
  36276. enumerable: true,
  36277. configurable: true
  36278. });
  36279. Object.defineProperty(PerformanceMonitor.prototype, "averageFrameTimeVariance", {
  36280. /**
  36281. * Returns the variance frame time in milliseconds over the sliding window (or the subset of frames sampled so far)
  36282. * @return Frame time variance in milliseconds squared
  36283. */
  36284. get: function () {
  36285. return this._rollingFrameTime.variance;
  36286. },
  36287. enumerable: true,
  36288. configurable: true
  36289. });
  36290. Object.defineProperty(PerformanceMonitor.prototype, "instantaneousFrameTime", {
  36291. /**
  36292. * Returns the frame time of the most recent frame
  36293. * @return Frame time in milliseconds
  36294. */
  36295. get: function () {
  36296. return this._rollingFrameTime.history(0);
  36297. },
  36298. enumerable: true,
  36299. configurable: true
  36300. });
  36301. Object.defineProperty(PerformanceMonitor.prototype, "averageFPS", {
  36302. /**
  36303. * Returns the average framerate in frames per second over the sliding window (or the subset of frames sampled so far)
  36304. * @return Framerate in frames per second
  36305. */
  36306. get: function () {
  36307. return 1000.0 / this._rollingFrameTime.average;
  36308. },
  36309. enumerable: true,
  36310. configurable: true
  36311. });
  36312. Object.defineProperty(PerformanceMonitor.prototype, "instantaneousFPS", {
  36313. /**
  36314. * Returns the average framerate in frames per second using the most recent frame time
  36315. * @return Framerate in frames per second
  36316. */
  36317. get: function () {
  36318. var history = this._rollingFrameTime.history(0);
  36319. if (history === 0) {
  36320. return 0;
  36321. }
  36322. return 1000.0 / history;
  36323. },
  36324. enumerable: true,
  36325. configurable: true
  36326. });
  36327. Object.defineProperty(PerformanceMonitor.prototype, "isSaturated", {
  36328. /**
  36329. * Returns true if enough samples have been taken to completely fill the sliding window
  36330. * @return true if saturated
  36331. */
  36332. get: function () {
  36333. return this._rollingFrameTime.isSaturated();
  36334. },
  36335. enumerable: true,
  36336. configurable: true
  36337. });
  36338. /**
  36339. * Enables contributions to the sliding window sample set
  36340. */
  36341. PerformanceMonitor.prototype.enable = function () {
  36342. this._enabled = true;
  36343. };
  36344. /**
  36345. * Disables contributions to the sliding window sample set
  36346. * Samples will not be interpolated over the disabled period
  36347. */
  36348. PerformanceMonitor.prototype.disable = function () {
  36349. this._enabled = false;
  36350. //clear last sample to avoid interpolating over the disabled period when next enabled
  36351. this._lastFrameTimeMs = null;
  36352. };
  36353. Object.defineProperty(PerformanceMonitor.prototype, "isEnabled", {
  36354. /**
  36355. * Returns true if sampling is enabled
  36356. * @return true if enabled
  36357. */
  36358. get: function () {
  36359. return this._enabled;
  36360. },
  36361. enumerable: true,
  36362. configurable: true
  36363. });
  36364. /**
  36365. * Resets performance monitor
  36366. */
  36367. PerformanceMonitor.prototype.reset = function () {
  36368. //clear last sample to avoid interpolating over the disabled period when next enabled
  36369. this._lastFrameTimeMs = null;
  36370. //wipe record
  36371. this._rollingFrameTime.reset();
  36372. };
  36373. return PerformanceMonitor;
  36374. }());
  36375. BABYLON.PerformanceMonitor = PerformanceMonitor;
  36376. /**
  36377. * RollingAverage
  36378. *
  36379. * Utility to efficiently compute the rolling average and variance over a sliding window of samples
  36380. */
  36381. var RollingAverage = /** @class */ (function () {
  36382. /**
  36383. * constructor
  36384. * @param length The number of samples required to saturate the sliding window
  36385. */
  36386. function RollingAverage(length) {
  36387. this._samples = new Array(length);
  36388. this.reset();
  36389. }
  36390. /**
  36391. * Adds a sample to the sample set
  36392. * @param v The sample value
  36393. */
  36394. RollingAverage.prototype.add = function (v) {
  36395. //http://en.wikipedia.org/wiki/Algorithms_for_calculating_variance
  36396. var delta;
  36397. //we need to check if we've already wrapped round
  36398. if (this.isSaturated()) {
  36399. //remove bottom of stack from mean
  36400. var bottomValue = this._samples[this._pos];
  36401. delta = bottomValue - this.average;
  36402. this.average -= delta / (this._sampleCount - 1);
  36403. this._m2 -= delta * (bottomValue - this.average);
  36404. }
  36405. else {
  36406. this._sampleCount++;
  36407. }
  36408. //add new value to mean
  36409. delta = v - this.average;
  36410. this.average += delta / (this._sampleCount);
  36411. this._m2 += delta * (v - this.average);
  36412. //set the new variance
  36413. this.variance = this._m2 / (this._sampleCount - 1);
  36414. this._samples[this._pos] = v;
  36415. this._pos++;
  36416. this._pos %= this._samples.length; //positive wrap around
  36417. };
  36418. /**
  36419. * Returns previously added values or null if outside of history or outside the sliding window domain
  36420. * @param i Index in history. For example, pass 0 for the most recent value and 1 for the value before that
  36421. * @return Value previously recorded with add() or null if outside of range
  36422. */
  36423. RollingAverage.prototype.history = function (i) {
  36424. if ((i >= this._sampleCount) || (i >= this._samples.length)) {
  36425. return 0;
  36426. }
  36427. var i0 = this._wrapPosition(this._pos - 1.0);
  36428. return this._samples[this._wrapPosition(i0 - i)];
  36429. };
  36430. /**
  36431. * Returns true if enough samples have been taken to completely fill the sliding window
  36432. * @return true if sample-set saturated
  36433. */
  36434. RollingAverage.prototype.isSaturated = function () {
  36435. return this._sampleCount >= this._samples.length;
  36436. };
  36437. /**
  36438. * Resets the rolling average (equivalent to 0 samples taken so far)
  36439. */
  36440. RollingAverage.prototype.reset = function () {
  36441. this.average = 0;
  36442. this.variance = 0;
  36443. this._sampleCount = 0;
  36444. this._pos = 0;
  36445. this._m2 = 0;
  36446. };
  36447. /**
  36448. * Wraps a value around the sample range boundaries
  36449. * @param i Position in sample range, for example if the sample length is 5, and i is -3, then 2 will be returned.
  36450. * @return Wrapped position in sample range
  36451. */
  36452. RollingAverage.prototype._wrapPosition = function (i) {
  36453. var max = this._samples.length;
  36454. return ((i % max) + max) % max;
  36455. };
  36456. return RollingAverage;
  36457. }());
  36458. BABYLON.RollingAverage = RollingAverage;
  36459. })(BABYLON || (BABYLON = {}));
  36460. //# sourceMappingURL=babylon.performanceMonitor.js.map
  36461. var BABYLON;
  36462. (function (BABYLON) {
  36463. /**
  36464. * This groups together the common properties used for image processing either in direct forward pass
  36465. * or through post processing effect depending on the use of the image processing pipeline in your scene
  36466. * or not.
  36467. */
  36468. var ImageProcessingConfiguration = /** @class */ (function () {
  36469. function ImageProcessingConfiguration() {
  36470. /**
  36471. * Color curves setup used in the effect if colorCurvesEnabled is set to true
  36472. */
  36473. this.colorCurves = new BABYLON.ColorCurves();
  36474. this._colorCurvesEnabled = false;
  36475. this._colorGradingEnabled = false;
  36476. this._colorGradingWithGreenDepth = true;
  36477. this._colorGradingBGR = true;
  36478. this._exposure = 1.0;
  36479. this._toneMappingEnabled = false;
  36480. this._contrast = 1.0;
  36481. /**
  36482. * Vignette stretch size.
  36483. */
  36484. this.vignetteStretch = 0;
  36485. /**
  36486. * Vignette centre X Offset.
  36487. */
  36488. this.vignetteCentreX = 0;
  36489. /**
  36490. * Vignette centre Y Offset.
  36491. */
  36492. this.vignetteCentreY = 0;
  36493. /**
  36494. * Vignette weight or intensity of the vignette effect.
  36495. */
  36496. this.vignetteWeight = 1.5;
  36497. /**
  36498. * Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  36499. * if vignetteEnabled is set to true.
  36500. */
  36501. this.vignetteColor = new BABYLON.Color4(0, 0, 0, 0);
  36502. /**
  36503. * Camera field of view used by the Vignette effect.
  36504. */
  36505. this.vignetteCameraFov = 0.5;
  36506. this._vignetteBlendMode = ImageProcessingConfiguration.VIGNETTEMODE_MULTIPLY;
  36507. this._vignetteEnabled = false;
  36508. this._applyByPostProcess = false;
  36509. this._isEnabled = true;
  36510. /**
  36511. * An event triggered when the configuration changes and requires Shader to Update some parameters.
  36512. * @type {BABYLON.Observable}
  36513. */
  36514. this.onUpdateParameters = new BABYLON.Observable();
  36515. }
  36516. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorCurvesEnabled", {
  36517. /**
  36518. * Gets wether the color curves effect is enabled.
  36519. */
  36520. get: function () {
  36521. return this._colorCurvesEnabled;
  36522. },
  36523. /**
  36524. * Sets wether the color curves effect is enabled.
  36525. */
  36526. set: function (value) {
  36527. if (this._colorCurvesEnabled === value) {
  36528. return;
  36529. }
  36530. this._colorCurvesEnabled = value;
  36531. this._updateParameters();
  36532. },
  36533. enumerable: true,
  36534. configurable: true
  36535. });
  36536. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingEnabled", {
  36537. /**
  36538. * Gets wether the color grading effect is enabled.
  36539. */
  36540. get: function () {
  36541. return this._colorGradingEnabled;
  36542. },
  36543. /**
  36544. * Sets wether the color grading effect is enabled.
  36545. */
  36546. set: function (value) {
  36547. if (this._colorGradingEnabled === value) {
  36548. return;
  36549. }
  36550. this._colorGradingEnabled = value;
  36551. this._updateParameters();
  36552. },
  36553. enumerable: true,
  36554. configurable: true
  36555. });
  36556. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingWithGreenDepth", {
  36557. /**
  36558. * Gets wether the color grading effect is using a green depth for the 3d Texture.
  36559. */
  36560. get: function () {
  36561. return this._colorGradingWithGreenDepth;
  36562. },
  36563. /**
  36564. * Sets wether the color grading effect is using a green depth for the 3d Texture.
  36565. */
  36566. set: function (value) {
  36567. if (this._colorGradingWithGreenDepth === value) {
  36568. return;
  36569. }
  36570. this._colorGradingWithGreenDepth = value;
  36571. this._updateParameters();
  36572. },
  36573. enumerable: true,
  36574. configurable: true
  36575. });
  36576. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingBGR", {
  36577. /**
  36578. * Gets wether the color grading texture contains BGR values.
  36579. */
  36580. get: function () {
  36581. return this._colorGradingBGR;
  36582. },
  36583. /**
  36584. * Sets wether the color grading texture contains BGR values.
  36585. */
  36586. set: function (value) {
  36587. if (this._colorGradingBGR === value) {
  36588. return;
  36589. }
  36590. this._colorGradingBGR = value;
  36591. this._updateParameters();
  36592. },
  36593. enumerable: true,
  36594. configurable: true
  36595. });
  36596. Object.defineProperty(ImageProcessingConfiguration.prototype, "exposure", {
  36597. /**
  36598. * Gets the Exposure used in the effect.
  36599. */
  36600. get: function () {
  36601. return this._exposure;
  36602. },
  36603. /**
  36604. * Sets the Exposure used in the effect.
  36605. */
  36606. set: function (value) {
  36607. if (this._exposure === value) {
  36608. return;
  36609. }
  36610. this._exposure = value;
  36611. this._updateParameters();
  36612. },
  36613. enumerable: true,
  36614. configurable: true
  36615. });
  36616. Object.defineProperty(ImageProcessingConfiguration.prototype, "toneMappingEnabled", {
  36617. /**
  36618. * Gets wether the tone mapping effect is enabled.
  36619. */
  36620. get: function () {
  36621. return this._toneMappingEnabled;
  36622. },
  36623. /**
  36624. * Sets wether the tone mapping effect is enabled.
  36625. */
  36626. set: function (value) {
  36627. if (this._toneMappingEnabled === value) {
  36628. return;
  36629. }
  36630. this._toneMappingEnabled = value;
  36631. this._updateParameters();
  36632. },
  36633. enumerable: true,
  36634. configurable: true
  36635. });
  36636. Object.defineProperty(ImageProcessingConfiguration.prototype, "contrast", {
  36637. /**
  36638. * Gets the contrast used in the effect.
  36639. */
  36640. get: function () {
  36641. return this._contrast;
  36642. },
  36643. /**
  36644. * Sets the contrast used in the effect.
  36645. */
  36646. set: function (value) {
  36647. if (this._contrast === value) {
  36648. return;
  36649. }
  36650. this._contrast = value;
  36651. this._updateParameters();
  36652. },
  36653. enumerable: true,
  36654. configurable: true
  36655. });
  36656. Object.defineProperty(ImageProcessingConfiguration.prototype, "vignetteBlendMode", {
  36657. /**
  36658. * Gets the vignette blend mode allowing different kind of effect.
  36659. */
  36660. get: function () {
  36661. return this._vignetteBlendMode;
  36662. },
  36663. /**
  36664. * Sets the vignette blend mode allowing different kind of effect.
  36665. */
  36666. set: function (value) {
  36667. if (this._vignetteBlendMode === value) {
  36668. return;
  36669. }
  36670. this._vignetteBlendMode = value;
  36671. this._updateParameters();
  36672. },
  36673. enumerable: true,
  36674. configurable: true
  36675. });
  36676. Object.defineProperty(ImageProcessingConfiguration.prototype, "vignetteEnabled", {
  36677. /**
  36678. * Gets wether the vignette effect is enabled.
  36679. */
  36680. get: function () {
  36681. return this._vignetteEnabled;
  36682. },
  36683. /**
  36684. * Sets wether the vignette effect is enabled.
  36685. */
  36686. set: function (value) {
  36687. if (this._vignetteEnabled === value) {
  36688. return;
  36689. }
  36690. this._vignetteEnabled = value;
  36691. this._updateParameters();
  36692. },
  36693. enumerable: true,
  36694. configurable: true
  36695. });
  36696. Object.defineProperty(ImageProcessingConfiguration.prototype, "applyByPostProcess", {
  36697. /**
  36698. * Gets wether the image processing is applied through a post process or not.
  36699. */
  36700. get: function () {
  36701. return this._applyByPostProcess;
  36702. },
  36703. /**
  36704. * Sets wether the image processing is applied through a post process or not.
  36705. */
  36706. set: function (value) {
  36707. if (this._applyByPostProcess === value) {
  36708. return;
  36709. }
  36710. this._applyByPostProcess = value;
  36711. this._updateParameters();
  36712. },
  36713. enumerable: true,
  36714. configurable: true
  36715. });
  36716. Object.defineProperty(ImageProcessingConfiguration.prototype, "isEnabled", {
  36717. /**
  36718. * Gets wether the image processing is enabled or not.
  36719. */
  36720. get: function () {
  36721. return this._isEnabled;
  36722. },
  36723. /**
  36724. * Sets wether the image processing is enabled or not.
  36725. */
  36726. set: function (value) {
  36727. if (this._isEnabled === value) {
  36728. return;
  36729. }
  36730. this._isEnabled = value;
  36731. this._updateParameters();
  36732. },
  36733. enumerable: true,
  36734. configurable: true
  36735. });
  36736. /**
  36737. * Method called each time the image processing information changes requires to recompile the effect.
  36738. */
  36739. ImageProcessingConfiguration.prototype._updateParameters = function () {
  36740. this.onUpdateParameters.notifyObservers(this);
  36741. };
  36742. ImageProcessingConfiguration.prototype.getClassName = function () {
  36743. return "ImageProcessingConfiguration";
  36744. };
  36745. /**
  36746. * Prepare the list of uniforms associated with the Image Processing effects.
  36747. * @param uniformsList The list of uniforms used in the effect
  36748. * @param defines the list of defines currently in use
  36749. */
  36750. ImageProcessingConfiguration.PrepareUniforms = function (uniforms, defines) {
  36751. if (defines.EXPOSURE) {
  36752. uniforms.push("exposureLinear");
  36753. }
  36754. if (defines.CONTRAST) {
  36755. uniforms.push("contrast");
  36756. }
  36757. if (defines.COLORGRADING) {
  36758. uniforms.push("colorTransformSettings");
  36759. }
  36760. if (defines.VIGNETTE) {
  36761. uniforms.push("vInverseScreenSize");
  36762. uniforms.push("vignetteSettings1");
  36763. uniforms.push("vignetteSettings2");
  36764. }
  36765. if (defines.COLORCURVES) {
  36766. BABYLON.ColorCurves.PrepareUniforms(uniforms);
  36767. }
  36768. };
  36769. /**
  36770. * Prepare the list of samplers associated with the Image Processing effects.
  36771. * @param uniformsList The list of uniforms used in the effect
  36772. * @param defines the list of defines currently in use
  36773. */
  36774. ImageProcessingConfiguration.PrepareSamplers = function (samplersList, defines) {
  36775. if (defines.COLORGRADING) {
  36776. samplersList.push("txColorTransform");
  36777. }
  36778. };
  36779. /**
  36780. * Prepare the list of defines associated to the shader.
  36781. * @param defines the list of defines to complete
  36782. */
  36783. ImageProcessingConfiguration.prototype.prepareDefines = function (defines, forPostProcess) {
  36784. if (forPostProcess === void 0) { forPostProcess = false; }
  36785. if (forPostProcess !== this.applyByPostProcess || !this._isEnabled) {
  36786. defines.VIGNETTE = false;
  36787. defines.TONEMAPPING = false;
  36788. defines.CONTRAST = false;
  36789. defines.EXPOSURE = false;
  36790. defines.COLORCURVES = false;
  36791. defines.COLORGRADING = false;
  36792. defines.COLORGRADING3D = false;
  36793. defines.IMAGEPROCESSING = false;
  36794. defines.IMAGEPROCESSINGPOSTPROCESS = this.applyByPostProcess && this._isEnabled;
  36795. return;
  36796. }
  36797. defines.VIGNETTE = this.vignetteEnabled;
  36798. defines.VIGNETTEBLENDMODEMULTIPLY = (this.vignetteBlendMode === ImageProcessingConfiguration._VIGNETTEMODE_MULTIPLY);
  36799. defines.VIGNETTEBLENDMODEOPAQUE = !defines.VIGNETTEBLENDMODEMULTIPLY;
  36800. defines.TONEMAPPING = this.toneMappingEnabled;
  36801. defines.CONTRAST = (this.contrast !== 1.0);
  36802. defines.EXPOSURE = (this.exposure !== 1.0);
  36803. defines.COLORCURVES = (this.colorCurvesEnabled && !!this.colorCurves);
  36804. defines.COLORGRADING = (this.colorGradingEnabled && !!this.colorGradingTexture);
  36805. if (defines.COLORGRADING) {
  36806. defines.COLORGRADING3D = this.colorGradingTexture.is3D;
  36807. }
  36808. else {
  36809. defines.COLORGRADING3D = false;
  36810. }
  36811. defines.SAMPLER3DGREENDEPTH = this.colorGradingWithGreenDepth;
  36812. defines.SAMPLER3DBGRMAP = this.colorGradingBGR;
  36813. defines.IMAGEPROCESSINGPOSTPROCESS = this.applyByPostProcess;
  36814. defines.IMAGEPROCESSING = defines.VIGNETTE || defines.TONEMAPPING || defines.CONTRAST || defines.EXPOSURE || defines.COLORCURVES || defines.COLORGRADING;
  36815. };
  36816. /**
  36817. * Returns true if all the image processing information are ready.
  36818. */
  36819. ImageProcessingConfiguration.prototype.isReady = function () {
  36820. // Color Grading texure can not be none blocking.
  36821. return !this.colorGradingEnabled || !this.colorGradingTexture || this.colorGradingTexture.isReady();
  36822. };
  36823. /**
  36824. * Binds the image processing to the shader.
  36825. * @param effect The effect to bind to
  36826. */
  36827. ImageProcessingConfiguration.prototype.bind = function (effect, aspectRatio) {
  36828. if (aspectRatio === void 0) { aspectRatio = 1; }
  36829. // Color Curves
  36830. if (this._colorCurvesEnabled && this.colorCurves) {
  36831. BABYLON.ColorCurves.Bind(this.colorCurves, effect);
  36832. }
  36833. // Vignette
  36834. if (this._vignetteEnabled) {
  36835. var inverseWidth = 1 / effect.getEngine().getRenderWidth();
  36836. var inverseHeight = 1 / effect.getEngine().getRenderHeight();
  36837. effect.setFloat2("vInverseScreenSize", inverseWidth, inverseHeight);
  36838. var vignetteScaleY = Math.tan(this.vignetteCameraFov * 0.5);
  36839. var vignetteScaleX = vignetteScaleY * aspectRatio;
  36840. var vignetteScaleGeometricMean = Math.sqrt(vignetteScaleX * vignetteScaleY);
  36841. vignetteScaleX = BABYLON.Tools.Mix(vignetteScaleX, vignetteScaleGeometricMean, this.vignetteStretch);
  36842. vignetteScaleY = BABYLON.Tools.Mix(vignetteScaleY, vignetteScaleGeometricMean, this.vignetteStretch);
  36843. effect.setFloat4("vignetteSettings1", vignetteScaleX, vignetteScaleY, -vignetteScaleX * this.vignetteCentreX, -vignetteScaleY * this.vignetteCentreY);
  36844. var vignettePower = -2.0 * this.vignetteWeight;
  36845. effect.setFloat4("vignetteSettings2", this.vignetteColor.r, this.vignetteColor.g, this.vignetteColor.b, vignettePower);
  36846. }
  36847. // Exposure
  36848. effect.setFloat("exposureLinear", this.exposure);
  36849. // Contrast
  36850. effect.setFloat("contrast", this.contrast);
  36851. // Color transform settings
  36852. if (this.colorGradingTexture) {
  36853. effect.setTexture("txColorTransform", this.colorGradingTexture);
  36854. var textureSize = this.colorGradingTexture.getSize().height;
  36855. effect.setFloat4("colorTransformSettings", (textureSize - 1) / textureSize, // textureScale
  36856. 0.5 / textureSize, // textureOffset
  36857. textureSize, // textureSize
  36858. this.colorGradingTexture.level // weight
  36859. );
  36860. }
  36861. };
  36862. /**
  36863. * Clones the current image processing instance.
  36864. * @return The cloned image processing
  36865. */
  36866. ImageProcessingConfiguration.prototype.clone = function () {
  36867. return BABYLON.SerializationHelper.Clone(function () { return new ImageProcessingConfiguration(); }, this);
  36868. };
  36869. /**
  36870. * Serializes the current image processing instance to a json representation.
  36871. * @return a JSON representation
  36872. */
  36873. ImageProcessingConfiguration.prototype.serialize = function () {
  36874. return BABYLON.SerializationHelper.Serialize(this);
  36875. };
  36876. /**
  36877. * Parses the image processing from a json representation.
  36878. * @param source the JSON source to parse
  36879. * @return The parsed image processing
  36880. */
  36881. ImageProcessingConfiguration.Parse = function (source) {
  36882. return BABYLON.SerializationHelper.Parse(function () { return new ImageProcessingConfiguration(); }, source, null, null);
  36883. };
  36884. Object.defineProperty(ImageProcessingConfiguration, "VIGNETTEMODE_MULTIPLY", {
  36885. /**
  36886. * Used to apply the vignette as a mix with the pixel color.
  36887. */
  36888. get: function () {
  36889. return this._VIGNETTEMODE_MULTIPLY;
  36890. },
  36891. enumerable: true,
  36892. configurable: true
  36893. });
  36894. Object.defineProperty(ImageProcessingConfiguration, "VIGNETTEMODE_OPAQUE", {
  36895. /**
  36896. * Used to apply the vignette as a replacement of the pixel color.
  36897. */
  36898. get: function () {
  36899. return this._VIGNETTEMODE_OPAQUE;
  36900. },
  36901. enumerable: true,
  36902. configurable: true
  36903. });
  36904. // Static constants associated to the image processing.
  36905. ImageProcessingConfiguration._VIGNETTEMODE_MULTIPLY = 0;
  36906. ImageProcessingConfiguration._VIGNETTEMODE_OPAQUE = 1;
  36907. __decorate([
  36908. BABYLON.serializeAsColorCurves()
  36909. ], ImageProcessingConfiguration.prototype, "colorCurves", void 0);
  36910. __decorate([
  36911. BABYLON.serialize()
  36912. ], ImageProcessingConfiguration.prototype, "_colorCurvesEnabled", void 0);
  36913. __decorate([
  36914. BABYLON.serializeAsTexture()
  36915. ], ImageProcessingConfiguration.prototype, "colorGradingTexture", void 0);
  36916. __decorate([
  36917. BABYLON.serialize()
  36918. ], ImageProcessingConfiguration.prototype, "_colorGradingEnabled", void 0);
  36919. __decorate([
  36920. BABYLON.serialize()
  36921. ], ImageProcessingConfiguration.prototype, "_colorGradingWithGreenDepth", void 0);
  36922. __decorate([
  36923. BABYLON.serialize()
  36924. ], ImageProcessingConfiguration.prototype, "_colorGradingBGR", void 0);
  36925. __decorate([
  36926. BABYLON.serialize()
  36927. ], ImageProcessingConfiguration.prototype, "_exposure", void 0);
  36928. __decorate([
  36929. BABYLON.serialize()
  36930. ], ImageProcessingConfiguration.prototype, "_toneMappingEnabled", void 0);
  36931. __decorate([
  36932. BABYLON.serialize()
  36933. ], ImageProcessingConfiguration.prototype, "_contrast", void 0);
  36934. __decorate([
  36935. BABYLON.serialize()
  36936. ], ImageProcessingConfiguration.prototype, "vignetteStretch", void 0);
  36937. __decorate([
  36938. BABYLON.serialize()
  36939. ], ImageProcessingConfiguration.prototype, "vignetteCentreX", void 0);
  36940. __decorate([
  36941. BABYLON.serialize()
  36942. ], ImageProcessingConfiguration.prototype, "vignetteCentreY", void 0);
  36943. __decorate([
  36944. BABYLON.serialize()
  36945. ], ImageProcessingConfiguration.prototype, "vignetteWeight", void 0);
  36946. __decorate([
  36947. BABYLON.serializeAsColor4()
  36948. ], ImageProcessingConfiguration.prototype, "vignetteColor", void 0);
  36949. __decorate([
  36950. BABYLON.serialize()
  36951. ], ImageProcessingConfiguration.prototype, "vignetteCameraFov", void 0);
  36952. __decorate([
  36953. BABYLON.serialize()
  36954. ], ImageProcessingConfiguration.prototype, "_vignetteBlendMode", void 0);
  36955. __decorate([
  36956. BABYLON.serialize()
  36957. ], ImageProcessingConfiguration.prototype, "_vignetteEnabled", void 0);
  36958. __decorate([
  36959. BABYLON.serialize()
  36960. ], ImageProcessingConfiguration.prototype, "_applyByPostProcess", void 0);
  36961. __decorate([
  36962. BABYLON.serialize()
  36963. ], ImageProcessingConfiguration.prototype, "_isEnabled", void 0);
  36964. return ImageProcessingConfiguration;
  36965. }());
  36966. BABYLON.ImageProcessingConfiguration = ImageProcessingConfiguration;
  36967. })(BABYLON || (BABYLON = {}));
  36968. //# sourceMappingURL=babylon.imageProcessingConfiguration.js.map
  36969. var BABYLON;
  36970. (function (BABYLON) {
  36971. /**
  36972. * This represents a color grading texture. This acts as a lookup table LUT, useful during post process
  36973. * It can help converting any input color in a desired output one. This can then be used to create effects
  36974. * from sepia, black and white to sixties or futuristic rendering...
  36975. *
  36976. * The only supported format is currently 3dl.
  36977. * More information on LUT: https://en.wikipedia.org/wiki/3D_lookup_table/
  36978. */
  36979. var ColorGradingTexture = /** @class */ (function (_super) {
  36980. __extends(ColorGradingTexture, _super);
  36981. /**
  36982. * Instantiates a ColorGradingTexture from the following parameters.
  36983. *
  36984. * @param url The location of the color gradind data (currently only supporting 3dl)
  36985. * @param scene The scene the texture will be used in
  36986. */
  36987. function ColorGradingTexture(url, scene) {
  36988. var _this = _super.call(this, scene) || this;
  36989. if (!url) {
  36990. return _this;
  36991. }
  36992. _this._engine = scene.getEngine();
  36993. _this._textureMatrix = BABYLON.Matrix.Identity();
  36994. _this.name = url;
  36995. _this.url = url;
  36996. _this.hasAlpha = false;
  36997. _this.isCube = false;
  36998. _this.is3D = _this._engine.webGLVersion > 1;
  36999. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  37000. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  37001. _this.wrapR = BABYLON.Texture.CLAMP_ADDRESSMODE;
  37002. _this.anisotropicFilteringLevel = 1;
  37003. _this._texture = _this._getFromCache(url, true);
  37004. if (!_this._texture) {
  37005. if (!scene.useDelayedTextureLoading) {
  37006. _this.loadTexture();
  37007. }
  37008. else {
  37009. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  37010. }
  37011. }
  37012. return _this;
  37013. }
  37014. /**
  37015. * Returns the texture matrix used in most of the material.
  37016. * This is not used in color grading but keep for troubleshooting purpose (easily swap diffuse by colorgrading to look in).
  37017. */
  37018. ColorGradingTexture.prototype.getTextureMatrix = function () {
  37019. return this._textureMatrix;
  37020. };
  37021. /**
  37022. * Occurs when the file being loaded is a .3dl LUT file.
  37023. */
  37024. ColorGradingTexture.prototype.load3dlTexture = function () {
  37025. var engine = this._engine;
  37026. var texture;
  37027. if (engine.webGLVersion === 1) {
  37028. texture = engine.createRawTexture(null, 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  37029. }
  37030. else {
  37031. texture = engine.createRawTexture3D(null, 1, 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  37032. }
  37033. this._texture = texture;
  37034. var callback = function (text) {
  37035. if (typeof text !== "string") {
  37036. return;
  37037. }
  37038. var data = null;
  37039. var tempData = null;
  37040. var line;
  37041. var lines = text.split('\n');
  37042. var size = 0, pixelIndexW = 0, pixelIndexH = 0, pixelIndexSlice = 0;
  37043. var maxColor = 0;
  37044. for (var i = 0; i < lines.length; i++) {
  37045. line = lines[i];
  37046. if (!ColorGradingTexture._noneEmptyLineRegex.test(line))
  37047. continue;
  37048. if (line.indexOf('#') === 0)
  37049. continue;
  37050. var words = line.split(" ");
  37051. if (size === 0) {
  37052. // Number of space + one
  37053. size = words.length;
  37054. data = new Uint8Array(size * size * size * 4); // volume texture of side size and rgb 8
  37055. tempData = new Float32Array(size * size * size * 4);
  37056. continue;
  37057. }
  37058. if (size != 0) {
  37059. var r = Math.max(parseInt(words[0]), 0);
  37060. var g = Math.max(parseInt(words[1]), 0);
  37061. var b = Math.max(parseInt(words[2]), 0);
  37062. maxColor = Math.max(r, maxColor);
  37063. maxColor = Math.max(g, maxColor);
  37064. maxColor = Math.max(b, maxColor);
  37065. var pixelStorageIndex = (pixelIndexW + pixelIndexSlice * size + pixelIndexH * size * size) * 4;
  37066. if (tempData) {
  37067. tempData[pixelStorageIndex + 0] = r;
  37068. tempData[pixelStorageIndex + 1] = g;
  37069. tempData[pixelStorageIndex + 2] = b;
  37070. }
  37071. pixelIndexSlice++;
  37072. if (pixelIndexSlice % size == 0) {
  37073. pixelIndexH++;
  37074. pixelIndexSlice = 0;
  37075. if (pixelIndexH % size == 0) {
  37076. pixelIndexW++;
  37077. pixelIndexH = 0;
  37078. }
  37079. }
  37080. }
  37081. }
  37082. if (tempData && data) {
  37083. for (var i = 0; i < tempData.length; i++) {
  37084. if (i > 0 && (i + 1) % 4 === 0) {
  37085. data[i] = 255;
  37086. }
  37087. else {
  37088. var value = tempData[i];
  37089. data[i] = (value / maxColor * 255);
  37090. }
  37091. }
  37092. }
  37093. if (texture.is3D) {
  37094. texture.updateSize(size, size, size);
  37095. engine.updateRawTexture3D(texture, data, BABYLON.Engine.TEXTUREFORMAT_RGBA, false);
  37096. }
  37097. else {
  37098. texture.updateSize(size * size, size);
  37099. engine.updateRawTexture(texture, data, BABYLON.Engine.TEXTUREFORMAT_RGBA, false);
  37100. }
  37101. };
  37102. var scene = this.getScene();
  37103. if (scene) {
  37104. scene._loadFile(this.url, callback);
  37105. }
  37106. else {
  37107. this._engine._loadFile(this.url, callback);
  37108. }
  37109. return this._texture;
  37110. };
  37111. /**
  37112. * Starts the loading process of the texture.
  37113. */
  37114. ColorGradingTexture.prototype.loadTexture = function () {
  37115. if (this.url && this.url.toLocaleLowerCase().indexOf(".3dl") == (this.url.length - 4)) {
  37116. this.load3dlTexture();
  37117. }
  37118. };
  37119. /**
  37120. * Clones the color gradind texture.
  37121. */
  37122. ColorGradingTexture.prototype.clone = function () {
  37123. var newTexture = new ColorGradingTexture(this.url, this.getScene());
  37124. // Base texture
  37125. newTexture.level = this.level;
  37126. return newTexture;
  37127. };
  37128. /**
  37129. * Called during delayed load for textures.
  37130. */
  37131. ColorGradingTexture.prototype.delayLoad = function () {
  37132. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  37133. return;
  37134. }
  37135. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  37136. this._texture = this._getFromCache(this.url, true);
  37137. if (!this._texture) {
  37138. this.loadTexture();
  37139. }
  37140. };
  37141. /**
  37142. * Parses a color grading texture serialized by Babylon.
  37143. * @param parsedTexture The texture information being parsedTexture
  37144. * @param scene The scene to load the texture in
  37145. * @param rootUrl The root url of the data assets to load
  37146. * @return A color gradind texture
  37147. */
  37148. ColorGradingTexture.Parse = function (parsedTexture, scene, rootUrl) {
  37149. var texture = null;
  37150. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  37151. texture = new ColorGradingTexture(parsedTexture.name, scene);
  37152. texture.name = parsedTexture.name;
  37153. texture.level = parsedTexture.level;
  37154. }
  37155. return texture;
  37156. };
  37157. /**
  37158. * Serializes the LUT texture to json format.
  37159. */
  37160. ColorGradingTexture.prototype.serialize = function () {
  37161. if (!this.name) {
  37162. return null;
  37163. }
  37164. var serializationObject = {};
  37165. serializationObject.name = this.name;
  37166. serializationObject.level = this.level;
  37167. serializationObject.customType = "BABYLON.ColorGradingTexture";
  37168. return serializationObject;
  37169. };
  37170. /**
  37171. * Empty line regex stored for GC.
  37172. */
  37173. ColorGradingTexture._noneEmptyLineRegex = /\S+/;
  37174. return ColorGradingTexture;
  37175. }(BABYLON.BaseTexture));
  37176. BABYLON.ColorGradingTexture = ColorGradingTexture;
  37177. })(BABYLON || (BABYLON = {}));
  37178. //# sourceMappingURL=babylon.colorGradingTexture.js.map
  37179. var BABYLON;
  37180. (function (BABYLON) {
  37181. /**
  37182. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  37183. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  37184. * 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;
  37185. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  37186. */
  37187. var ColorCurves = /** @class */ (function () {
  37188. function ColorCurves() {
  37189. this._dirty = true;
  37190. this._tempColor = new BABYLON.Color4(0, 0, 0, 0);
  37191. this._globalCurve = new BABYLON.Color4(0, 0, 0, 0);
  37192. this._highlightsCurve = new BABYLON.Color4(0, 0, 0, 0);
  37193. this._midtonesCurve = new BABYLON.Color4(0, 0, 0, 0);
  37194. this._shadowsCurve = new BABYLON.Color4(0, 0, 0, 0);
  37195. this._positiveCurve = new BABYLON.Color4(0, 0, 0, 0);
  37196. this._negativeCurve = new BABYLON.Color4(0, 0, 0, 0);
  37197. this._globalHue = 30;
  37198. this._globalDensity = 0;
  37199. this._globalSaturation = 0;
  37200. this._globalExposure = 0;
  37201. this._highlightsHue = 30;
  37202. this._highlightsDensity = 0;
  37203. this._highlightsSaturation = 0;
  37204. this._highlightsExposure = 0;
  37205. this._midtonesHue = 30;
  37206. this._midtonesDensity = 0;
  37207. this._midtonesSaturation = 0;
  37208. this._midtonesExposure = 0;
  37209. this._shadowsHue = 30;
  37210. this._shadowsDensity = 0;
  37211. this._shadowsSaturation = 0;
  37212. this._shadowsExposure = 0;
  37213. }
  37214. Object.defineProperty(ColorCurves.prototype, "globalHue", {
  37215. /**
  37216. * Gets the global Hue value.
  37217. * 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).
  37218. */
  37219. get: function () {
  37220. return this._globalHue;
  37221. },
  37222. /**
  37223. * Sets the global Hue value.
  37224. * 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).
  37225. */
  37226. set: function (value) {
  37227. this._globalHue = value;
  37228. this._dirty = true;
  37229. },
  37230. enumerable: true,
  37231. configurable: true
  37232. });
  37233. Object.defineProperty(ColorCurves.prototype, "globalDensity", {
  37234. /**
  37235. * Gets the global Density value.
  37236. * 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.
  37237. * Values less than zero provide a filter of opposite hue.
  37238. */
  37239. get: function () {
  37240. return this._globalDensity;
  37241. },
  37242. /**
  37243. * Sets the global Density value.
  37244. * 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.
  37245. * Values less than zero provide a filter of opposite hue.
  37246. */
  37247. set: function (value) {
  37248. this._globalDensity = value;
  37249. this._dirty = true;
  37250. },
  37251. enumerable: true,
  37252. configurable: true
  37253. });
  37254. Object.defineProperty(ColorCurves.prototype, "globalSaturation", {
  37255. /**
  37256. * Gets the global Saturation value.
  37257. * 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.
  37258. */
  37259. get: function () {
  37260. return this._globalSaturation;
  37261. },
  37262. /**
  37263. * Sets the global Saturation value.
  37264. * 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.
  37265. */
  37266. set: function (value) {
  37267. this._globalSaturation = value;
  37268. this._dirty = true;
  37269. },
  37270. enumerable: true,
  37271. configurable: true
  37272. });
  37273. Object.defineProperty(ColorCurves.prototype, "highlightsHue", {
  37274. /**
  37275. * Gets the highlights Hue value.
  37276. * 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).
  37277. */
  37278. get: function () {
  37279. return this._highlightsHue;
  37280. },
  37281. /**
  37282. * Sets the highlights Hue value.
  37283. * 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).
  37284. */
  37285. set: function (value) {
  37286. this._highlightsHue = value;
  37287. this._dirty = true;
  37288. },
  37289. enumerable: true,
  37290. configurable: true
  37291. });
  37292. Object.defineProperty(ColorCurves.prototype, "highlightsDensity", {
  37293. /**
  37294. * Gets the highlights Density value.
  37295. * 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.
  37296. * Values less than zero provide a filter of opposite hue.
  37297. */
  37298. get: function () {
  37299. return this._highlightsDensity;
  37300. },
  37301. /**
  37302. * Sets the highlights Density value.
  37303. * 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.
  37304. * Values less than zero provide a filter of opposite hue.
  37305. */
  37306. set: function (value) {
  37307. this._highlightsDensity = value;
  37308. this._dirty = true;
  37309. },
  37310. enumerable: true,
  37311. configurable: true
  37312. });
  37313. Object.defineProperty(ColorCurves.prototype, "highlightsSaturation", {
  37314. /**
  37315. * Gets the highlights Saturation value.
  37316. * 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.
  37317. */
  37318. get: function () {
  37319. return this._highlightsSaturation;
  37320. },
  37321. /**
  37322. * Sets the highlights Saturation value.
  37323. * 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.
  37324. */
  37325. set: function (value) {
  37326. this._highlightsSaturation = value;
  37327. this._dirty = true;
  37328. },
  37329. enumerable: true,
  37330. configurable: true
  37331. });
  37332. Object.defineProperty(ColorCurves.prototype, "highlightsExposure", {
  37333. /**
  37334. * Gets the highlights Exposure value.
  37335. * 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.
  37336. */
  37337. get: function () {
  37338. return this._highlightsExposure;
  37339. },
  37340. /**
  37341. * Sets the highlights Exposure value.
  37342. * 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.
  37343. */
  37344. set: function (value) {
  37345. this._highlightsExposure = value;
  37346. this._dirty = true;
  37347. },
  37348. enumerable: true,
  37349. configurable: true
  37350. });
  37351. Object.defineProperty(ColorCurves.prototype, "midtonesHue", {
  37352. /**
  37353. * Gets the midtones Hue value.
  37354. * 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).
  37355. */
  37356. get: function () {
  37357. return this._midtonesHue;
  37358. },
  37359. /**
  37360. * Sets the midtones Hue value.
  37361. * 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).
  37362. */
  37363. set: function (value) {
  37364. this._midtonesHue = value;
  37365. this._dirty = true;
  37366. },
  37367. enumerable: true,
  37368. configurable: true
  37369. });
  37370. Object.defineProperty(ColorCurves.prototype, "midtonesDensity", {
  37371. /**
  37372. * Gets the midtones Density value.
  37373. * 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.
  37374. * Values less than zero provide a filter of opposite hue.
  37375. */
  37376. get: function () {
  37377. return this._midtonesDensity;
  37378. },
  37379. /**
  37380. * Sets the midtones Density value.
  37381. * 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.
  37382. * Values less than zero provide a filter of opposite hue.
  37383. */
  37384. set: function (value) {
  37385. this._midtonesDensity = value;
  37386. this._dirty = true;
  37387. },
  37388. enumerable: true,
  37389. configurable: true
  37390. });
  37391. Object.defineProperty(ColorCurves.prototype, "midtonesSaturation", {
  37392. /**
  37393. * Gets the midtones Saturation value.
  37394. * 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.
  37395. */
  37396. get: function () {
  37397. return this._midtonesSaturation;
  37398. },
  37399. /**
  37400. * Sets the midtones Saturation value.
  37401. * 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.
  37402. */
  37403. set: function (value) {
  37404. this._midtonesSaturation = value;
  37405. this._dirty = true;
  37406. },
  37407. enumerable: true,
  37408. configurable: true
  37409. });
  37410. Object.defineProperty(ColorCurves.prototype, "midtonesExposure", {
  37411. /**
  37412. * Gets the midtones Exposure value.
  37413. * 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.
  37414. */
  37415. get: function () {
  37416. return this._midtonesExposure;
  37417. },
  37418. /**
  37419. * Sets the midtones Exposure value.
  37420. * 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.
  37421. */
  37422. set: function (value) {
  37423. this._midtonesExposure = value;
  37424. this._dirty = true;
  37425. },
  37426. enumerable: true,
  37427. configurable: true
  37428. });
  37429. Object.defineProperty(ColorCurves.prototype, "shadowsHue", {
  37430. /**
  37431. * Gets the shadows Hue value.
  37432. * 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).
  37433. */
  37434. get: function () {
  37435. return this._shadowsHue;
  37436. },
  37437. /**
  37438. * Sets the shadows Hue value.
  37439. * 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).
  37440. */
  37441. set: function (value) {
  37442. this._shadowsHue = value;
  37443. this._dirty = true;
  37444. },
  37445. enumerable: true,
  37446. configurable: true
  37447. });
  37448. Object.defineProperty(ColorCurves.prototype, "shadowsDensity", {
  37449. /**
  37450. * Gets the shadows Density value.
  37451. * 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.
  37452. * Values less than zero provide a filter of opposite hue.
  37453. */
  37454. get: function () {
  37455. return this._shadowsDensity;
  37456. },
  37457. /**
  37458. * Sets the shadows Density value.
  37459. * 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.
  37460. * Values less than zero provide a filter of opposite hue.
  37461. */
  37462. set: function (value) {
  37463. this._shadowsDensity = value;
  37464. this._dirty = true;
  37465. },
  37466. enumerable: true,
  37467. configurable: true
  37468. });
  37469. Object.defineProperty(ColorCurves.prototype, "shadowsSaturation", {
  37470. /**
  37471. * Gets the shadows Saturation value.
  37472. * 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.
  37473. */
  37474. get: function () {
  37475. return this._shadowsSaturation;
  37476. },
  37477. /**
  37478. * Sets the shadows Saturation value.
  37479. * 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.
  37480. */
  37481. set: function (value) {
  37482. this._shadowsSaturation = value;
  37483. this._dirty = true;
  37484. },
  37485. enumerable: true,
  37486. configurable: true
  37487. });
  37488. Object.defineProperty(ColorCurves.prototype, "shadowsExposure", {
  37489. /**
  37490. * Gets the shadows Exposure value.
  37491. * 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.
  37492. */
  37493. get: function () {
  37494. return this._shadowsExposure;
  37495. },
  37496. /**
  37497. * Sets the shadows Exposure value.
  37498. * 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.
  37499. */
  37500. set: function (value) {
  37501. this._shadowsExposure = value;
  37502. this._dirty = true;
  37503. },
  37504. enumerable: true,
  37505. configurable: true
  37506. });
  37507. ColorCurves.prototype.getClassName = function () {
  37508. return "ColorCurves";
  37509. };
  37510. /**
  37511. * Binds the color curves to the shader.
  37512. * @param colorCurves The color curve to bind
  37513. * @param effect The effect to bind to
  37514. */
  37515. ColorCurves.Bind = function (colorCurves, effect, positiveUniform, neutralUniform, negativeUniform) {
  37516. if (positiveUniform === void 0) { positiveUniform = "vCameraColorCurvePositive"; }
  37517. if (neutralUniform === void 0) { neutralUniform = "vCameraColorCurveNeutral"; }
  37518. if (negativeUniform === void 0) { negativeUniform = "vCameraColorCurveNegative"; }
  37519. if (colorCurves._dirty) {
  37520. colorCurves._dirty = false;
  37521. // Fill in global info.
  37522. colorCurves.getColorGradingDataToRef(colorCurves._globalHue, colorCurves._globalDensity, colorCurves._globalSaturation, colorCurves._globalExposure, colorCurves._globalCurve);
  37523. // Compute highlights info.
  37524. colorCurves.getColorGradingDataToRef(colorCurves._highlightsHue, colorCurves._highlightsDensity, colorCurves._highlightsSaturation, colorCurves._highlightsExposure, colorCurves._tempColor);
  37525. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._highlightsCurve);
  37526. // Compute midtones info.
  37527. colorCurves.getColorGradingDataToRef(colorCurves._midtonesHue, colorCurves._midtonesDensity, colorCurves._midtonesSaturation, colorCurves._midtonesExposure, colorCurves._tempColor);
  37528. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._midtonesCurve);
  37529. // Compute shadows info.
  37530. colorCurves.getColorGradingDataToRef(colorCurves._shadowsHue, colorCurves._shadowsDensity, colorCurves._shadowsSaturation, colorCurves._shadowsExposure, colorCurves._tempColor);
  37531. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._shadowsCurve);
  37532. // Compute deltas (neutral is midtones).
  37533. colorCurves._highlightsCurve.subtractToRef(colorCurves._midtonesCurve, colorCurves._positiveCurve);
  37534. colorCurves._midtonesCurve.subtractToRef(colorCurves._shadowsCurve, colorCurves._negativeCurve);
  37535. }
  37536. if (effect) {
  37537. effect.setFloat4(positiveUniform, colorCurves._positiveCurve.r, colorCurves._positiveCurve.g, colorCurves._positiveCurve.b, colorCurves._positiveCurve.a);
  37538. effect.setFloat4(neutralUniform, colorCurves._midtonesCurve.r, colorCurves._midtonesCurve.g, colorCurves._midtonesCurve.b, colorCurves._midtonesCurve.a);
  37539. effect.setFloat4(negativeUniform, colorCurves._negativeCurve.r, colorCurves._negativeCurve.g, colorCurves._negativeCurve.b, colorCurves._negativeCurve.a);
  37540. }
  37541. };
  37542. /**
  37543. * Prepare the list of uniforms associated with the ColorCurves effects.
  37544. * @param uniformsList The list of uniforms used in the effect
  37545. */
  37546. ColorCurves.PrepareUniforms = function (uniformsList) {
  37547. uniformsList.push("vCameraColorCurveNeutral", "vCameraColorCurvePositive", "vCameraColorCurveNegative");
  37548. };
  37549. /**
  37550. * Returns color grading data based on a hue, density, saturation and exposure value.
  37551. * @param filterHue The hue of the color filter.
  37552. * @param filterDensity The density of the color filter.
  37553. * @param saturation The saturation.
  37554. * @param exposure The exposure.
  37555. * @param result The result data container.
  37556. */
  37557. ColorCurves.prototype.getColorGradingDataToRef = function (hue, density, saturation, exposure, result) {
  37558. if (hue == null) {
  37559. return;
  37560. }
  37561. hue = ColorCurves.clamp(hue, 0, 360);
  37562. density = ColorCurves.clamp(density, -100, 100);
  37563. saturation = ColorCurves.clamp(saturation, -100, 100);
  37564. exposure = ColorCurves.clamp(exposure, -100, 100);
  37565. // Remap the slider/config filter density with non-linear mapping and also scale by half
  37566. // so that the maximum filter density is only 50% control. This provides fine control
  37567. // for small values and reasonable range.
  37568. density = ColorCurves.applyColorGradingSliderNonlinear(density);
  37569. density *= 0.5;
  37570. exposure = ColorCurves.applyColorGradingSliderNonlinear(exposure);
  37571. if (density < 0) {
  37572. density *= -1;
  37573. hue = (hue + 180) % 360;
  37574. }
  37575. ColorCurves.fromHSBToRef(hue, density, 50 + 0.25 * exposure, result);
  37576. result.scaleToRef(2, result);
  37577. result.a = 1 + 0.01 * saturation;
  37578. };
  37579. /**
  37580. * Takes an input slider value and returns an adjusted value that provides extra control near the centre.
  37581. * @param value The input slider value in range [-100,100].
  37582. * @returns Adjusted value.
  37583. */
  37584. ColorCurves.applyColorGradingSliderNonlinear = function (value) {
  37585. value /= 100;
  37586. var x = Math.abs(value);
  37587. x = Math.pow(x, 2);
  37588. if (value < 0) {
  37589. x *= -1;
  37590. }
  37591. x *= 100;
  37592. return x;
  37593. };
  37594. /**
  37595. * Returns an RGBA Color4 based on Hue, Saturation and Brightness (also referred to as value, HSV).
  37596. * @param hue The hue (H) input.
  37597. * @param saturation The saturation (S) input.
  37598. * @param brightness The brightness (B) input.
  37599. * @result An RGBA color represented as Vector4.
  37600. */
  37601. ColorCurves.fromHSBToRef = function (hue, saturation, brightness, result) {
  37602. var h = ColorCurves.clamp(hue, 0, 360);
  37603. var s = ColorCurves.clamp(saturation / 100, 0, 1);
  37604. var v = ColorCurves.clamp(brightness / 100, 0, 1);
  37605. if (s === 0) {
  37606. result.r = v;
  37607. result.g = v;
  37608. result.b = v;
  37609. }
  37610. else {
  37611. // sector 0 to 5
  37612. h /= 60;
  37613. var i = Math.floor(h);
  37614. // fractional part of h
  37615. var f = h - i;
  37616. var p = v * (1 - s);
  37617. var q = v * (1 - s * f);
  37618. var t = v * (1 - s * (1 - f));
  37619. switch (i) {
  37620. case 0:
  37621. result.r = v;
  37622. result.g = t;
  37623. result.b = p;
  37624. break;
  37625. case 1:
  37626. result.r = q;
  37627. result.g = v;
  37628. result.b = p;
  37629. break;
  37630. case 2:
  37631. result.r = p;
  37632. result.g = v;
  37633. result.b = t;
  37634. break;
  37635. case 3:
  37636. result.r = p;
  37637. result.g = q;
  37638. result.b = v;
  37639. break;
  37640. case 4:
  37641. result.r = t;
  37642. result.g = p;
  37643. result.b = v;
  37644. break;
  37645. default:// case 5:
  37646. result.r = v;
  37647. result.g = p;
  37648. result.b = q;
  37649. break;
  37650. }
  37651. }
  37652. result.a = 1;
  37653. };
  37654. /**
  37655. * Returns a value clamped between min and max
  37656. * @param value The value to clamp
  37657. * @param min The minimum of value
  37658. * @param max The maximum of value
  37659. * @returns The clamped value.
  37660. */
  37661. ColorCurves.clamp = function (value, min, max) {
  37662. return Math.min(Math.max(value, min), max);
  37663. };
  37664. /**
  37665. * Clones the current color curve instance.
  37666. * @return The cloned curves
  37667. */
  37668. ColorCurves.prototype.clone = function () {
  37669. return BABYLON.SerializationHelper.Clone(function () { return new ColorCurves(); }, this);
  37670. };
  37671. /**
  37672. * Serializes the current color curve instance to a json representation.
  37673. * @return a JSON representation
  37674. */
  37675. ColorCurves.prototype.serialize = function () {
  37676. return BABYLON.SerializationHelper.Serialize(this);
  37677. };
  37678. /**
  37679. * Parses the color curve from a json representation.
  37680. * @param source the JSON source to parse
  37681. * @return The parsed curves
  37682. */
  37683. ColorCurves.Parse = function (source) {
  37684. return BABYLON.SerializationHelper.Parse(function () { return new ColorCurves(); }, source, null, null);
  37685. };
  37686. __decorate([
  37687. BABYLON.serialize()
  37688. ], ColorCurves.prototype, "_globalHue", void 0);
  37689. __decorate([
  37690. BABYLON.serialize()
  37691. ], ColorCurves.prototype, "_globalDensity", void 0);
  37692. __decorate([
  37693. BABYLON.serialize()
  37694. ], ColorCurves.prototype, "_globalSaturation", void 0);
  37695. __decorate([
  37696. BABYLON.serialize()
  37697. ], ColorCurves.prototype, "_globalExposure", void 0);
  37698. __decorate([
  37699. BABYLON.serialize()
  37700. ], ColorCurves.prototype, "_highlightsHue", void 0);
  37701. __decorate([
  37702. BABYLON.serialize()
  37703. ], ColorCurves.prototype, "_highlightsDensity", void 0);
  37704. __decorate([
  37705. BABYLON.serialize()
  37706. ], ColorCurves.prototype, "_highlightsSaturation", void 0);
  37707. __decorate([
  37708. BABYLON.serialize()
  37709. ], ColorCurves.prototype, "_highlightsExposure", void 0);
  37710. __decorate([
  37711. BABYLON.serialize()
  37712. ], ColorCurves.prototype, "_midtonesHue", void 0);
  37713. __decorate([
  37714. BABYLON.serialize()
  37715. ], ColorCurves.prototype, "_midtonesDensity", void 0);
  37716. __decorate([
  37717. BABYLON.serialize()
  37718. ], ColorCurves.prototype, "_midtonesSaturation", void 0);
  37719. __decorate([
  37720. BABYLON.serialize()
  37721. ], ColorCurves.prototype, "_midtonesExposure", void 0);
  37722. return ColorCurves;
  37723. }());
  37724. BABYLON.ColorCurves = ColorCurves;
  37725. })(BABYLON || (BABYLON = {}));
  37726. //# sourceMappingURL=babylon.colorCurves.js.map
  37727. //# sourceMappingURL=babylon.behavior.js.map
  37728. var BABYLON;
  37729. (function (BABYLON) {
  37730. /**
  37731. * "Static Class" containing the most commonly used helper while dealing with material for
  37732. * rendering purpose.
  37733. *
  37734. * It contains the basic tools to help defining defines, binding uniform for the common part of the materials.
  37735. *
  37736. * This works by convention in BabylonJS but is meant to be use only with shader following the in place naming rules and conventions.
  37737. */
  37738. var MaterialHelper = /** @class */ (function () {
  37739. function MaterialHelper() {
  37740. }
  37741. /**
  37742. * Bind the current view position to an effect.
  37743. * @param effect The effect to be bound
  37744. * @param scene The scene the eyes position is used from
  37745. */
  37746. MaterialHelper.BindEyePosition = function (effect, scene) {
  37747. if (scene._forcedViewPosition) {
  37748. effect.setVector3("vEyePosition", scene._forcedViewPosition);
  37749. return;
  37750. }
  37751. effect.setVector3("vEyePosition", scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.globalPosition);
  37752. };
  37753. /**
  37754. * Helps preparing the defines values about the UVs in used in the effect.
  37755. * UVs are shared as much as we can accross chanels in the shaders.
  37756. * @param texture The texture we are preparing the UVs for
  37757. * @param defines The defines to update
  37758. * @param key The chanel key "diffuse", "specular"... used in the shader
  37759. */
  37760. MaterialHelper.PrepareDefinesForMergedUV = function (texture, defines, key) {
  37761. defines._needUVs = true;
  37762. defines[key] = true;
  37763. if (texture.getTextureMatrix().isIdentity(true)) {
  37764. defines[key + "DIRECTUV"] = texture.coordinatesIndex + 1;
  37765. if (texture.coordinatesIndex === 0) {
  37766. defines["MAINUV1"] = true;
  37767. }
  37768. else {
  37769. defines["MAINUV2"] = true;
  37770. }
  37771. }
  37772. else {
  37773. defines[key + "DIRECTUV"] = 0;
  37774. }
  37775. };
  37776. /**
  37777. * Binds a texture matrix value to its corrsponding uniform
  37778. * @param texture The texture to bind the matrix for
  37779. * @param uniformBuffer The uniform buffer receivin the data
  37780. * @param key The chanel key "diffuse", "specular"... used in the shader
  37781. */
  37782. MaterialHelper.BindTextureMatrix = function (texture, uniformBuffer, key) {
  37783. var matrix = texture.getTextureMatrix();
  37784. if (!matrix.isIdentity(true)) {
  37785. uniformBuffer.updateMatrix(key + "Matrix", matrix);
  37786. }
  37787. };
  37788. /**
  37789. * Helper used to prepare the list of defines associated with misc. values for shader compilation
  37790. * @param mesh defines the current mesh
  37791. * @param scene defines the current scene
  37792. * @param useLogarithmicDepth defines if logarithmic depth has to be turned on
  37793. * @param pointsCloud defines if point cloud rendering has to be turned on
  37794. * @param fogEnabled defines if fog has to be turned on
  37795. * @param alphaTest defines if alpha testing has to be turned on
  37796. * @param defines defines the current list of defines
  37797. */
  37798. MaterialHelper.PrepareDefinesForMisc = function (mesh, scene, useLogarithmicDepth, pointsCloud, fogEnabled, alphaTest, defines) {
  37799. if (defines._areMiscDirty) {
  37800. defines["LOGARITHMICDEPTH"] = useLogarithmicDepth;
  37801. defines["POINTSIZE"] = (pointsCloud || scene.forcePointsCloud);
  37802. defines["FOG"] = (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && fogEnabled);
  37803. defines["NONUNIFORMSCALING"] = mesh.nonUniformScaling;
  37804. defines["ALPHATEST"] = alphaTest;
  37805. }
  37806. };
  37807. /**
  37808. * Helper used to prepare the list of defines associated with frame values for shader compilation
  37809. * @param scene defines the current scene
  37810. * @param engine defines the current engine
  37811. * @param defines specifies the list of active defines
  37812. * @param useInstances defines if instances have to be turned on
  37813. * @param useClipPlane defines if clip plane have to be turned on
  37814. */
  37815. MaterialHelper.PrepareDefinesForFrameBoundValues = function (scene, engine, defines, useInstances, useClipPlane) {
  37816. if (useClipPlane === void 0) { useClipPlane = null; }
  37817. var changed = false;
  37818. if (useClipPlane == null) {
  37819. useClipPlane = (scene.clipPlane !== undefined && scene.clipPlane !== null);
  37820. }
  37821. if (defines["CLIPPLANE"] !== useClipPlane) {
  37822. defines["CLIPPLANE"] = useClipPlane;
  37823. changed = true;
  37824. }
  37825. if (defines["DEPTHPREPASS"] !== !engine.getColorWrite()) {
  37826. defines["DEPTHPREPASS"] = !defines["DEPTHPREPASS"];
  37827. changed = true;
  37828. }
  37829. if (defines["INSTANCES"] !== useInstances) {
  37830. defines["INSTANCES"] = useInstances;
  37831. changed = true;
  37832. }
  37833. if (changed) {
  37834. defines.markAsUnprocessed();
  37835. }
  37836. };
  37837. /**
  37838. * Prepares the defines used in the shader depending on the attributes data available in the mesh
  37839. * @param mesh The mesh containing the geometry data we will draw
  37840. * @param defines The defines to update
  37841. * @param useVertexColor Precise whether vertex colors should be used or not (override mesh info)
  37842. * @param useBones Precise whether bones should be used or not (override mesh info)
  37843. * @param useMorphTargets Precise whether morph targets should be used or not (override mesh info)
  37844. * @param useVertexAlpha Precise whether vertex alpha should be used or not (override mesh info)
  37845. * @returns false if defines are considered not dirty and have not been checked
  37846. */
  37847. MaterialHelper.PrepareDefinesForAttributes = function (mesh, defines, useVertexColor, useBones, useMorphTargets, useVertexAlpha) {
  37848. if (useMorphTargets === void 0) { useMorphTargets = false; }
  37849. if (useVertexAlpha === void 0) { useVertexAlpha = true; }
  37850. if (!defines._areAttributesDirty && defines._needNormals === defines._normals && defines._needUVs === defines._uvs) {
  37851. return false;
  37852. }
  37853. defines._normals = defines._needNormals;
  37854. defines._uvs = defines._needUVs;
  37855. defines["NORMAL"] = (defines._needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind));
  37856. if (defines._needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  37857. defines["TANGENT"] = true;
  37858. }
  37859. if (defines._needUVs) {
  37860. defines["UV1"] = mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind);
  37861. defines["UV2"] = mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind);
  37862. }
  37863. else {
  37864. defines["UV1"] = false;
  37865. defines["UV2"] = false;
  37866. }
  37867. if (useVertexColor) {
  37868. var hasVertexColors = mesh.useVertexColors && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind);
  37869. defines["VERTEXCOLOR"] = hasVertexColors;
  37870. defines["VERTEXALPHA"] = mesh.hasVertexAlpha && hasVertexColors && useVertexAlpha;
  37871. }
  37872. if (useBones) {
  37873. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  37874. defines["NUM_BONE_INFLUENCERS"] = mesh.numBoneInfluencers;
  37875. defines["BonesPerMesh"] = (mesh.skeleton.bones.length + 1);
  37876. }
  37877. else {
  37878. defines["NUM_BONE_INFLUENCERS"] = 0;
  37879. defines["BonesPerMesh"] = 0;
  37880. }
  37881. }
  37882. if (useMorphTargets) {
  37883. var manager = mesh.morphTargetManager;
  37884. if (manager) {
  37885. defines["MORPHTARGETS_TANGENT"] = manager.supportsTangents && defines["TANGENT"];
  37886. defines["MORPHTARGETS_NORMAL"] = manager.supportsNormals && defines["NORMAL"];
  37887. defines["MORPHTARGETS"] = (manager.numInfluencers > 0);
  37888. defines["NUM_MORPH_INFLUENCERS"] = manager.numInfluencers;
  37889. }
  37890. else {
  37891. defines["MORPHTARGETS_TANGENT"] = false;
  37892. defines["MORPHTARGETS_NORMAL"] = false;
  37893. defines["MORPHTARGETS"] = false;
  37894. defines["NUM_MORPH_INFLUENCERS"] = 0;
  37895. }
  37896. }
  37897. return true;
  37898. };
  37899. /**
  37900. * Prepares the defines related to the light information passed in parameter
  37901. * @param scene The scene we are intending to draw
  37902. * @param mesh The mesh the effect is compiling for
  37903. * @param defines The defines to update
  37904. * @param specularSupported Specifies whether specular is supported or not (override lights data)
  37905. * @param maxSimultaneousLights Specfies how manuy lights can be added to the effect at max
  37906. * @param disableLighting Specifies whether the lighting is disabled (override scene and light)
  37907. * @returns true if normals will be required for the rest of the effect
  37908. */
  37909. MaterialHelper.PrepareDefinesForLights = function (scene, mesh, defines, specularSupported, maxSimultaneousLights, disableLighting) {
  37910. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  37911. if (disableLighting === void 0) { disableLighting = false; }
  37912. if (!defines._areLightsDirty) {
  37913. return defines._needNormals;
  37914. }
  37915. var lightIndex = 0;
  37916. var needNormals = false;
  37917. var needRebuild = false;
  37918. var lightmapMode = false;
  37919. var shadowEnabled = false;
  37920. var specularEnabled = false;
  37921. if (scene.lightsEnabled && !disableLighting) {
  37922. for (var _i = 0, _a = mesh._lightSources; _i < _a.length; _i++) {
  37923. var light = _a[_i];
  37924. needNormals = true;
  37925. if (defines["LIGHT" + lightIndex] === undefined) {
  37926. needRebuild = true;
  37927. }
  37928. defines["LIGHT" + lightIndex] = true;
  37929. defines["SPOTLIGHT" + lightIndex] = false;
  37930. defines["HEMILIGHT" + lightIndex] = false;
  37931. defines["POINTLIGHT" + lightIndex] = false;
  37932. defines["DIRLIGHT" + lightIndex] = false;
  37933. var type;
  37934. if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_SPOTLIGHT) {
  37935. type = "SPOTLIGHT" + lightIndex;
  37936. var spotLight = light;
  37937. defines["PROJECTEDLIGHTTEXTURE" + lightIndex] = spotLight.projectionTexture ? spotLight.projectionTexture.isReady() : false;
  37938. }
  37939. else if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_HEMISPHERICLIGHT) {
  37940. type = "HEMILIGHT" + lightIndex;
  37941. }
  37942. else if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_POINTLIGHT) {
  37943. type = "POINTLIGHT" + lightIndex;
  37944. }
  37945. else {
  37946. type = "DIRLIGHT" + lightIndex;
  37947. }
  37948. defines[type] = true;
  37949. // Specular
  37950. if (specularSupported && !light.specular.equalsFloats(0, 0, 0)) {
  37951. specularEnabled = true;
  37952. }
  37953. // Shadows
  37954. defines["SHADOW" + lightIndex] = false;
  37955. defines["SHADOWPCF" + lightIndex] = false;
  37956. defines["SHADOWESM" + lightIndex] = false;
  37957. defines["SHADOWCUBE" + lightIndex] = false;
  37958. if (mesh && mesh.receiveShadows && scene.shadowsEnabled && light.shadowEnabled) {
  37959. var shadowGenerator = light.getShadowGenerator();
  37960. if (shadowGenerator) {
  37961. shadowEnabled = true;
  37962. shadowGenerator.prepareDefines(defines, lightIndex);
  37963. }
  37964. }
  37965. if (light.lightmapMode != BABYLON.Light.LIGHTMAP_DEFAULT) {
  37966. lightmapMode = true;
  37967. defines["LIGHTMAPEXCLUDED" + lightIndex] = true;
  37968. defines["LIGHTMAPNOSPECULAR" + lightIndex] = (light.lightmapMode == BABYLON.Light.LIGHTMAP_SHADOWSONLY);
  37969. }
  37970. else {
  37971. defines["LIGHTMAPEXCLUDED" + lightIndex] = false;
  37972. defines["LIGHTMAPNOSPECULAR" + lightIndex] = false;
  37973. }
  37974. lightIndex++;
  37975. if (lightIndex === maxSimultaneousLights)
  37976. break;
  37977. }
  37978. }
  37979. defines["SPECULARTERM"] = specularEnabled;
  37980. defines["SHADOWS"] = shadowEnabled;
  37981. // Resetting all other lights if any
  37982. for (var index = lightIndex; index < maxSimultaneousLights; index++) {
  37983. if (defines["LIGHT" + index] !== undefined) {
  37984. defines["LIGHT" + index] = false;
  37985. defines["HEMILIGHT" + lightIndex] = false;
  37986. defines["POINTLIGHT" + lightIndex] = false;
  37987. defines["DIRLIGHT" + lightIndex] = false;
  37988. defines["SPOTLIGHT" + lightIndex] = false;
  37989. defines["SHADOW" + lightIndex] = false;
  37990. }
  37991. }
  37992. var caps = scene.getEngine().getCaps();
  37993. if (defines["SHADOWFLOAT"] === undefined) {
  37994. needRebuild = true;
  37995. }
  37996. defines["SHADOWFLOAT"] = shadowEnabled &&
  37997. ((caps.textureFloatRender && caps.textureFloatLinearFiltering) ||
  37998. (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering));
  37999. defines["LIGHTMAPEXCLUDED"] = lightmapMode;
  38000. if (needRebuild) {
  38001. defines.rebuild();
  38002. }
  38003. return needNormals;
  38004. };
  38005. /**
  38006. * Prepares the uniforms and samplers list to be used in the effect. This can automatically remove from the list uniforms
  38007. * that won t be acctive due to defines being turned off.
  38008. * @param uniformsListOrOptions The uniform names to prepare or an EffectCreationOptions containing the liist and extra information
  38009. * @param samplersList The samplers list
  38010. * @param defines The defines helping in the list generation
  38011. * @param maxSimultaneousLights The maximum number of simultanous light allowed in the effect
  38012. */
  38013. MaterialHelper.PrepareUniformsAndSamplersList = function (uniformsListOrOptions, samplersList, defines, maxSimultaneousLights) {
  38014. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  38015. var uniformsList;
  38016. var uniformBuffersList = null;
  38017. if (uniformsListOrOptions.uniformsNames) {
  38018. var options = uniformsListOrOptions;
  38019. uniformsList = options.uniformsNames;
  38020. uniformBuffersList = options.uniformBuffersNames;
  38021. samplersList = options.samplers;
  38022. defines = options.defines;
  38023. maxSimultaneousLights = options.maxSimultaneousLights;
  38024. }
  38025. else {
  38026. uniformsList = uniformsListOrOptions;
  38027. if (!samplersList) {
  38028. samplersList = [];
  38029. }
  38030. }
  38031. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  38032. if (!defines["LIGHT" + lightIndex]) {
  38033. break;
  38034. }
  38035. uniformsList.push("vLightData" + lightIndex, "vLightDiffuse" + lightIndex, "vLightSpecular" + lightIndex, "vLightDirection" + lightIndex, "vLightGround" + lightIndex, "lightMatrix" + lightIndex, "shadowsInfo" + lightIndex, "depthValues" + lightIndex);
  38036. if (uniformBuffersList) {
  38037. uniformBuffersList.push("Light" + lightIndex);
  38038. }
  38039. samplersList.push("shadowSampler" + lightIndex);
  38040. if (defines["PROJECTEDLIGHTTEXTURE" + lightIndex]) {
  38041. samplersList.push("projectionLightSampler" + lightIndex);
  38042. uniformsList.push("textureProjectionMatrix" + lightIndex);
  38043. }
  38044. }
  38045. if (defines["NUM_MORPH_INFLUENCERS"]) {
  38046. uniformsList.push("morphTargetInfluences");
  38047. }
  38048. };
  38049. /**
  38050. * This helps decreasing rank by rank the shadow quality (0 being the highest rank and quality)
  38051. * @param defines The defines to update while falling back
  38052. * @param fallbacks The authorized effect fallbacks
  38053. * @param maxSimultaneousLights The maximum number of lights allowed
  38054. * @param rank the current rank of the Effect
  38055. * @returns The newly affected rank
  38056. */
  38057. MaterialHelper.HandleFallbacksForShadows = function (defines, fallbacks, maxSimultaneousLights, rank) {
  38058. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  38059. if (rank === void 0) { rank = 0; }
  38060. var lightFallbackRank = 0;
  38061. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  38062. if (!defines["LIGHT" + lightIndex]) {
  38063. break;
  38064. }
  38065. if (lightIndex > 0) {
  38066. lightFallbackRank = rank + lightIndex;
  38067. fallbacks.addFallback(lightFallbackRank, "LIGHT" + lightIndex);
  38068. }
  38069. if (!defines["SHADOWS"]) {
  38070. if (defines["SHADOW" + lightIndex]) {
  38071. fallbacks.addFallback(rank, "SHADOW" + lightIndex);
  38072. }
  38073. if (defines["SHADOWPCF" + lightIndex]) {
  38074. fallbacks.addFallback(rank, "SHADOWPCF" + lightIndex);
  38075. }
  38076. if (defines["SHADOWESM" + lightIndex]) {
  38077. fallbacks.addFallback(rank, "SHADOWESM" + lightIndex);
  38078. }
  38079. }
  38080. }
  38081. return lightFallbackRank++;
  38082. };
  38083. /**
  38084. * Prepares the list of attributes required for morph targets according to the effect defines.
  38085. * @param attribs The current list of supported attribs
  38086. * @param mesh The mesh to prepare the morph targets attributes for
  38087. * @param defines The current Defines of the effect
  38088. */
  38089. MaterialHelper.PrepareAttributesForMorphTargets = function (attribs, mesh, defines) {
  38090. var influencers = defines["NUM_MORPH_INFLUENCERS"];
  38091. if (influencers > 0 && BABYLON.Engine.LastCreatedEngine) {
  38092. var maxAttributesCount = BABYLON.Engine.LastCreatedEngine.getCaps().maxVertexAttribs;
  38093. var manager = mesh.morphTargetManager;
  38094. var normal = manager && manager.supportsNormals && defines["NORMAL"];
  38095. var tangent = manager && manager.supportsTangents && defines["TANGENT"];
  38096. for (var index = 0; index < influencers; index++) {
  38097. attribs.push(BABYLON.VertexBuffer.PositionKind + index);
  38098. if (normal) {
  38099. attribs.push(BABYLON.VertexBuffer.NormalKind + index);
  38100. }
  38101. if (tangent) {
  38102. attribs.push(BABYLON.VertexBuffer.TangentKind + index);
  38103. }
  38104. if (attribs.length > maxAttributesCount) {
  38105. BABYLON.Tools.Error("Cannot add more vertex attributes for mesh " + mesh.name);
  38106. }
  38107. }
  38108. }
  38109. };
  38110. /**
  38111. * Prepares the list of attributes required for bones according to the effect defines.
  38112. * @param attribs The current list of supported attribs
  38113. * @param mesh The mesh to prepare the bones attributes for
  38114. * @param defines The current Defines of the effect
  38115. * @param fallbacks The current efffect fallback strategy
  38116. */
  38117. MaterialHelper.PrepareAttributesForBones = function (attribs, mesh, defines, fallbacks) {
  38118. if (defines["NUM_BONE_INFLUENCERS"] > 0) {
  38119. fallbacks.addCPUSkinningFallback(0, mesh);
  38120. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  38121. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  38122. if (defines["NUM_BONE_INFLUENCERS"] > 4) {
  38123. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  38124. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  38125. }
  38126. }
  38127. };
  38128. /**
  38129. * Prepares the list of attributes required for instances according to the effect defines.
  38130. * @param attribs The current list of supported attribs
  38131. * @param defines The current Defines of the effect
  38132. */
  38133. MaterialHelper.PrepareAttributesForInstances = function (attribs, defines) {
  38134. if (defines["INSTANCES"]) {
  38135. attribs.push("world0");
  38136. attribs.push("world1");
  38137. attribs.push("world2");
  38138. attribs.push("world3");
  38139. }
  38140. };
  38141. /**
  38142. * Binds the light shadow information to the effect for the given mesh.
  38143. * @param light The light containing the generator
  38144. * @param scene The scene the lights belongs to
  38145. * @param mesh The mesh we are binding the information to render
  38146. * @param lightIndex The light index in the effect used to render the mesh
  38147. * @param effect The effect we are binding the data to
  38148. */
  38149. MaterialHelper.BindLightShadow = function (light, scene, mesh, lightIndex, effect) {
  38150. if (light.shadowEnabled && mesh.receiveShadows) {
  38151. var shadowGenerator = light.getShadowGenerator();
  38152. if (shadowGenerator) {
  38153. shadowGenerator.bindShadowLight(lightIndex, effect);
  38154. }
  38155. }
  38156. };
  38157. /**
  38158. * Binds the light information to the effect.
  38159. * @param light The light containing the generator
  38160. * @param effect The effect we are binding the data to
  38161. * @param lightIndex The light index in the effect used to render
  38162. */
  38163. MaterialHelper.BindLightProperties = function (light, effect, lightIndex) {
  38164. light.transferToEffect(effect, lightIndex + "");
  38165. };
  38166. /**
  38167. * Binds the lights information from the scene to the effect for the given mesh.
  38168. * @param scene The scene the lights belongs to
  38169. * @param mesh The mesh we are binding the information to render
  38170. * @param effect The effect we are binding the data to
  38171. * @param defines The generated defines for the effect
  38172. * @param maxSimultaneousLights The maximum number of light that can be bound to the effect
  38173. * @param usePhysicalLightFalloff Specifies whether the light falloff is defined physically or not
  38174. */
  38175. MaterialHelper.BindLights = function (scene, mesh, effect, defines, maxSimultaneousLights, usePhysicalLightFalloff) {
  38176. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  38177. if (usePhysicalLightFalloff === void 0) { usePhysicalLightFalloff = false; }
  38178. var len = Math.min(mesh._lightSources.length, maxSimultaneousLights);
  38179. for (var i = 0; i < len; i++) {
  38180. var light = mesh._lightSources[i];
  38181. var iAsString = i.toString();
  38182. var scaledIntensity = light.getScaledIntensity();
  38183. light._uniformBuffer.bindToEffect(effect, "Light" + i);
  38184. MaterialHelper.BindLightProperties(light, effect, i);
  38185. light.diffuse.scaleToRef(scaledIntensity, BABYLON.Tmp.Color3[0]);
  38186. light._uniformBuffer.updateColor4("vLightDiffuse", BABYLON.Tmp.Color3[0], usePhysicalLightFalloff ? light.radius : light.range, iAsString);
  38187. if (defines["SPECULARTERM"]) {
  38188. light.specular.scaleToRef(scaledIntensity, BABYLON.Tmp.Color3[1]);
  38189. light._uniformBuffer.updateColor3("vLightSpecular", BABYLON.Tmp.Color3[1], iAsString);
  38190. }
  38191. // Shadows
  38192. if (scene.shadowsEnabled) {
  38193. this.BindLightShadow(light, scene, mesh, iAsString, effect);
  38194. }
  38195. light._uniformBuffer.update();
  38196. }
  38197. };
  38198. /**
  38199. * Binds the fog information from the scene to the effect for the given mesh.
  38200. * @param scene The scene the lights belongs to
  38201. * @param mesh The mesh we are binding the information to render
  38202. * @param effect The effect we are binding the data to
  38203. */
  38204. MaterialHelper.BindFogParameters = function (scene, mesh, effect) {
  38205. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE) {
  38206. effect.setFloat4("vFogInfos", scene.fogMode, scene.fogStart, scene.fogEnd, scene.fogDensity);
  38207. effect.setColor3("vFogColor", scene.fogColor);
  38208. }
  38209. };
  38210. /**
  38211. * Binds the bones information from the mesh to the effect.
  38212. * @param mesh The mesh we are binding the information to render
  38213. * @param effect The effect we are binding the data to
  38214. */
  38215. MaterialHelper.BindBonesParameters = function (mesh, effect) {
  38216. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  38217. var matrices = mesh.skeleton.getTransformMatrices(mesh);
  38218. if (matrices && effect) {
  38219. effect.setMatrices("mBones", matrices);
  38220. }
  38221. }
  38222. };
  38223. /**
  38224. * Binds the morph targets information from the mesh to the effect.
  38225. * @param abstractMesh The mesh we are binding the information to render
  38226. * @param effect The effect we are binding the data to
  38227. */
  38228. MaterialHelper.BindMorphTargetParameters = function (abstractMesh, effect) {
  38229. var manager = abstractMesh.morphTargetManager;
  38230. if (!abstractMesh || !manager) {
  38231. return;
  38232. }
  38233. effect.setFloatArray("morphTargetInfluences", manager.influences);
  38234. };
  38235. /**
  38236. * Binds the logarithmic depth information from the scene to the effect for the given defines.
  38237. * @param defines The generated defines used in the effect
  38238. * @param effect The effect we are binding the data to
  38239. * @param scene The scene we are willing to render with logarithmic scale for
  38240. */
  38241. MaterialHelper.BindLogDepth = function (defines, effect, scene) {
  38242. if (defines["LOGARITHMICDEPTH"]) {
  38243. effect.setFloat("logarithmicDepthConstant", 2.0 / (Math.log(scene.activeCamera.maxZ + 1.0) / Math.LN2));
  38244. }
  38245. };
  38246. /**
  38247. * Binds the clip plane information from the scene to the effect.
  38248. * @param scene The scene the clip plane information are extracted from
  38249. * @param effect The effect we are binding the data to
  38250. */
  38251. MaterialHelper.BindClipPlane = function (effect, scene) {
  38252. if (scene.clipPlane) {
  38253. var clipPlane = scene.clipPlane;
  38254. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  38255. }
  38256. };
  38257. return MaterialHelper;
  38258. }());
  38259. BABYLON.MaterialHelper = MaterialHelper;
  38260. })(BABYLON || (BABYLON = {}));
  38261. //# sourceMappingURL=babylon.materialHelper.js.map
  38262. var BABYLON;
  38263. (function (BABYLON) {
  38264. var PushMaterial = /** @class */ (function (_super) {
  38265. __extends(PushMaterial, _super);
  38266. function PushMaterial(name, scene) {
  38267. var _this = _super.call(this, name, scene) || this;
  38268. _this._normalMatrix = new BABYLON.Matrix();
  38269. _this.storeEffectOnSubMeshes = true;
  38270. return _this;
  38271. }
  38272. PushMaterial.prototype.getEffect = function () {
  38273. return this._activeEffect;
  38274. };
  38275. PushMaterial.prototype.isReady = function (mesh, useInstances) {
  38276. if (!mesh) {
  38277. return false;
  38278. }
  38279. if (!mesh.subMeshes || mesh.subMeshes.length === 0) {
  38280. return true;
  38281. }
  38282. return this.isReadyForSubMesh(mesh, mesh.subMeshes[0], useInstances);
  38283. };
  38284. /**
  38285. * Binds the given world matrix to the active effect
  38286. *
  38287. * @param world the matrix to bind
  38288. */
  38289. PushMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  38290. this._activeEffect.setMatrix("world", world);
  38291. };
  38292. /**
  38293. * Binds the given normal matrix to the active effect
  38294. *
  38295. * @param normalMatrix the matrix to bind
  38296. */
  38297. PushMaterial.prototype.bindOnlyNormalMatrix = function (normalMatrix) {
  38298. this._activeEffect.setMatrix("normalMatrix", normalMatrix);
  38299. };
  38300. PushMaterial.prototype.bind = function (world, mesh) {
  38301. if (!mesh) {
  38302. return;
  38303. }
  38304. this.bindForSubMesh(world, mesh, mesh.subMeshes[0]);
  38305. };
  38306. PushMaterial.prototype._afterBind = function (mesh, effect) {
  38307. if (effect === void 0) { effect = null; }
  38308. _super.prototype._afterBind.call(this, mesh);
  38309. this.getScene()._cachedEffect = effect;
  38310. };
  38311. PushMaterial.prototype._mustRebind = function (scene, effect, visibility) {
  38312. if (visibility === void 0) { visibility = 1; }
  38313. return scene.isCachedMaterialInvalid(this, effect, visibility);
  38314. };
  38315. return PushMaterial;
  38316. }(BABYLON.Material));
  38317. BABYLON.PushMaterial = PushMaterial;
  38318. })(BABYLON || (BABYLON = {}));
  38319. //# sourceMappingURL=babylon.pushMaterial.js.map
  38320. var BABYLON;
  38321. (function (BABYLON) {
  38322. /** @ignore */
  38323. var StandardMaterialDefines = /** @class */ (function (_super) {
  38324. __extends(StandardMaterialDefines, _super);
  38325. function StandardMaterialDefines() {
  38326. var _this = _super.call(this) || this;
  38327. _this.MAINUV1 = false;
  38328. _this.MAINUV2 = false;
  38329. _this.DIFFUSE = false;
  38330. _this.DIFFUSEDIRECTUV = 0;
  38331. _this.AMBIENT = false;
  38332. _this.AMBIENTDIRECTUV = 0;
  38333. _this.OPACITY = false;
  38334. _this.OPACITYDIRECTUV = 0;
  38335. _this.OPACITYRGB = false;
  38336. _this.REFLECTION = false;
  38337. _this.EMISSIVE = false;
  38338. _this.EMISSIVEDIRECTUV = 0;
  38339. _this.SPECULAR = false;
  38340. _this.SPECULARDIRECTUV = 0;
  38341. _this.BUMP = false;
  38342. _this.BUMPDIRECTUV = 0;
  38343. _this.PARALLAX = false;
  38344. _this.PARALLAXOCCLUSION = false;
  38345. _this.SPECULAROVERALPHA = false;
  38346. _this.CLIPPLANE = false;
  38347. _this.ALPHATEST = false;
  38348. _this.DEPTHPREPASS = false;
  38349. _this.ALPHAFROMDIFFUSE = false;
  38350. _this.POINTSIZE = false;
  38351. _this.FOG = false;
  38352. _this.SPECULARTERM = false;
  38353. _this.DIFFUSEFRESNEL = false;
  38354. _this.OPACITYFRESNEL = false;
  38355. _this.REFLECTIONFRESNEL = false;
  38356. _this.REFRACTIONFRESNEL = false;
  38357. _this.EMISSIVEFRESNEL = false;
  38358. _this.FRESNEL = false;
  38359. _this.NORMAL = false;
  38360. _this.UV1 = false;
  38361. _this.UV2 = false;
  38362. _this.VERTEXCOLOR = false;
  38363. _this.VERTEXALPHA = false;
  38364. _this.NUM_BONE_INFLUENCERS = 0;
  38365. _this.BonesPerMesh = 0;
  38366. _this.INSTANCES = false;
  38367. _this.GLOSSINESS = false;
  38368. _this.ROUGHNESS = false;
  38369. _this.EMISSIVEASILLUMINATION = false;
  38370. _this.LINKEMISSIVEWITHDIFFUSE = false;
  38371. _this.REFLECTIONFRESNELFROMSPECULAR = false;
  38372. _this.LIGHTMAP = false;
  38373. _this.LIGHTMAPDIRECTUV = 0;
  38374. _this.OBJECTSPACE_NORMALMAP = false;
  38375. _this.USELIGHTMAPASSHADOWMAP = false;
  38376. _this.REFLECTIONMAP_3D = false;
  38377. _this.REFLECTIONMAP_SPHERICAL = false;
  38378. _this.REFLECTIONMAP_PLANAR = false;
  38379. _this.REFLECTIONMAP_CUBIC = false;
  38380. _this.USE_LOCAL_REFLECTIONMAP_CUBIC = false;
  38381. _this.REFLECTIONMAP_PROJECTION = false;
  38382. _this.REFLECTIONMAP_SKYBOX = false;
  38383. _this.REFLECTIONMAP_EXPLICIT = false;
  38384. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  38385. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  38386. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  38387. _this.INVERTCUBICMAP = false;
  38388. _this.LOGARITHMICDEPTH = false;
  38389. _this.REFRACTION = false;
  38390. _this.REFRACTIONMAP_3D = false;
  38391. _this.REFLECTIONOVERALPHA = false;
  38392. _this.TWOSIDEDLIGHTING = false;
  38393. _this.SHADOWFLOAT = false;
  38394. _this.MORPHTARGETS = false;
  38395. _this.MORPHTARGETS_NORMAL = false;
  38396. _this.MORPHTARGETS_TANGENT = false;
  38397. _this.NUM_MORPH_INFLUENCERS = 0;
  38398. _this.NONUNIFORMSCALING = false; // https://playground.babylonjs.com#V6DWIH
  38399. _this.PREMULTIPLYALPHA = false; // https://playground.babylonjs.com#LNVJJ7
  38400. _this.IMAGEPROCESSING = false;
  38401. _this.VIGNETTE = false;
  38402. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  38403. _this.VIGNETTEBLENDMODEOPAQUE = false;
  38404. _this.TONEMAPPING = false;
  38405. _this.CONTRAST = false;
  38406. _this.COLORCURVES = false;
  38407. _this.COLORGRADING = false;
  38408. _this.COLORGRADING3D = false;
  38409. _this.SAMPLER3DGREENDEPTH = false;
  38410. _this.SAMPLER3DBGRMAP = false;
  38411. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  38412. _this.EXPOSURE = false;
  38413. _this.rebuild();
  38414. return _this;
  38415. }
  38416. StandardMaterialDefines.prototype.setReflectionMode = function (modeToEnable) {
  38417. var modes = [
  38418. "REFLECTIONMAP_CUBIC", "REFLECTIONMAP_EXPLICIT", "REFLECTIONMAP_PLANAR",
  38419. "REFLECTIONMAP_PROJECTION", "REFLECTIONMAP_PROJECTION", "REFLECTIONMAP_SKYBOX",
  38420. "REFLECTIONMAP_SPHERICAL", "REFLECTIONMAP_EQUIRECTANGULAR", "REFLECTIONMAP_EQUIRECTANGULAR_FIXED",
  38421. "REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED"
  38422. ];
  38423. for (var _i = 0, modes_1 = modes; _i < modes_1.length; _i++) {
  38424. var mode = modes_1[_i];
  38425. this[mode] = (mode === modeToEnable);
  38426. }
  38427. };
  38428. return StandardMaterialDefines;
  38429. }(BABYLON.MaterialDefines));
  38430. BABYLON.StandardMaterialDefines = StandardMaterialDefines;
  38431. var StandardMaterial = /** @class */ (function (_super) {
  38432. __extends(StandardMaterial, _super);
  38433. function StandardMaterial(name, scene) {
  38434. var _this = _super.call(this, name, scene) || this;
  38435. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  38436. _this.diffuseColor = new BABYLON.Color3(1, 1, 1);
  38437. _this.specularColor = new BABYLON.Color3(1, 1, 1);
  38438. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  38439. _this.specularPower = 64;
  38440. _this._useAlphaFromDiffuseTexture = false;
  38441. _this._useEmissiveAsIllumination = false;
  38442. _this._linkEmissiveWithDiffuse = false;
  38443. _this._useSpecularOverAlpha = false;
  38444. _this._useReflectionOverAlpha = false;
  38445. _this._disableLighting = false;
  38446. _this._useObjectSpaceNormalMap = false;
  38447. _this._useParallax = false;
  38448. _this._useParallaxOcclusion = false;
  38449. _this.parallaxScaleBias = 0.05;
  38450. _this._roughness = 0;
  38451. _this.indexOfRefraction = 0.98;
  38452. _this.invertRefractionY = true;
  38453. _this._useLightmapAsShadowmap = false;
  38454. _this._useReflectionFresnelFromSpecular = false;
  38455. _this._useGlossinessFromSpecularMapAlpha = false;
  38456. _this._maxSimultaneousLights = 4;
  38457. /**
  38458. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  38459. */
  38460. _this._invertNormalMapX = false;
  38461. /**
  38462. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  38463. */
  38464. _this._invertNormalMapY = false;
  38465. /**
  38466. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  38467. */
  38468. _this._twoSidedLighting = false;
  38469. _this._renderTargets = new BABYLON.SmartArray(16);
  38470. _this._worldViewProjectionMatrix = BABYLON.Matrix.Zero();
  38471. _this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  38472. // Setup the default processing configuration to the scene.
  38473. _this._attachImageProcessingConfiguration(null);
  38474. _this.getRenderTargetTextures = function () {
  38475. _this._renderTargets.reset();
  38476. if (StandardMaterial.ReflectionTextureEnabled && _this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  38477. _this._renderTargets.push(_this._reflectionTexture);
  38478. }
  38479. if (StandardMaterial.RefractionTextureEnabled && _this._refractionTexture && _this._refractionTexture.isRenderTarget) {
  38480. _this._renderTargets.push(_this._refractionTexture);
  38481. }
  38482. return _this._renderTargets;
  38483. };
  38484. return _this;
  38485. }
  38486. ;
  38487. ;
  38488. ;
  38489. ;
  38490. ;
  38491. ;
  38492. ;
  38493. ;
  38494. ;
  38495. ;
  38496. ;
  38497. ;
  38498. ;
  38499. ;
  38500. ;
  38501. ;
  38502. ;
  38503. Object.defineProperty(StandardMaterial.prototype, "imageProcessingConfiguration", {
  38504. /**
  38505. * Gets the image processing configuration used either in this material.
  38506. */
  38507. get: function () {
  38508. return this._imageProcessingConfiguration;
  38509. },
  38510. /**
  38511. * Sets the Default image processing configuration used either in the this material.
  38512. *
  38513. * If sets to null, the scene one is in use.
  38514. */
  38515. set: function (value) {
  38516. this._attachImageProcessingConfiguration(value);
  38517. // Ensure the effect will be rebuilt.
  38518. this._markAllSubMeshesAsTexturesDirty();
  38519. },
  38520. enumerable: true,
  38521. configurable: true
  38522. });
  38523. /**
  38524. * Attaches a new image processing configuration to the Standard Material.
  38525. * @param configuration
  38526. */
  38527. StandardMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  38528. var _this = this;
  38529. if (configuration === this._imageProcessingConfiguration) {
  38530. return;
  38531. }
  38532. // Detaches observer.
  38533. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  38534. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  38535. }
  38536. // Pick the scene configuration if needed.
  38537. if (!configuration) {
  38538. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  38539. }
  38540. else {
  38541. this._imageProcessingConfiguration = configuration;
  38542. }
  38543. // Attaches observer.
  38544. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  38545. _this._markAllSubMeshesAsImageProcessingDirty();
  38546. });
  38547. };
  38548. Object.defineProperty(StandardMaterial.prototype, "cameraColorCurvesEnabled", {
  38549. /**
  38550. * Gets wether the color curves effect is enabled.
  38551. */
  38552. get: function () {
  38553. return this.imageProcessingConfiguration.colorCurvesEnabled;
  38554. },
  38555. /**
  38556. * Sets wether the color curves effect is enabled.
  38557. */
  38558. set: function (value) {
  38559. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  38560. },
  38561. enumerable: true,
  38562. configurable: true
  38563. });
  38564. Object.defineProperty(StandardMaterial.prototype, "cameraColorGradingEnabled", {
  38565. /**
  38566. * Gets wether the color grading effect is enabled.
  38567. */
  38568. get: function () {
  38569. return this.imageProcessingConfiguration.colorGradingEnabled;
  38570. },
  38571. /**
  38572. * Gets wether the color grading effect is enabled.
  38573. */
  38574. set: function (value) {
  38575. this.imageProcessingConfiguration.colorGradingEnabled = value;
  38576. },
  38577. enumerable: true,
  38578. configurable: true
  38579. });
  38580. Object.defineProperty(StandardMaterial.prototype, "cameraToneMappingEnabled", {
  38581. /**
  38582. * Gets wether tonemapping is enabled or not.
  38583. */
  38584. get: function () {
  38585. return this._imageProcessingConfiguration.toneMappingEnabled;
  38586. },
  38587. /**
  38588. * Sets wether tonemapping is enabled or not
  38589. */
  38590. set: function (value) {
  38591. this._imageProcessingConfiguration.toneMappingEnabled = value;
  38592. },
  38593. enumerable: true,
  38594. configurable: true
  38595. });
  38596. ;
  38597. ;
  38598. Object.defineProperty(StandardMaterial.prototype, "cameraExposure", {
  38599. /**
  38600. * The camera exposure used on this material.
  38601. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  38602. * This corresponds to a photographic exposure.
  38603. */
  38604. get: function () {
  38605. return this._imageProcessingConfiguration.exposure;
  38606. },
  38607. /**
  38608. * The camera exposure used on this material.
  38609. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  38610. * This corresponds to a photographic exposure.
  38611. */
  38612. set: function (value) {
  38613. this._imageProcessingConfiguration.exposure = value;
  38614. },
  38615. enumerable: true,
  38616. configurable: true
  38617. });
  38618. ;
  38619. ;
  38620. Object.defineProperty(StandardMaterial.prototype, "cameraContrast", {
  38621. /**
  38622. * Gets The camera contrast used on this material.
  38623. */
  38624. get: function () {
  38625. return this._imageProcessingConfiguration.contrast;
  38626. },
  38627. /**
  38628. * Sets The camera contrast used on this material.
  38629. */
  38630. set: function (value) {
  38631. this._imageProcessingConfiguration.contrast = value;
  38632. },
  38633. enumerable: true,
  38634. configurable: true
  38635. });
  38636. Object.defineProperty(StandardMaterial.prototype, "cameraColorGradingTexture", {
  38637. /**
  38638. * Gets the Color Grading 2D Lookup Texture.
  38639. */
  38640. get: function () {
  38641. return this._imageProcessingConfiguration.colorGradingTexture;
  38642. },
  38643. /**
  38644. * Sets the Color Grading 2D Lookup Texture.
  38645. */
  38646. set: function (value) {
  38647. this._imageProcessingConfiguration.colorGradingTexture = value;
  38648. },
  38649. enumerable: true,
  38650. configurable: true
  38651. });
  38652. Object.defineProperty(StandardMaterial.prototype, "cameraColorCurves", {
  38653. /**
  38654. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  38655. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  38656. * 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;
  38657. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  38658. */
  38659. get: function () {
  38660. return this._imageProcessingConfiguration.colorCurves;
  38661. },
  38662. /**
  38663. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  38664. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  38665. * 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;
  38666. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  38667. */
  38668. set: function (value) {
  38669. this._imageProcessingConfiguration.colorCurves = value;
  38670. },
  38671. enumerable: true,
  38672. configurable: true
  38673. });
  38674. StandardMaterial.prototype.getClassName = function () {
  38675. return "StandardMaterial";
  38676. };
  38677. Object.defineProperty(StandardMaterial.prototype, "useLogarithmicDepth", {
  38678. get: function () {
  38679. return this._useLogarithmicDepth;
  38680. },
  38681. set: function (value) {
  38682. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  38683. this._markAllSubMeshesAsMiscDirty();
  38684. },
  38685. enumerable: true,
  38686. configurable: true
  38687. });
  38688. StandardMaterial.prototype.needAlphaBlending = function () {
  38689. return (this.alpha < 1.0) || (this._opacityTexture != null) || this._shouldUseAlphaFromDiffuseTexture() || this._opacityFresnelParameters && this._opacityFresnelParameters.isEnabled;
  38690. };
  38691. StandardMaterial.prototype.needAlphaTesting = function () {
  38692. return this._diffuseTexture != null && this._diffuseTexture.hasAlpha;
  38693. };
  38694. StandardMaterial.prototype._shouldUseAlphaFromDiffuseTexture = function () {
  38695. return this._diffuseTexture != null && this._diffuseTexture.hasAlpha && this._useAlphaFromDiffuseTexture;
  38696. };
  38697. StandardMaterial.prototype.getAlphaTestTexture = function () {
  38698. return this._diffuseTexture;
  38699. };
  38700. /**
  38701. * Child classes can use it to update shaders
  38702. */
  38703. StandardMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  38704. if (useInstances === void 0) { useInstances = false; }
  38705. if (subMesh.effect && this.isFrozen) {
  38706. if (this._wasPreviouslyReady && subMesh.effect) {
  38707. return true;
  38708. }
  38709. }
  38710. if (!subMesh._materialDefines) {
  38711. subMesh._materialDefines = new StandardMaterialDefines();
  38712. }
  38713. var scene = this.getScene();
  38714. var defines = subMesh._materialDefines;
  38715. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  38716. if (defines._renderId === scene.getRenderId()) {
  38717. return true;
  38718. }
  38719. }
  38720. var engine = scene.getEngine();
  38721. // Lights
  38722. defines._needNormals = BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, true, this._maxSimultaneousLights, this._disableLighting);
  38723. // Textures
  38724. if (defines._areTexturesDirty) {
  38725. defines._needUVs = false;
  38726. defines.MAINUV1 = false;
  38727. defines.MAINUV2 = false;
  38728. if (scene.texturesEnabled) {
  38729. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  38730. if (!this._diffuseTexture.isReadyOrNotBlocking()) {
  38731. return false;
  38732. }
  38733. else {
  38734. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._diffuseTexture, defines, "DIFFUSE");
  38735. }
  38736. }
  38737. else {
  38738. defines.DIFFUSE = false;
  38739. }
  38740. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  38741. if (!this._ambientTexture.isReadyOrNotBlocking()) {
  38742. return false;
  38743. }
  38744. else {
  38745. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._ambientTexture, defines, "AMBIENT");
  38746. }
  38747. }
  38748. else {
  38749. defines.AMBIENT = false;
  38750. }
  38751. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  38752. if (!this._opacityTexture.isReadyOrNotBlocking()) {
  38753. return false;
  38754. }
  38755. else {
  38756. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._opacityTexture, defines, "OPACITY");
  38757. defines.OPACITYRGB = this._opacityTexture.getAlphaFromRGB;
  38758. }
  38759. }
  38760. else {
  38761. defines.OPACITY = false;
  38762. }
  38763. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  38764. if (!this._reflectionTexture.isReadyOrNotBlocking()) {
  38765. return false;
  38766. }
  38767. else {
  38768. defines._needNormals = true;
  38769. defines.REFLECTION = true;
  38770. defines.ROUGHNESS = (this._roughness > 0);
  38771. defines.REFLECTIONOVERALPHA = this._useReflectionOverAlpha;
  38772. defines.INVERTCUBICMAP = (this._reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE);
  38773. defines.REFLECTIONMAP_3D = this._reflectionTexture.isCube;
  38774. switch (this._reflectionTexture.coordinatesMode) {
  38775. case BABYLON.Texture.CUBIC_MODE:
  38776. case BABYLON.Texture.INVCUBIC_MODE:
  38777. defines.setReflectionMode("REFLECTIONMAP_CUBIC");
  38778. break;
  38779. case BABYLON.Texture.EXPLICIT_MODE:
  38780. defines.setReflectionMode("REFLECTIONMAP_EXPLICIT");
  38781. break;
  38782. case BABYLON.Texture.PLANAR_MODE:
  38783. defines.setReflectionMode("REFLECTIONMAP_PLANAR");
  38784. break;
  38785. case BABYLON.Texture.PROJECTION_MODE:
  38786. defines.setReflectionMode("REFLECTIONMAP_PROJECTION");
  38787. break;
  38788. case BABYLON.Texture.SKYBOX_MODE:
  38789. defines.setReflectionMode("REFLECTIONMAP_SKYBOX");
  38790. break;
  38791. case BABYLON.Texture.SPHERICAL_MODE:
  38792. defines.setReflectionMode("REFLECTIONMAP_SPHERICAL");
  38793. break;
  38794. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  38795. defines.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR");
  38796. break;
  38797. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  38798. defines.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR_FIXED");
  38799. break;
  38800. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  38801. defines.setReflectionMode("REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED");
  38802. break;
  38803. }
  38804. defines.USE_LOCAL_REFLECTIONMAP_CUBIC = this._reflectionTexture.boundingBoxSize ? true : false;
  38805. }
  38806. }
  38807. else {
  38808. defines.REFLECTION = false;
  38809. }
  38810. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  38811. if (!this._emissiveTexture.isReadyOrNotBlocking()) {
  38812. return false;
  38813. }
  38814. else {
  38815. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._emissiveTexture, defines, "EMISSIVE");
  38816. }
  38817. }
  38818. else {
  38819. defines.EMISSIVE = false;
  38820. }
  38821. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  38822. if (!this._lightmapTexture.isReadyOrNotBlocking()) {
  38823. return false;
  38824. }
  38825. else {
  38826. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._lightmapTexture, defines, "LIGHTMAP");
  38827. defines.USELIGHTMAPASSHADOWMAP = this._useLightmapAsShadowmap;
  38828. }
  38829. }
  38830. else {
  38831. defines.LIGHTMAP = false;
  38832. }
  38833. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  38834. if (!this._specularTexture.isReadyOrNotBlocking()) {
  38835. return false;
  38836. }
  38837. else {
  38838. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._specularTexture, defines, "SPECULAR");
  38839. defines.GLOSSINESS = this._useGlossinessFromSpecularMapAlpha;
  38840. }
  38841. }
  38842. else {
  38843. defines.SPECULAR = false;
  38844. }
  38845. if (scene.getEngine().getCaps().standardDerivatives && this._bumpTexture && StandardMaterial.BumpTextureEnabled) {
  38846. // Bump texure can not be not blocking.
  38847. if (!this._bumpTexture.isReady()) {
  38848. return false;
  38849. }
  38850. else {
  38851. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._bumpTexture, defines, "BUMP");
  38852. defines.PARALLAX = this._useParallax;
  38853. defines.PARALLAXOCCLUSION = this._useParallaxOcclusion;
  38854. }
  38855. defines.OBJECTSPACE_NORMALMAP = this._useObjectSpaceNormalMap;
  38856. }
  38857. else {
  38858. defines.BUMP = false;
  38859. }
  38860. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  38861. if (!this._refractionTexture.isReadyOrNotBlocking()) {
  38862. return false;
  38863. }
  38864. else {
  38865. defines._needUVs = true;
  38866. defines.REFRACTION = true;
  38867. defines.REFRACTIONMAP_3D = this._refractionTexture.isCube;
  38868. }
  38869. }
  38870. else {
  38871. defines.REFRACTION = false;
  38872. }
  38873. defines.TWOSIDEDLIGHTING = !this._backFaceCulling && this._twoSidedLighting;
  38874. }
  38875. else {
  38876. defines.DIFFUSE = false;
  38877. defines.AMBIENT = false;
  38878. defines.OPACITY = false;
  38879. defines.REFLECTION = false;
  38880. defines.EMISSIVE = false;
  38881. defines.LIGHTMAP = false;
  38882. defines.BUMP = false;
  38883. defines.REFRACTION = false;
  38884. }
  38885. defines.ALPHAFROMDIFFUSE = this._shouldUseAlphaFromDiffuseTexture();
  38886. defines.EMISSIVEASILLUMINATION = this._useEmissiveAsIllumination;
  38887. defines.LINKEMISSIVEWITHDIFFUSE = this._linkEmissiveWithDiffuse;
  38888. defines.SPECULAROVERALPHA = this._useSpecularOverAlpha;
  38889. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  38890. }
  38891. if (defines._areImageProcessingDirty) {
  38892. if (!this._imageProcessingConfiguration.isReady()) {
  38893. return false;
  38894. }
  38895. this._imageProcessingConfiguration.prepareDefines(defines);
  38896. }
  38897. if (defines._areFresnelDirty) {
  38898. if (StandardMaterial.FresnelEnabled) {
  38899. // Fresnel
  38900. if (this._diffuseFresnelParameters || this._opacityFresnelParameters ||
  38901. this._emissiveFresnelParameters || this._refractionFresnelParameters ||
  38902. this._reflectionFresnelParameters) {
  38903. defines.DIFFUSEFRESNEL = (this._diffuseFresnelParameters && this._diffuseFresnelParameters.isEnabled);
  38904. defines.OPACITYFRESNEL = (this._opacityFresnelParameters && this._opacityFresnelParameters.isEnabled);
  38905. defines.REFLECTIONFRESNEL = (this._reflectionFresnelParameters && this._reflectionFresnelParameters.isEnabled);
  38906. defines.REFLECTIONFRESNELFROMSPECULAR = this._useReflectionFresnelFromSpecular;
  38907. defines.REFRACTIONFRESNEL = (this._refractionFresnelParameters && this._refractionFresnelParameters.isEnabled);
  38908. defines.EMISSIVEFRESNEL = (this._emissiveFresnelParameters && this._emissiveFresnelParameters.isEnabled);
  38909. defines._needNormals = true;
  38910. defines.FRESNEL = true;
  38911. }
  38912. }
  38913. else {
  38914. defines.FRESNEL = false;
  38915. }
  38916. }
  38917. // Misc.
  38918. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, this._useLogarithmicDepth, this.pointsCloud, this.fogEnabled, this._shouldTurnAlphaTestOn(mesh), defines);
  38919. // Attribs
  38920. BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, true, true, true);
  38921. // Values that need to be evaluated on every frame
  38922. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances);
  38923. // Get correct effect
  38924. if (defines.isDirty) {
  38925. defines.markAsProcessed();
  38926. scene.resetCachedMaterial();
  38927. // Fallbacks
  38928. var fallbacks = new BABYLON.EffectFallbacks();
  38929. if (defines.REFLECTION) {
  38930. fallbacks.addFallback(0, "REFLECTION");
  38931. }
  38932. if (defines.SPECULAR) {
  38933. fallbacks.addFallback(0, "SPECULAR");
  38934. }
  38935. if (defines.BUMP) {
  38936. fallbacks.addFallback(0, "BUMP");
  38937. }
  38938. if (defines.PARALLAX) {
  38939. fallbacks.addFallback(1, "PARALLAX");
  38940. }
  38941. if (defines.PARALLAXOCCLUSION) {
  38942. fallbacks.addFallback(0, "PARALLAXOCCLUSION");
  38943. }
  38944. if (defines.SPECULAROVERALPHA) {
  38945. fallbacks.addFallback(0, "SPECULAROVERALPHA");
  38946. }
  38947. if (defines.FOG) {
  38948. fallbacks.addFallback(1, "FOG");
  38949. }
  38950. if (defines.POINTSIZE) {
  38951. fallbacks.addFallback(0, "POINTSIZE");
  38952. }
  38953. if (defines.LOGARITHMICDEPTH) {
  38954. fallbacks.addFallback(0, "LOGARITHMICDEPTH");
  38955. }
  38956. BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights);
  38957. if (defines.SPECULARTERM) {
  38958. fallbacks.addFallback(0, "SPECULARTERM");
  38959. }
  38960. if (defines.DIFFUSEFRESNEL) {
  38961. fallbacks.addFallback(1, "DIFFUSEFRESNEL");
  38962. }
  38963. if (defines.OPACITYFRESNEL) {
  38964. fallbacks.addFallback(2, "OPACITYFRESNEL");
  38965. }
  38966. if (defines.REFLECTIONFRESNEL) {
  38967. fallbacks.addFallback(3, "REFLECTIONFRESNEL");
  38968. }
  38969. if (defines.EMISSIVEFRESNEL) {
  38970. fallbacks.addFallback(4, "EMISSIVEFRESNEL");
  38971. }
  38972. if (defines.FRESNEL) {
  38973. fallbacks.addFallback(4, "FRESNEL");
  38974. }
  38975. //Attributes
  38976. var attribs = [BABYLON.VertexBuffer.PositionKind];
  38977. if (defines.NORMAL) {
  38978. attribs.push(BABYLON.VertexBuffer.NormalKind);
  38979. }
  38980. if (defines.UV1) {
  38981. attribs.push(BABYLON.VertexBuffer.UVKind);
  38982. }
  38983. if (defines.UV2) {
  38984. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  38985. }
  38986. if (defines.VERTEXCOLOR) {
  38987. attribs.push(BABYLON.VertexBuffer.ColorKind);
  38988. }
  38989. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  38990. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  38991. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, defines);
  38992. var shaderName = "default";
  38993. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vDiffuseColor", "vSpecularColor", "vEmissiveColor",
  38994. "vFogInfos", "vFogColor", "pointSize",
  38995. "vDiffuseInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vEmissiveInfos", "vSpecularInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  38996. "mBones",
  38997. "vClipPlane", "diffuseMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "specularMatrix", "bumpMatrix", "normalMatrix", "lightmapMatrix", "refractionMatrix",
  38998. "diffuseLeftColor", "diffuseRightColor", "opacityParts", "reflectionLeftColor", "reflectionRightColor", "emissiveLeftColor", "emissiveRightColor", "refractionLeftColor", "refractionRightColor",
  38999. "vReflectionPosition", "vReflectionSize",
  39000. "logarithmicDepthConstant", "vTangentSpaceParams"
  39001. ];
  39002. var samplers = ["diffuseSampler", "ambientSampler", "opacitySampler", "reflectionCubeSampler", "reflection2DSampler", "emissiveSampler", "specularSampler", "bumpSampler", "lightmapSampler", "refractionCubeSampler", "refraction2DSampler"];
  39003. var uniformBuffers = ["Material", "Scene"];
  39004. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  39005. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  39006. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  39007. uniformsNames: uniforms,
  39008. uniformBuffersNames: uniformBuffers,
  39009. samplers: samplers,
  39010. defines: defines,
  39011. maxSimultaneousLights: this._maxSimultaneousLights
  39012. });
  39013. if (this.customShaderNameResolve) {
  39014. shaderName = this.customShaderNameResolve(shaderName, uniforms, uniformBuffers, samplers, defines);
  39015. }
  39016. var join = defines.toString();
  39017. subMesh.setEffect(scene.getEngine().createEffect(shaderName, {
  39018. attributes: attribs,
  39019. uniformsNames: uniforms,
  39020. uniformBuffersNames: uniformBuffers,
  39021. samplers: samplers,
  39022. defines: join,
  39023. fallbacks: fallbacks,
  39024. onCompiled: this.onCompiled,
  39025. onError: this.onError,
  39026. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights, maxSimultaneousMorphTargets: defines.NUM_MORPH_INFLUENCERS }
  39027. }, engine), defines);
  39028. this.buildUniformLayout();
  39029. }
  39030. if (!subMesh.effect || !subMesh.effect.isReady()) {
  39031. return false;
  39032. }
  39033. defines._renderId = scene.getRenderId();
  39034. this._wasPreviouslyReady = true;
  39035. return true;
  39036. };
  39037. StandardMaterial.prototype.buildUniformLayout = function () {
  39038. // Order is important !
  39039. this._uniformBuffer.addUniform("diffuseLeftColor", 4);
  39040. this._uniformBuffer.addUniform("diffuseRightColor", 4);
  39041. this._uniformBuffer.addUniform("opacityParts", 4);
  39042. this._uniformBuffer.addUniform("reflectionLeftColor", 4);
  39043. this._uniformBuffer.addUniform("reflectionRightColor", 4);
  39044. this._uniformBuffer.addUniform("refractionLeftColor", 4);
  39045. this._uniformBuffer.addUniform("refractionRightColor", 4);
  39046. this._uniformBuffer.addUniform("emissiveLeftColor", 4);
  39047. this._uniformBuffer.addUniform("emissiveRightColor", 4);
  39048. this._uniformBuffer.addUniform("vDiffuseInfos", 2);
  39049. this._uniformBuffer.addUniform("vAmbientInfos", 2);
  39050. this._uniformBuffer.addUniform("vOpacityInfos", 2);
  39051. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  39052. this._uniformBuffer.addUniform("vReflectionPosition", 3);
  39053. this._uniformBuffer.addUniform("vReflectionSize", 3);
  39054. this._uniformBuffer.addUniform("vEmissiveInfos", 2);
  39055. this._uniformBuffer.addUniform("vLightmapInfos", 2);
  39056. this._uniformBuffer.addUniform("vSpecularInfos", 2);
  39057. this._uniformBuffer.addUniform("vBumpInfos", 3);
  39058. this._uniformBuffer.addUniform("diffuseMatrix", 16);
  39059. this._uniformBuffer.addUniform("ambientMatrix", 16);
  39060. this._uniformBuffer.addUniform("opacityMatrix", 16);
  39061. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  39062. this._uniformBuffer.addUniform("emissiveMatrix", 16);
  39063. this._uniformBuffer.addUniform("lightmapMatrix", 16);
  39064. this._uniformBuffer.addUniform("specularMatrix", 16);
  39065. this._uniformBuffer.addUniform("bumpMatrix", 16);
  39066. this._uniformBuffer.addUniform("vTangentSpaceParams", 2);
  39067. this._uniformBuffer.addUniform("refractionMatrix", 16);
  39068. this._uniformBuffer.addUniform("vRefractionInfos", 4);
  39069. this._uniformBuffer.addUniform("vSpecularColor", 4);
  39070. this._uniformBuffer.addUniform("vEmissiveColor", 3);
  39071. this._uniformBuffer.addUniform("vDiffuseColor", 4);
  39072. this._uniformBuffer.addUniform("pointSize", 1);
  39073. this._uniformBuffer.create();
  39074. };
  39075. StandardMaterial.prototype.unbind = function () {
  39076. if (this._activeEffect) {
  39077. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  39078. this._activeEffect.setTexture("reflection2DSampler", null);
  39079. }
  39080. if (this._refractionTexture && this._refractionTexture.isRenderTarget) {
  39081. this._activeEffect.setTexture("refraction2DSampler", null);
  39082. }
  39083. }
  39084. _super.prototype.unbind.call(this);
  39085. };
  39086. StandardMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  39087. var scene = this.getScene();
  39088. var defines = subMesh._materialDefines;
  39089. if (!defines) {
  39090. return;
  39091. }
  39092. var effect = subMesh.effect;
  39093. if (!effect) {
  39094. return;
  39095. }
  39096. this._activeEffect = effect;
  39097. // Matrices
  39098. this.bindOnlyWorldMatrix(world);
  39099. // Normal Matrix
  39100. if (defines.OBJECTSPACE_NORMALMAP) {
  39101. world.toNormalMatrix(this._normalMatrix);
  39102. this.bindOnlyNormalMatrix(this._normalMatrix);
  39103. }
  39104. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  39105. // Bones
  39106. BABYLON.MaterialHelper.BindBonesParameters(mesh, effect);
  39107. if (mustRebind) {
  39108. this._uniformBuffer.bindToEffect(effect, "Material");
  39109. this.bindViewProjection(effect);
  39110. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  39111. if (StandardMaterial.FresnelEnabled && defines.FRESNEL) {
  39112. // Fresnel
  39113. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  39114. this._uniformBuffer.updateColor4("diffuseLeftColor", this.diffuseFresnelParameters.leftColor, this.diffuseFresnelParameters.power);
  39115. this._uniformBuffer.updateColor4("diffuseRightColor", this.diffuseFresnelParameters.rightColor, this.diffuseFresnelParameters.bias);
  39116. }
  39117. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  39118. this._uniformBuffer.updateColor4("opacityParts", new BABYLON.Color3(this.opacityFresnelParameters.leftColor.toLuminance(), this.opacityFresnelParameters.rightColor.toLuminance(), this.opacityFresnelParameters.bias), this.opacityFresnelParameters.power);
  39119. }
  39120. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  39121. this._uniformBuffer.updateColor4("reflectionLeftColor", this.reflectionFresnelParameters.leftColor, this.reflectionFresnelParameters.power);
  39122. this._uniformBuffer.updateColor4("reflectionRightColor", this.reflectionFresnelParameters.rightColor, this.reflectionFresnelParameters.bias);
  39123. }
  39124. if (this.refractionFresnelParameters && this.refractionFresnelParameters.isEnabled) {
  39125. this._uniformBuffer.updateColor4("refractionLeftColor", this.refractionFresnelParameters.leftColor, this.refractionFresnelParameters.power);
  39126. this._uniformBuffer.updateColor4("refractionRightColor", this.refractionFresnelParameters.rightColor, this.refractionFresnelParameters.bias);
  39127. }
  39128. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  39129. this._uniformBuffer.updateColor4("emissiveLeftColor", this.emissiveFresnelParameters.leftColor, this.emissiveFresnelParameters.power);
  39130. this._uniformBuffer.updateColor4("emissiveRightColor", this.emissiveFresnelParameters.rightColor, this.emissiveFresnelParameters.bias);
  39131. }
  39132. }
  39133. // Textures
  39134. if (scene.texturesEnabled) {
  39135. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  39136. this._uniformBuffer.updateFloat2("vDiffuseInfos", this._diffuseTexture.coordinatesIndex, this._diffuseTexture.level);
  39137. BABYLON.MaterialHelper.BindTextureMatrix(this._diffuseTexture, this._uniformBuffer, "diffuse");
  39138. }
  39139. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  39140. this._uniformBuffer.updateFloat2("vAmbientInfos", this._ambientTexture.coordinatesIndex, this._ambientTexture.level);
  39141. BABYLON.MaterialHelper.BindTextureMatrix(this._ambientTexture, this._uniformBuffer, "ambient");
  39142. }
  39143. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  39144. this._uniformBuffer.updateFloat2("vOpacityInfos", this._opacityTexture.coordinatesIndex, this._opacityTexture.level);
  39145. BABYLON.MaterialHelper.BindTextureMatrix(this._opacityTexture, this._uniformBuffer, "opacity");
  39146. }
  39147. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  39148. this._uniformBuffer.updateFloat2("vReflectionInfos", this._reflectionTexture.level, this.roughness);
  39149. this._uniformBuffer.updateMatrix("reflectionMatrix", this._reflectionTexture.getReflectionTextureMatrix());
  39150. if (this._reflectionTexture.boundingBoxSize) {
  39151. var cubeTexture = this._reflectionTexture;
  39152. this._uniformBuffer.updateVector3("vReflectionPosition", cubeTexture.boundingBoxPosition);
  39153. this._uniformBuffer.updateVector3("vReflectionSize", cubeTexture.boundingBoxSize);
  39154. }
  39155. }
  39156. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  39157. this._uniformBuffer.updateFloat2("vEmissiveInfos", this._emissiveTexture.coordinatesIndex, this._emissiveTexture.level);
  39158. BABYLON.MaterialHelper.BindTextureMatrix(this._emissiveTexture, this._uniformBuffer, "emissive");
  39159. }
  39160. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  39161. this._uniformBuffer.updateFloat2("vLightmapInfos", this._lightmapTexture.coordinatesIndex, this._lightmapTexture.level);
  39162. BABYLON.MaterialHelper.BindTextureMatrix(this._lightmapTexture, this._uniformBuffer, "lightmap");
  39163. }
  39164. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  39165. this._uniformBuffer.updateFloat2("vSpecularInfos", this._specularTexture.coordinatesIndex, this._specularTexture.level);
  39166. BABYLON.MaterialHelper.BindTextureMatrix(this._specularTexture, this._uniformBuffer, "specular");
  39167. }
  39168. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  39169. this._uniformBuffer.updateFloat3("vBumpInfos", this._bumpTexture.coordinatesIndex, 1.0 / this._bumpTexture.level, this.parallaxScaleBias);
  39170. BABYLON.MaterialHelper.BindTextureMatrix(this._bumpTexture, this._uniformBuffer, "bump");
  39171. if (scene._mirroredCameraPosition) {
  39172. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? 1.0 : -1.0, this._invertNormalMapY ? 1.0 : -1.0);
  39173. }
  39174. else {
  39175. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? -1.0 : 1.0, this._invertNormalMapY ? -1.0 : 1.0);
  39176. }
  39177. }
  39178. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  39179. var depth = 1.0;
  39180. if (!this._refractionTexture.isCube) {
  39181. this._uniformBuffer.updateMatrix("refractionMatrix", this._refractionTexture.getReflectionTextureMatrix());
  39182. if (this._refractionTexture.depth) {
  39183. depth = this._refractionTexture.depth;
  39184. }
  39185. }
  39186. this._uniformBuffer.updateFloat4("vRefractionInfos", this._refractionTexture.level, this.indexOfRefraction, depth, this.invertRefractionY ? -1 : 1);
  39187. }
  39188. }
  39189. // Point size
  39190. if (this.pointsCloud) {
  39191. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  39192. }
  39193. if (defines.SPECULARTERM) {
  39194. this._uniformBuffer.updateColor4("vSpecularColor", this.specularColor, this.specularPower);
  39195. }
  39196. this._uniformBuffer.updateColor3("vEmissiveColor", this.emissiveColor);
  39197. // Diffuse
  39198. this._uniformBuffer.updateColor4("vDiffuseColor", this.diffuseColor, this.alpha * mesh.visibility);
  39199. }
  39200. // Textures
  39201. if (scene.texturesEnabled) {
  39202. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  39203. effect.setTexture("diffuseSampler", this._diffuseTexture);
  39204. }
  39205. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  39206. effect.setTexture("ambientSampler", this._ambientTexture);
  39207. }
  39208. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  39209. effect.setTexture("opacitySampler", this._opacityTexture);
  39210. }
  39211. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  39212. if (this._reflectionTexture.isCube) {
  39213. effect.setTexture("reflectionCubeSampler", this._reflectionTexture);
  39214. }
  39215. else {
  39216. effect.setTexture("reflection2DSampler", this._reflectionTexture);
  39217. }
  39218. }
  39219. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  39220. effect.setTexture("emissiveSampler", this._emissiveTexture);
  39221. }
  39222. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  39223. effect.setTexture("lightmapSampler", this._lightmapTexture);
  39224. }
  39225. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  39226. effect.setTexture("specularSampler", this._specularTexture);
  39227. }
  39228. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  39229. effect.setTexture("bumpSampler", this._bumpTexture);
  39230. }
  39231. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  39232. var depth = 1.0;
  39233. if (this._refractionTexture.isCube) {
  39234. effect.setTexture("refractionCubeSampler", this._refractionTexture);
  39235. }
  39236. else {
  39237. effect.setTexture("refraction2DSampler", this._refractionTexture);
  39238. }
  39239. }
  39240. }
  39241. // Clip plane
  39242. BABYLON.MaterialHelper.BindClipPlane(effect, scene);
  39243. // Colors
  39244. scene.ambientColor.multiplyToRef(this.ambientColor, this._globalAmbientColor);
  39245. BABYLON.MaterialHelper.BindEyePosition(effect, scene);
  39246. effect.setColor3("vAmbientColor", this._globalAmbientColor);
  39247. }
  39248. if (mustRebind || !this.isFrozen) {
  39249. // Lights
  39250. if (scene.lightsEnabled && !this._disableLighting) {
  39251. BABYLON.MaterialHelper.BindLights(scene, mesh, effect, defines, this._maxSimultaneousLights);
  39252. }
  39253. // View
  39254. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || this._reflectionTexture || this._refractionTexture) {
  39255. this.bindView(effect);
  39256. }
  39257. // Fog
  39258. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, effect);
  39259. // Morph targets
  39260. if (defines.NUM_MORPH_INFLUENCERS) {
  39261. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, effect);
  39262. }
  39263. // Log. depth
  39264. BABYLON.MaterialHelper.BindLogDepth(defines, effect, scene);
  39265. // image processing
  39266. if (!this._imageProcessingConfiguration.applyByPostProcess) {
  39267. this._imageProcessingConfiguration.bind(this._activeEffect);
  39268. }
  39269. }
  39270. this._uniformBuffer.update();
  39271. this._afterBind(mesh, this._activeEffect);
  39272. };
  39273. StandardMaterial.prototype.getAnimatables = function () {
  39274. var results = [];
  39275. if (this._diffuseTexture && this._diffuseTexture.animations && this._diffuseTexture.animations.length > 0) {
  39276. results.push(this._diffuseTexture);
  39277. }
  39278. if (this._ambientTexture && this._ambientTexture.animations && this._ambientTexture.animations.length > 0) {
  39279. results.push(this._ambientTexture);
  39280. }
  39281. if (this._opacityTexture && this._opacityTexture.animations && this._opacityTexture.animations.length > 0) {
  39282. results.push(this._opacityTexture);
  39283. }
  39284. if (this._reflectionTexture && this._reflectionTexture.animations && this._reflectionTexture.animations.length > 0) {
  39285. results.push(this._reflectionTexture);
  39286. }
  39287. if (this._emissiveTexture && this._emissiveTexture.animations && this._emissiveTexture.animations.length > 0) {
  39288. results.push(this._emissiveTexture);
  39289. }
  39290. if (this._specularTexture && this._specularTexture.animations && this._specularTexture.animations.length > 0) {
  39291. results.push(this._specularTexture);
  39292. }
  39293. if (this._bumpTexture && this._bumpTexture.animations && this._bumpTexture.animations.length > 0) {
  39294. results.push(this._bumpTexture);
  39295. }
  39296. if (this._lightmapTexture && this._lightmapTexture.animations && this._lightmapTexture.animations.length > 0) {
  39297. results.push(this._lightmapTexture);
  39298. }
  39299. if (this._refractionTexture && this._refractionTexture.animations && this._refractionTexture.animations.length > 0) {
  39300. results.push(this._refractionTexture);
  39301. }
  39302. return results;
  39303. };
  39304. StandardMaterial.prototype.getActiveTextures = function () {
  39305. var activeTextures = _super.prototype.getActiveTextures.call(this);
  39306. if (this._diffuseTexture) {
  39307. activeTextures.push(this._diffuseTexture);
  39308. }
  39309. if (this._ambientTexture) {
  39310. activeTextures.push(this._ambientTexture);
  39311. }
  39312. if (this._opacityTexture) {
  39313. activeTextures.push(this._opacityTexture);
  39314. }
  39315. if (this._reflectionTexture) {
  39316. activeTextures.push(this._reflectionTexture);
  39317. }
  39318. if (this._emissiveTexture) {
  39319. activeTextures.push(this._emissiveTexture);
  39320. }
  39321. if (this._specularTexture) {
  39322. activeTextures.push(this._specularTexture);
  39323. }
  39324. if (this._bumpTexture) {
  39325. activeTextures.push(this._bumpTexture);
  39326. }
  39327. if (this._lightmapTexture) {
  39328. activeTextures.push(this._lightmapTexture);
  39329. }
  39330. if (this._refractionTexture) {
  39331. activeTextures.push(this._refractionTexture);
  39332. }
  39333. return activeTextures;
  39334. };
  39335. StandardMaterial.prototype.hasTexture = function (texture) {
  39336. if (_super.prototype.hasTexture.call(this, texture)) {
  39337. return true;
  39338. }
  39339. if (this._diffuseTexture === texture) {
  39340. return true;
  39341. }
  39342. if (this._ambientTexture === texture) {
  39343. return true;
  39344. }
  39345. if (this._opacityTexture === texture) {
  39346. return true;
  39347. }
  39348. if (this._reflectionTexture === texture) {
  39349. return true;
  39350. }
  39351. if (this._emissiveTexture === texture) {
  39352. return true;
  39353. }
  39354. if (this._specularTexture === texture) {
  39355. return true;
  39356. }
  39357. if (this._bumpTexture === texture) {
  39358. return true;
  39359. }
  39360. if (this._lightmapTexture === texture) {
  39361. return true;
  39362. }
  39363. if (this._refractionTexture === texture) {
  39364. return true;
  39365. }
  39366. return false;
  39367. };
  39368. StandardMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  39369. if (forceDisposeTextures) {
  39370. if (this._diffuseTexture) {
  39371. this._diffuseTexture.dispose();
  39372. }
  39373. if (this._ambientTexture) {
  39374. this._ambientTexture.dispose();
  39375. }
  39376. if (this._opacityTexture) {
  39377. this._opacityTexture.dispose();
  39378. }
  39379. if (this._reflectionTexture) {
  39380. this._reflectionTexture.dispose();
  39381. }
  39382. if (this._emissiveTexture) {
  39383. this._emissiveTexture.dispose();
  39384. }
  39385. if (this._specularTexture) {
  39386. this._specularTexture.dispose();
  39387. }
  39388. if (this._bumpTexture) {
  39389. this._bumpTexture.dispose();
  39390. }
  39391. if (this._lightmapTexture) {
  39392. this._lightmapTexture.dispose();
  39393. }
  39394. if (this._refractionTexture) {
  39395. this._refractionTexture.dispose();
  39396. }
  39397. }
  39398. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  39399. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  39400. }
  39401. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  39402. };
  39403. StandardMaterial.prototype.clone = function (name) {
  39404. var _this = this;
  39405. var result = BABYLON.SerializationHelper.Clone(function () { return new StandardMaterial(name, _this.getScene()); }, this);
  39406. result.name = name;
  39407. result.id = name;
  39408. return result;
  39409. };
  39410. StandardMaterial.prototype.serialize = function () {
  39411. return BABYLON.SerializationHelper.Serialize(this);
  39412. };
  39413. // Statics
  39414. StandardMaterial.Parse = function (source, scene, rootUrl) {
  39415. return BABYLON.SerializationHelper.Parse(function () { return new StandardMaterial(source.name, scene); }, source, scene, rootUrl);
  39416. };
  39417. Object.defineProperty(StandardMaterial, "DiffuseTextureEnabled", {
  39418. get: function () {
  39419. return StandardMaterial._DiffuseTextureEnabled;
  39420. },
  39421. set: function (value) {
  39422. if (StandardMaterial._DiffuseTextureEnabled === value) {
  39423. return;
  39424. }
  39425. StandardMaterial._DiffuseTextureEnabled = value;
  39426. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  39427. },
  39428. enumerable: true,
  39429. configurable: true
  39430. });
  39431. Object.defineProperty(StandardMaterial, "AmbientTextureEnabled", {
  39432. get: function () {
  39433. return StandardMaterial._AmbientTextureEnabled;
  39434. },
  39435. set: function (value) {
  39436. if (StandardMaterial._AmbientTextureEnabled === value) {
  39437. return;
  39438. }
  39439. StandardMaterial._AmbientTextureEnabled = value;
  39440. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  39441. },
  39442. enumerable: true,
  39443. configurable: true
  39444. });
  39445. Object.defineProperty(StandardMaterial, "OpacityTextureEnabled", {
  39446. get: function () {
  39447. return StandardMaterial._OpacityTextureEnabled;
  39448. },
  39449. set: function (value) {
  39450. if (StandardMaterial._OpacityTextureEnabled === value) {
  39451. return;
  39452. }
  39453. StandardMaterial._OpacityTextureEnabled = value;
  39454. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  39455. },
  39456. enumerable: true,
  39457. configurable: true
  39458. });
  39459. Object.defineProperty(StandardMaterial, "ReflectionTextureEnabled", {
  39460. get: function () {
  39461. return StandardMaterial._ReflectionTextureEnabled;
  39462. },
  39463. set: function (value) {
  39464. if (StandardMaterial._ReflectionTextureEnabled === value) {
  39465. return;
  39466. }
  39467. StandardMaterial._ReflectionTextureEnabled = value;
  39468. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  39469. },
  39470. enumerable: true,
  39471. configurable: true
  39472. });
  39473. Object.defineProperty(StandardMaterial, "EmissiveTextureEnabled", {
  39474. get: function () {
  39475. return StandardMaterial._EmissiveTextureEnabled;
  39476. },
  39477. set: function (value) {
  39478. if (StandardMaterial._EmissiveTextureEnabled === value) {
  39479. return;
  39480. }
  39481. StandardMaterial._EmissiveTextureEnabled = value;
  39482. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  39483. },
  39484. enumerable: true,
  39485. configurable: true
  39486. });
  39487. Object.defineProperty(StandardMaterial, "SpecularTextureEnabled", {
  39488. get: function () {
  39489. return StandardMaterial._SpecularTextureEnabled;
  39490. },
  39491. set: function (value) {
  39492. if (StandardMaterial._SpecularTextureEnabled === value) {
  39493. return;
  39494. }
  39495. StandardMaterial._SpecularTextureEnabled = value;
  39496. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  39497. },
  39498. enumerable: true,
  39499. configurable: true
  39500. });
  39501. Object.defineProperty(StandardMaterial, "BumpTextureEnabled", {
  39502. get: function () {
  39503. return StandardMaterial._BumpTextureEnabled;
  39504. },
  39505. set: function (value) {
  39506. if (StandardMaterial._BumpTextureEnabled === value) {
  39507. return;
  39508. }
  39509. StandardMaterial._BumpTextureEnabled = value;
  39510. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  39511. },
  39512. enumerable: true,
  39513. configurable: true
  39514. });
  39515. Object.defineProperty(StandardMaterial, "LightmapTextureEnabled", {
  39516. get: function () {
  39517. return StandardMaterial._LightmapTextureEnabled;
  39518. },
  39519. set: function (value) {
  39520. if (StandardMaterial._LightmapTextureEnabled === value) {
  39521. return;
  39522. }
  39523. StandardMaterial._LightmapTextureEnabled = value;
  39524. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  39525. },
  39526. enumerable: true,
  39527. configurable: true
  39528. });
  39529. Object.defineProperty(StandardMaterial, "RefractionTextureEnabled", {
  39530. get: function () {
  39531. return StandardMaterial._RefractionTextureEnabled;
  39532. },
  39533. set: function (value) {
  39534. if (StandardMaterial._RefractionTextureEnabled === value) {
  39535. return;
  39536. }
  39537. StandardMaterial._RefractionTextureEnabled = value;
  39538. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  39539. },
  39540. enumerable: true,
  39541. configurable: true
  39542. });
  39543. Object.defineProperty(StandardMaterial, "ColorGradingTextureEnabled", {
  39544. get: function () {
  39545. return StandardMaterial._ColorGradingTextureEnabled;
  39546. },
  39547. set: function (value) {
  39548. if (StandardMaterial._ColorGradingTextureEnabled === value) {
  39549. return;
  39550. }
  39551. StandardMaterial._ColorGradingTextureEnabled = value;
  39552. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  39553. },
  39554. enumerable: true,
  39555. configurable: true
  39556. });
  39557. Object.defineProperty(StandardMaterial, "FresnelEnabled", {
  39558. get: function () {
  39559. return StandardMaterial._FresnelEnabled;
  39560. },
  39561. set: function (value) {
  39562. if (StandardMaterial._FresnelEnabled === value) {
  39563. return;
  39564. }
  39565. StandardMaterial._FresnelEnabled = value;
  39566. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.FresnelDirtyFlag);
  39567. },
  39568. enumerable: true,
  39569. configurable: true
  39570. });
  39571. // Flags used to enable or disable a type of texture for all Standard Materials
  39572. StandardMaterial._DiffuseTextureEnabled = true;
  39573. StandardMaterial._AmbientTextureEnabled = true;
  39574. StandardMaterial._OpacityTextureEnabled = true;
  39575. StandardMaterial._ReflectionTextureEnabled = true;
  39576. StandardMaterial._EmissiveTextureEnabled = true;
  39577. StandardMaterial._SpecularTextureEnabled = true;
  39578. StandardMaterial._BumpTextureEnabled = true;
  39579. StandardMaterial._LightmapTextureEnabled = true;
  39580. StandardMaterial._RefractionTextureEnabled = true;
  39581. StandardMaterial._ColorGradingTextureEnabled = true;
  39582. StandardMaterial._FresnelEnabled = true;
  39583. __decorate([
  39584. BABYLON.serializeAsTexture("diffuseTexture")
  39585. ], StandardMaterial.prototype, "_diffuseTexture", void 0);
  39586. __decorate([
  39587. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  39588. ], StandardMaterial.prototype, "diffuseTexture", void 0);
  39589. __decorate([
  39590. BABYLON.serializeAsTexture("ambientTexture")
  39591. ], StandardMaterial.prototype, "_ambientTexture", void 0);
  39592. __decorate([
  39593. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39594. ], StandardMaterial.prototype, "ambientTexture", void 0);
  39595. __decorate([
  39596. BABYLON.serializeAsTexture("opacityTexture")
  39597. ], StandardMaterial.prototype, "_opacityTexture", void 0);
  39598. __decorate([
  39599. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  39600. ], StandardMaterial.prototype, "opacityTexture", void 0);
  39601. __decorate([
  39602. BABYLON.serializeAsTexture("reflectionTexture")
  39603. ], StandardMaterial.prototype, "_reflectionTexture", void 0);
  39604. __decorate([
  39605. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39606. ], StandardMaterial.prototype, "reflectionTexture", void 0);
  39607. __decorate([
  39608. BABYLON.serializeAsTexture("emissiveTexture")
  39609. ], StandardMaterial.prototype, "_emissiveTexture", void 0);
  39610. __decorate([
  39611. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39612. ], StandardMaterial.prototype, "emissiveTexture", void 0);
  39613. __decorate([
  39614. BABYLON.serializeAsTexture("specularTexture")
  39615. ], StandardMaterial.prototype, "_specularTexture", void 0);
  39616. __decorate([
  39617. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39618. ], StandardMaterial.prototype, "specularTexture", void 0);
  39619. __decorate([
  39620. BABYLON.serializeAsTexture("bumpTexture")
  39621. ], StandardMaterial.prototype, "_bumpTexture", void 0);
  39622. __decorate([
  39623. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39624. ], StandardMaterial.prototype, "bumpTexture", void 0);
  39625. __decorate([
  39626. BABYLON.serializeAsTexture("lightmapTexture")
  39627. ], StandardMaterial.prototype, "_lightmapTexture", void 0);
  39628. __decorate([
  39629. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39630. ], StandardMaterial.prototype, "lightmapTexture", void 0);
  39631. __decorate([
  39632. BABYLON.serializeAsTexture("refractionTexture")
  39633. ], StandardMaterial.prototype, "_refractionTexture", void 0);
  39634. __decorate([
  39635. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39636. ], StandardMaterial.prototype, "refractionTexture", void 0);
  39637. __decorate([
  39638. BABYLON.serializeAsColor3("ambient")
  39639. ], StandardMaterial.prototype, "ambientColor", void 0);
  39640. __decorate([
  39641. BABYLON.serializeAsColor3("diffuse")
  39642. ], StandardMaterial.prototype, "diffuseColor", void 0);
  39643. __decorate([
  39644. BABYLON.serializeAsColor3("specular")
  39645. ], StandardMaterial.prototype, "specularColor", void 0);
  39646. __decorate([
  39647. BABYLON.serializeAsColor3("emissive")
  39648. ], StandardMaterial.prototype, "emissiveColor", void 0);
  39649. __decorate([
  39650. BABYLON.serialize()
  39651. ], StandardMaterial.prototype, "specularPower", void 0);
  39652. __decorate([
  39653. BABYLON.serialize("useAlphaFromDiffuseTexture")
  39654. ], StandardMaterial.prototype, "_useAlphaFromDiffuseTexture", void 0);
  39655. __decorate([
  39656. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39657. ], StandardMaterial.prototype, "useAlphaFromDiffuseTexture", void 0);
  39658. __decorate([
  39659. BABYLON.serialize("useEmissiveAsIllumination")
  39660. ], StandardMaterial.prototype, "_useEmissiveAsIllumination", void 0);
  39661. __decorate([
  39662. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39663. ], StandardMaterial.prototype, "useEmissiveAsIllumination", void 0);
  39664. __decorate([
  39665. BABYLON.serialize("linkEmissiveWithDiffuse")
  39666. ], StandardMaterial.prototype, "_linkEmissiveWithDiffuse", void 0);
  39667. __decorate([
  39668. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39669. ], StandardMaterial.prototype, "linkEmissiveWithDiffuse", void 0);
  39670. __decorate([
  39671. BABYLON.serialize("useSpecularOverAlpha")
  39672. ], StandardMaterial.prototype, "_useSpecularOverAlpha", void 0);
  39673. __decorate([
  39674. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39675. ], StandardMaterial.prototype, "useSpecularOverAlpha", void 0);
  39676. __decorate([
  39677. BABYLON.serialize("useReflectionOverAlpha")
  39678. ], StandardMaterial.prototype, "_useReflectionOverAlpha", void 0);
  39679. __decorate([
  39680. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39681. ], StandardMaterial.prototype, "useReflectionOverAlpha", void 0);
  39682. __decorate([
  39683. BABYLON.serialize("disableLighting")
  39684. ], StandardMaterial.prototype, "_disableLighting", void 0);
  39685. __decorate([
  39686. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  39687. ], StandardMaterial.prototype, "disableLighting", void 0);
  39688. __decorate([
  39689. BABYLON.serialize("useObjectSpaceNormalMap")
  39690. ], StandardMaterial.prototype, "_useObjectSpaceNormalMap", void 0);
  39691. __decorate([
  39692. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39693. ], StandardMaterial.prototype, "useObjectSpaceNormalMap", void 0);
  39694. __decorate([
  39695. BABYLON.serialize("useParallax")
  39696. ], StandardMaterial.prototype, "_useParallax", void 0);
  39697. __decorate([
  39698. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39699. ], StandardMaterial.prototype, "useParallax", void 0);
  39700. __decorate([
  39701. BABYLON.serialize("useParallaxOcclusion")
  39702. ], StandardMaterial.prototype, "_useParallaxOcclusion", void 0);
  39703. __decorate([
  39704. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39705. ], StandardMaterial.prototype, "useParallaxOcclusion", void 0);
  39706. __decorate([
  39707. BABYLON.serialize()
  39708. ], StandardMaterial.prototype, "parallaxScaleBias", void 0);
  39709. __decorate([
  39710. BABYLON.serialize("roughness")
  39711. ], StandardMaterial.prototype, "_roughness", void 0);
  39712. __decorate([
  39713. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39714. ], StandardMaterial.prototype, "roughness", void 0);
  39715. __decorate([
  39716. BABYLON.serialize()
  39717. ], StandardMaterial.prototype, "indexOfRefraction", void 0);
  39718. __decorate([
  39719. BABYLON.serialize()
  39720. ], StandardMaterial.prototype, "invertRefractionY", void 0);
  39721. __decorate([
  39722. BABYLON.serialize("useLightmapAsShadowmap")
  39723. ], StandardMaterial.prototype, "_useLightmapAsShadowmap", void 0);
  39724. __decorate([
  39725. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39726. ], StandardMaterial.prototype, "useLightmapAsShadowmap", void 0);
  39727. __decorate([
  39728. BABYLON.serializeAsFresnelParameters("diffuseFresnelParameters")
  39729. ], StandardMaterial.prototype, "_diffuseFresnelParameters", void 0);
  39730. __decorate([
  39731. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  39732. ], StandardMaterial.prototype, "diffuseFresnelParameters", void 0);
  39733. __decorate([
  39734. BABYLON.serializeAsFresnelParameters("opacityFresnelParameters")
  39735. ], StandardMaterial.prototype, "_opacityFresnelParameters", void 0);
  39736. __decorate([
  39737. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelAndMiscDirty")
  39738. ], StandardMaterial.prototype, "opacityFresnelParameters", void 0);
  39739. __decorate([
  39740. BABYLON.serializeAsFresnelParameters("reflectionFresnelParameters")
  39741. ], StandardMaterial.prototype, "_reflectionFresnelParameters", void 0);
  39742. __decorate([
  39743. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  39744. ], StandardMaterial.prototype, "reflectionFresnelParameters", void 0);
  39745. __decorate([
  39746. BABYLON.serializeAsFresnelParameters("refractionFresnelParameters")
  39747. ], StandardMaterial.prototype, "_refractionFresnelParameters", void 0);
  39748. __decorate([
  39749. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  39750. ], StandardMaterial.prototype, "refractionFresnelParameters", void 0);
  39751. __decorate([
  39752. BABYLON.serializeAsFresnelParameters("emissiveFresnelParameters")
  39753. ], StandardMaterial.prototype, "_emissiveFresnelParameters", void 0);
  39754. __decorate([
  39755. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  39756. ], StandardMaterial.prototype, "emissiveFresnelParameters", void 0);
  39757. __decorate([
  39758. BABYLON.serialize("useReflectionFresnelFromSpecular")
  39759. ], StandardMaterial.prototype, "_useReflectionFresnelFromSpecular", void 0);
  39760. __decorate([
  39761. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  39762. ], StandardMaterial.prototype, "useReflectionFresnelFromSpecular", void 0);
  39763. __decorate([
  39764. BABYLON.serialize("useGlossinessFromSpecularMapAlpha")
  39765. ], StandardMaterial.prototype, "_useGlossinessFromSpecularMapAlpha", void 0);
  39766. __decorate([
  39767. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39768. ], StandardMaterial.prototype, "useGlossinessFromSpecularMapAlpha", void 0);
  39769. __decorate([
  39770. BABYLON.serialize("maxSimultaneousLights")
  39771. ], StandardMaterial.prototype, "_maxSimultaneousLights", void 0);
  39772. __decorate([
  39773. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  39774. ], StandardMaterial.prototype, "maxSimultaneousLights", void 0);
  39775. __decorate([
  39776. BABYLON.serialize("invertNormalMapX")
  39777. ], StandardMaterial.prototype, "_invertNormalMapX", void 0);
  39778. __decorate([
  39779. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39780. ], StandardMaterial.prototype, "invertNormalMapX", void 0);
  39781. __decorate([
  39782. BABYLON.serialize("invertNormalMapY")
  39783. ], StandardMaterial.prototype, "_invertNormalMapY", void 0);
  39784. __decorate([
  39785. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39786. ], StandardMaterial.prototype, "invertNormalMapY", void 0);
  39787. __decorate([
  39788. BABYLON.serialize("twoSidedLighting")
  39789. ], StandardMaterial.prototype, "_twoSidedLighting", void 0);
  39790. __decorate([
  39791. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39792. ], StandardMaterial.prototype, "twoSidedLighting", void 0);
  39793. __decorate([
  39794. BABYLON.serialize()
  39795. ], StandardMaterial.prototype, "useLogarithmicDepth", null);
  39796. return StandardMaterial;
  39797. }(BABYLON.PushMaterial));
  39798. BABYLON.StandardMaterial = StandardMaterial;
  39799. })(BABYLON || (BABYLON = {}));
  39800. //# sourceMappingURL=babylon.standardMaterial.js.map
  39801. var BABYLON;
  39802. (function (BABYLON) {
  39803. /**
  39804. * Manages the defines for the PBR Material.
  39805. */
  39806. var PBRMaterialDefines = /** @class */ (function (_super) {
  39807. __extends(PBRMaterialDefines, _super);
  39808. /**
  39809. * Initializes the PBR Material defines.
  39810. */
  39811. function PBRMaterialDefines() {
  39812. var _this = _super.call(this) || this;
  39813. _this.PBR = true;
  39814. _this.MAINUV1 = false;
  39815. _this.MAINUV2 = false;
  39816. _this.UV1 = false;
  39817. _this.UV2 = false;
  39818. _this.ALBEDO = false;
  39819. _this.ALBEDODIRECTUV = 0;
  39820. _this.VERTEXCOLOR = false;
  39821. _this.AMBIENT = false;
  39822. _this.AMBIENTDIRECTUV = 0;
  39823. _this.AMBIENTINGRAYSCALE = false;
  39824. _this.OPACITY = false;
  39825. _this.VERTEXALPHA = false;
  39826. _this.OPACITYDIRECTUV = 0;
  39827. _this.OPACITYRGB = false;
  39828. _this.ALPHATEST = false;
  39829. _this.DEPTHPREPASS = false;
  39830. _this.ALPHABLEND = false;
  39831. _this.ALPHAFROMALBEDO = false;
  39832. _this.ALPHATESTVALUE = 0.5;
  39833. _this.SPECULAROVERALPHA = false;
  39834. _this.RADIANCEOVERALPHA = false;
  39835. _this.ALPHAFRESNEL = false;
  39836. _this.LINEARALPHAFRESNEL = false;
  39837. _this.PREMULTIPLYALPHA = false;
  39838. _this.EMISSIVE = false;
  39839. _this.EMISSIVEDIRECTUV = 0;
  39840. _this.REFLECTIVITY = false;
  39841. _this.REFLECTIVITYDIRECTUV = 0;
  39842. _this.SPECULARTERM = false;
  39843. _this.MICROSURFACEFROMREFLECTIVITYMAP = false;
  39844. _this.MICROSURFACEAUTOMATIC = false;
  39845. _this.LODBASEDMICROSFURACE = false;
  39846. _this.MICROSURFACEMAP = false;
  39847. _this.MICROSURFACEMAPDIRECTUV = 0;
  39848. _this.METALLICWORKFLOW = false;
  39849. _this.ROUGHNESSSTOREINMETALMAPALPHA = false;
  39850. _this.ROUGHNESSSTOREINMETALMAPGREEN = false;
  39851. _this.METALLNESSSTOREINMETALMAPBLUE = false;
  39852. _this.AOSTOREINMETALMAPRED = false;
  39853. _this.ENVIRONMENTBRDF = false;
  39854. _this.NORMAL = false;
  39855. _this.TANGENT = false;
  39856. _this.BUMP = false;
  39857. _this.BUMPDIRECTUV = 0;
  39858. _this.OBJECTSPACE_NORMALMAP = false;
  39859. _this.PARALLAX = false;
  39860. _this.PARALLAXOCCLUSION = false;
  39861. _this.NORMALXYSCALE = true;
  39862. _this.LIGHTMAP = false;
  39863. _this.LIGHTMAPDIRECTUV = 0;
  39864. _this.USELIGHTMAPASSHADOWMAP = false;
  39865. _this.REFLECTION = false;
  39866. _this.REFLECTIONMAP_3D = false;
  39867. _this.REFLECTIONMAP_SPHERICAL = false;
  39868. _this.REFLECTIONMAP_PLANAR = false;
  39869. _this.REFLECTIONMAP_CUBIC = false;
  39870. _this.USE_LOCAL_REFLECTIONMAP_CUBIC = false;
  39871. _this.REFLECTIONMAP_PROJECTION = false;
  39872. _this.REFLECTIONMAP_SKYBOX = false;
  39873. _this.REFLECTIONMAP_EXPLICIT = false;
  39874. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  39875. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  39876. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  39877. _this.INVERTCUBICMAP = false;
  39878. _this.USESPHERICALFROMREFLECTIONMAP = false;
  39879. _this.USESPHERICALINVERTEX = false;
  39880. _this.REFLECTIONMAP_OPPOSITEZ = false;
  39881. _this.LODINREFLECTIONALPHA = false;
  39882. _this.GAMMAREFLECTION = false;
  39883. _this.RADIANCEOCCLUSION = false;
  39884. _this.HORIZONOCCLUSION = false;
  39885. _this.REFRACTION = false;
  39886. _this.REFRACTIONMAP_3D = false;
  39887. _this.REFRACTIONMAP_OPPOSITEZ = false;
  39888. _this.LODINREFRACTIONALPHA = false;
  39889. _this.GAMMAREFRACTION = false;
  39890. _this.LINKREFRACTIONTOTRANSPARENCY = false;
  39891. _this.INSTANCES = false;
  39892. _this.NUM_BONE_INFLUENCERS = 0;
  39893. _this.BonesPerMesh = 0;
  39894. _this.NONUNIFORMSCALING = false;
  39895. _this.MORPHTARGETS = false;
  39896. _this.MORPHTARGETS_NORMAL = false;
  39897. _this.MORPHTARGETS_TANGENT = false;
  39898. _this.NUM_MORPH_INFLUENCERS = 0;
  39899. _this.IMAGEPROCESSING = false;
  39900. _this.VIGNETTE = false;
  39901. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  39902. _this.VIGNETTEBLENDMODEOPAQUE = false;
  39903. _this.TONEMAPPING = false;
  39904. _this.CONTRAST = false;
  39905. _this.COLORCURVES = false;
  39906. _this.COLORGRADING = false;
  39907. _this.COLORGRADING3D = false;
  39908. _this.SAMPLER3DGREENDEPTH = false;
  39909. _this.SAMPLER3DBGRMAP = false;
  39910. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  39911. _this.EXPOSURE = false;
  39912. _this.USEPHYSICALLIGHTFALLOFF = false;
  39913. _this.TWOSIDEDLIGHTING = false;
  39914. _this.SHADOWFLOAT = false;
  39915. _this.CLIPPLANE = false;
  39916. _this.POINTSIZE = false;
  39917. _this.FOG = false;
  39918. _this.LOGARITHMICDEPTH = false;
  39919. _this.FORCENORMALFORWARD = false;
  39920. _this.rebuild();
  39921. return _this;
  39922. }
  39923. /**
  39924. * Resets the PBR Material defines.
  39925. */
  39926. PBRMaterialDefines.prototype.reset = function () {
  39927. _super.prototype.reset.call(this);
  39928. this.ALPHATESTVALUE = 0.5;
  39929. this.PBR = true;
  39930. };
  39931. return PBRMaterialDefines;
  39932. }(BABYLON.MaterialDefines));
  39933. /**
  39934. * The Physically based material base class of BJS.
  39935. *
  39936. * This offers the main features of a standard PBR material.
  39937. * For more information, please refer to the documentation :
  39938. * http://doc.babylonjs.com/extensions/Physically_Based_Rendering
  39939. */
  39940. var PBRBaseMaterial = /** @class */ (function (_super) {
  39941. __extends(PBRBaseMaterial, _super);
  39942. /**
  39943. * Instantiates a new PBRMaterial instance.
  39944. *
  39945. * @param name The material name
  39946. * @param scene The scene the material will be use in.
  39947. */
  39948. function PBRBaseMaterial(name, scene) {
  39949. var _this = _super.call(this, name, scene) || this;
  39950. /**
  39951. * Intensity of the direct lights e.g. the four lights available in your scene.
  39952. * This impacts both the direct diffuse and specular highlights.
  39953. */
  39954. _this._directIntensity = 1.0;
  39955. /**
  39956. * Intensity of the emissive part of the material.
  39957. * This helps controlling the emissive effect without modifying the emissive color.
  39958. */
  39959. _this._emissiveIntensity = 1.0;
  39960. /**
  39961. * Intensity of the environment e.g. how much the environment will light the object
  39962. * either through harmonics for rough material or through the refelction for shiny ones.
  39963. */
  39964. _this._environmentIntensity = 1.0;
  39965. /**
  39966. * This is a special control allowing the reduction of the specular highlights coming from the
  39967. * four lights of the scene. Those highlights may not be needed in full environment lighting.
  39968. */
  39969. _this._specularIntensity = 1.0;
  39970. /**
  39971. * This stores the direct, emissive, environment, and specular light intensities into a Vector4.
  39972. */
  39973. _this._lightingInfos = new BABYLON.Vector4(_this._directIntensity, _this._emissiveIntensity, _this._environmentIntensity, _this._specularIntensity);
  39974. /**
  39975. * Debug Control allowing disabling the bump map on this material.
  39976. */
  39977. _this._disableBumpMap = false;
  39978. /**
  39979. * AKA Occlusion Texture Intensity in other nomenclature.
  39980. */
  39981. _this._ambientTextureStrength = 1.0;
  39982. /**
  39983. * The color of a material in ambient lighting.
  39984. */
  39985. _this._ambientColor = new BABYLON.Color3(0, 0, 0);
  39986. /**
  39987. * AKA Diffuse Color in other nomenclature.
  39988. */
  39989. _this._albedoColor = new BABYLON.Color3(1, 1, 1);
  39990. /**
  39991. * AKA Specular Color in other nomenclature.
  39992. */
  39993. _this._reflectivityColor = new BABYLON.Color3(1, 1, 1);
  39994. /**
  39995. * The color applied when light is reflected from a material.
  39996. */
  39997. _this._reflectionColor = new BABYLON.Color3(1, 1, 1);
  39998. /**
  39999. * The color applied when light is emitted from a material.
  40000. */
  40001. _this._emissiveColor = new BABYLON.Color3(0, 0, 0);
  40002. /**
  40003. * AKA Glossiness in other nomenclature.
  40004. */
  40005. _this._microSurface = 0.9;
  40006. /**
  40007. * source material index of refraction (IOR)' / 'destination material IOR.
  40008. */
  40009. _this._indexOfRefraction = 0.66;
  40010. /**
  40011. * Controls if refraction needs to be inverted on Y. This could be usefull for procedural texture.
  40012. */
  40013. _this._invertRefractionY = false;
  40014. /**
  40015. * This parameters will make the material used its opacity to control how much it is refracting aginst not.
  40016. * Materials half opaque for instance using refraction could benefit from this control.
  40017. */
  40018. _this._linkRefractionWithTransparency = false;
  40019. /**
  40020. * Specifies that the material will use the light map as a show map.
  40021. */
  40022. _this._useLightmapAsShadowmap = false;
  40023. /**
  40024. * This parameters will enable/disable Horizon occlusion to prevent normal maps to look shiny when the normal
  40025. * makes the reflect vector face the model (under horizon).
  40026. */
  40027. _this._useHorizonOcclusion = true;
  40028. /**
  40029. * This parameters will enable/disable radiance occlusion by preventing the radiance to lit
  40030. * too much the area relying on ambient texture to define their ambient occlusion.
  40031. */
  40032. _this._useRadianceOcclusion = true;
  40033. /**
  40034. * Specifies that the alpha is coming form the albedo channel alpha channel for alpha blending.
  40035. */
  40036. _this._useAlphaFromAlbedoTexture = false;
  40037. /**
  40038. * Specifies that the material will keeps the specular highlights over a transparent surface (only the most limunous ones).
  40039. * A car glass is a good exemple of that. When sun reflects on it you can not see what is behind.
  40040. */
  40041. _this._useSpecularOverAlpha = true;
  40042. /**
  40043. * Specifies if the reflectivity texture contains the glossiness information in its alpha channel.
  40044. */
  40045. _this._useMicroSurfaceFromReflectivityMapAlpha = false;
  40046. /**
  40047. * Specifies if the metallic texture contains the roughness information in its alpha channel.
  40048. */
  40049. _this._useRoughnessFromMetallicTextureAlpha = true;
  40050. /**
  40051. * Specifies if the metallic texture contains the roughness information in its green channel.
  40052. */
  40053. _this._useRoughnessFromMetallicTextureGreen = false;
  40054. /**
  40055. * Specifies if the metallic texture contains the metallness information in its blue channel.
  40056. */
  40057. _this._useMetallnessFromMetallicTextureBlue = false;
  40058. /**
  40059. * Specifies if the metallic texture contains the ambient occlusion information in its red channel.
  40060. */
  40061. _this._useAmbientOcclusionFromMetallicTextureRed = false;
  40062. /**
  40063. * Specifies if the ambient texture contains the ambient occlusion information in its red channel only.
  40064. */
  40065. _this._useAmbientInGrayScale = false;
  40066. /**
  40067. * In case the reflectivity map does not contain the microsurface information in its alpha channel,
  40068. * The material will try to infer what glossiness each pixel should be.
  40069. */
  40070. _this._useAutoMicroSurfaceFromReflectivityMap = false;
  40071. /**
  40072. * BJS is using an harcoded light falloff based on a manually sets up range.
  40073. * In PBR, one way to represents the fallof is to use the inverse squared root algorythm.
  40074. * This parameter can help you switch back to the BJS mode in order to create scenes using both materials.
  40075. */
  40076. _this._usePhysicalLightFalloff = true;
  40077. /**
  40078. * Specifies that the material will keeps the reflection highlights over a transparent surface (only the most limunous ones).
  40079. * A car glass is a good exemple of that. When the street lights reflects on it you can not see what is behind.
  40080. */
  40081. _this._useRadianceOverAlpha = true;
  40082. /**
  40083. * Allows using an object space normal map (instead of tangent space).
  40084. */
  40085. _this._useObjectSpaceNormalMap = false;
  40086. /**
  40087. * Allows using the bump map in parallax mode.
  40088. */
  40089. _this._useParallax = false;
  40090. /**
  40091. * Allows using the bump map in parallax occlusion mode.
  40092. */
  40093. _this._useParallaxOcclusion = false;
  40094. /**
  40095. * Controls the scale bias of the parallax mode.
  40096. */
  40097. _this._parallaxScaleBias = 0.05;
  40098. /**
  40099. * If sets to true, disables all the lights affecting the material.
  40100. */
  40101. _this._disableLighting = false;
  40102. /**
  40103. * Number of Simultaneous lights allowed on the material.
  40104. */
  40105. _this._maxSimultaneousLights = 4;
  40106. /**
  40107. * If sets to true, x component of normal map value will be inverted (x = 1.0 - x).
  40108. */
  40109. _this._invertNormalMapX = false;
  40110. /**
  40111. * If sets to true, y component of normal map value will be inverted (y = 1.0 - y).
  40112. */
  40113. _this._invertNormalMapY = false;
  40114. /**
  40115. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  40116. */
  40117. _this._twoSidedLighting = false;
  40118. /**
  40119. * Defines the alpha limits in alpha test mode.
  40120. */
  40121. _this._alphaCutOff = 0.4;
  40122. /**
  40123. * Enforces alpha test in opaque or blend mode in order to improve the performances of some situations.
  40124. */
  40125. _this._forceAlphaTest = false;
  40126. /**
  40127. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  40128. * And/Or occlude the blended part. (alpha is converted to gamma to compute the fresnel)
  40129. */
  40130. _this._useAlphaFresnel = false;
  40131. /**
  40132. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  40133. * And/Or occlude the blended part. (alpha stays linear to compute the fresnel)
  40134. */
  40135. _this._useLinearAlphaFresnel = false;
  40136. /**
  40137. * The transparency mode of the material.
  40138. */
  40139. _this._transparencyMode = null;
  40140. /**
  40141. * Specifies the environment BRDF texture used to comput the scale and offset roughness values
  40142. * from cos thetav and roughness:
  40143. * http://blog.selfshadow.com/publications/s2013-shading-course/karis/s2013_pbs_epic_notes_v2.pdf
  40144. */
  40145. _this._environmentBRDFTexture = null;
  40146. /**
  40147. * Force the shader to compute irradiance in the fragment shader in order to take bump in account.
  40148. */
  40149. _this._forceIrradianceInFragment = false;
  40150. /**
  40151. * Force normal to face away from face.
  40152. */
  40153. _this._forceNormalForward = false;
  40154. /**
  40155. * Force metallic workflow.
  40156. */
  40157. _this._forceMetallicWorkflow = false;
  40158. /**
  40159. * Stores the available render targets.
  40160. */
  40161. _this._renderTargets = new BABYLON.SmartArray(16);
  40162. /**
  40163. * Sets the global ambient color for the material used in lighting calculations.
  40164. */
  40165. _this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  40166. // Setup the default processing configuration to the scene.
  40167. _this._attachImageProcessingConfiguration(null);
  40168. _this.getRenderTargetTextures = function () {
  40169. _this._renderTargets.reset();
  40170. if (BABYLON.StandardMaterial.ReflectionTextureEnabled && _this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  40171. _this._renderTargets.push(_this._reflectionTexture);
  40172. }
  40173. if (BABYLON.StandardMaterial.RefractionTextureEnabled && _this._refractionTexture && _this._refractionTexture.isRenderTarget) {
  40174. _this._renderTargets.push(_this._refractionTexture);
  40175. }
  40176. return _this._renderTargets;
  40177. };
  40178. _this._environmentBRDFTexture = BABYLON.TextureTools.GetEnvironmentBRDFTexture(scene);
  40179. return _this;
  40180. }
  40181. /**
  40182. * Attaches a new image processing configuration to the PBR Material.
  40183. * @param configuration
  40184. */
  40185. PBRBaseMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  40186. var _this = this;
  40187. if (configuration === this._imageProcessingConfiguration) {
  40188. return;
  40189. }
  40190. // Detaches observer.
  40191. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  40192. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  40193. }
  40194. // Pick the scene configuration if needed.
  40195. if (!configuration) {
  40196. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  40197. }
  40198. else {
  40199. this._imageProcessingConfiguration = configuration;
  40200. }
  40201. // Attaches observer.
  40202. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  40203. _this._markAllSubMeshesAsImageProcessingDirty();
  40204. });
  40205. };
  40206. /**
  40207. * Gets the name of the material class.
  40208. */
  40209. PBRBaseMaterial.prototype.getClassName = function () {
  40210. return "PBRBaseMaterial";
  40211. };
  40212. Object.defineProperty(PBRBaseMaterial.prototype, "useLogarithmicDepth", {
  40213. /**
  40214. * Enabled the use of logarithmic depth buffers, which is good for wide depth buffers.
  40215. */
  40216. get: function () {
  40217. return this._useLogarithmicDepth;
  40218. },
  40219. /**
  40220. * Enabled the use of logarithmic depth buffers, which is good for wide depth buffers.
  40221. */
  40222. set: function (value) {
  40223. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  40224. },
  40225. enumerable: true,
  40226. configurable: true
  40227. });
  40228. Object.defineProperty(PBRBaseMaterial.prototype, "transparencyMode", {
  40229. /**
  40230. * Gets the current transparency mode.
  40231. */
  40232. get: function () {
  40233. return this._transparencyMode;
  40234. },
  40235. /**
  40236. * Sets the transparency mode of the material.
  40237. */
  40238. set: function (value) {
  40239. if (this._transparencyMode === value) {
  40240. return;
  40241. }
  40242. this._transparencyMode = value;
  40243. this._forceAlphaTest = (value === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATESTANDBLEND);
  40244. this._markAllSubMeshesAsTexturesAndMiscDirty();
  40245. },
  40246. enumerable: true,
  40247. configurable: true
  40248. });
  40249. Object.defineProperty(PBRBaseMaterial.prototype, "_disableAlphaBlending", {
  40250. /**
  40251. * Returns true if alpha blending should be disabled.
  40252. */
  40253. get: function () {
  40254. return (this._linkRefractionWithTransparency ||
  40255. this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE ||
  40256. this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATEST);
  40257. },
  40258. enumerable: true,
  40259. configurable: true
  40260. });
  40261. /**
  40262. * Specifies whether or not this material should be rendered in alpha blend mode.
  40263. */
  40264. PBRBaseMaterial.prototype.needAlphaBlending = function () {
  40265. if (this._disableAlphaBlending) {
  40266. return false;
  40267. }
  40268. return (this.alpha < 1.0) || (this._opacityTexture != null) || this._shouldUseAlphaFromAlbedoTexture();
  40269. };
  40270. /**
  40271. * Specifies if the mesh will require alpha blending.
  40272. * @param mesh - BJS mesh.
  40273. */
  40274. PBRBaseMaterial.prototype.needAlphaBlendingForMesh = function (mesh) {
  40275. if (this._disableAlphaBlending) {
  40276. return false;
  40277. }
  40278. return _super.prototype.needAlphaBlendingForMesh.call(this, mesh);
  40279. };
  40280. /**
  40281. * Specifies whether or not this material should be rendered in alpha test mode.
  40282. */
  40283. PBRBaseMaterial.prototype.needAlphaTesting = function () {
  40284. if (this._forceAlphaTest) {
  40285. return true;
  40286. }
  40287. if (this._linkRefractionWithTransparency) {
  40288. return false;
  40289. }
  40290. return this._albedoTexture != null && this._albedoTexture.hasAlpha && (this._transparencyMode == null || this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATEST);
  40291. };
  40292. /**
  40293. * Specifies whether or not the alpha value of the albedo texture should be used for alpha blending.
  40294. */
  40295. PBRBaseMaterial.prototype._shouldUseAlphaFromAlbedoTexture = function () {
  40296. return this._albedoTexture != null && this._albedoTexture.hasAlpha && this._useAlphaFromAlbedoTexture && this._transparencyMode !== BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE;
  40297. };
  40298. /**
  40299. * Gets the texture used for the alpha test.
  40300. */
  40301. PBRBaseMaterial.prototype.getAlphaTestTexture = function () {
  40302. return this._albedoTexture;
  40303. };
  40304. /**
  40305. * Specifies that the submesh is ready to be used.
  40306. * @param mesh - BJS mesh.
  40307. * @param subMesh - A submesh of the BJS mesh. Used to check if it is ready.
  40308. * @param useInstances - Specifies that instances should be used.
  40309. * @returns - boolean indicating that the submesh is ready or not.
  40310. */
  40311. PBRBaseMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  40312. if (subMesh.effect && this.isFrozen) {
  40313. if (this._wasPreviouslyReady) {
  40314. return true;
  40315. }
  40316. }
  40317. if (!subMesh._materialDefines) {
  40318. subMesh._materialDefines = new PBRMaterialDefines();
  40319. }
  40320. var defines = subMesh._materialDefines;
  40321. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  40322. if (defines._renderId === this.getScene().getRenderId()) {
  40323. return true;
  40324. }
  40325. }
  40326. var scene = this.getScene();
  40327. var engine = scene.getEngine();
  40328. if (defines._areTexturesDirty) {
  40329. if (scene.texturesEnabled) {
  40330. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  40331. if (!this._albedoTexture.isReadyOrNotBlocking()) {
  40332. return false;
  40333. }
  40334. }
  40335. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  40336. if (!this._ambientTexture.isReadyOrNotBlocking()) {
  40337. return false;
  40338. }
  40339. }
  40340. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  40341. if (!this._opacityTexture.isReadyOrNotBlocking()) {
  40342. return false;
  40343. }
  40344. }
  40345. var reflectionTexture = this._getReflectionTexture();
  40346. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  40347. if (!reflectionTexture.isReadyOrNotBlocking()) {
  40348. return false;
  40349. }
  40350. }
  40351. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  40352. if (!this._lightmapTexture.isReadyOrNotBlocking()) {
  40353. return false;
  40354. }
  40355. }
  40356. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  40357. if (!this._emissiveTexture.isReadyOrNotBlocking()) {
  40358. return false;
  40359. }
  40360. }
  40361. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  40362. if (this._metallicTexture) {
  40363. if (!this._metallicTexture.isReadyOrNotBlocking()) {
  40364. return false;
  40365. }
  40366. }
  40367. else if (this._reflectivityTexture) {
  40368. if (!this._reflectivityTexture.isReadyOrNotBlocking()) {
  40369. return false;
  40370. }
  40371. }
  40372. if (this._microSurfaceTexture) {
  40373. if (!this._microSurfaceTexture.isReadyOrNotBlocking()) {
  40374. return false;
  40375. }
  40376. }
  40377. }
  40378. if (engine.getCaps().standardDerivatives && this._bumpTexture && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  40379. // Bump texture cannot be not blocking.
  40380. if (!this._bumpTexture.isReady()) {
  40381. return false;
  40382. }
  40383. }
  40384. var refractionTexture = this._getRefractionTexture();
  40385. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  40386. if (!refractionTexture.isReadyOrNotBlocking()) {
  40387. return false;
  40388. }
  40389. }
  40390. if (this._environmentBRDFTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  40391. // This is blocking.
  40392. if (!this._environmentBRDFTexture.isReady()) {
  40393. return false;
  40394. }
  40395. }
  40396. }
  40397. }
  40398. if (defines._areImageProcessingDirty) {
  40399. if (!this._imageProcessingConfiguration.isReady()) {
  40400. return false;
  40401. }
  40402. }
  40403. if (!engine.getCaps().standardDerivatives) {
  40404. var bufferMesh = null;
  40405. if (mesh.getClassName() === "InstancedMesh") {
  40406. bufferMesh = mesh.sourceMesh;
  40407. }
  40408. else if (mesh.getClassName() === "Mesh") {
  40409. bufferMesh = mesh;
  40410. }
  40411. if (bufferMesh && bufferMesh.geometry && bufferMesh.geometry.isReady() && !bufferMesh.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  40412. bufferMesh.createNormals(true);
  40413. BABYLON.Tools.Warn("PBRMaterial: Normals have been created for the mesh: " + bufferMesh.name);
  40414. }
  40415. }
  40416. var effect = this._prepareEffect(mesh, defines, this.onCompiled, this.onError, useInstances);
  40417. if (effect) {
  40418. scene.resetCachedMaterial();
  40419. subMesh.setEffect(effect, defines);
  40420. this.buildUniformLayout();
  40421. }
  40422. if (!subMesh.effect || !subMesh.effect.isReady()) {
  40423. return false;
  40424. }
  40425. defines._renderId = scene.getRenderId();
  40426. this._wasPreviouslyReady = true;
  40427. return true;
  40428. };
  40429. PBRBaseMaterial.prototype._prepareEffect = function (mesh, defines, onCompiled, onError, useInstances, useClipPlane) {
  40430. if (onCompiled === void 0) { onCompiled = null; }
  40431. if (onError === void 0) { onError = null; }
  40432. if (useInstances === void 0) { useInstances = null; }
  40433. if (useClipPlane === void 0) { useClipPlane = null; }
  40434. this._prepareDefines(mesh, defines, useInstances, useClipPlane);
  40435. if (!defines.isDirty) {
  40436. return null;
  40437. }
  40438. defines.markAsProcessed();
  40439. var scene = this.getScene();
  40440. var engine = scene.getEngine();
  40441. // Fallbacks
  40442. var fallbacks = new BABYLON.EffectFallbacks();
  40443. var fallbackRank = 0;
  40444. if (defines.USESPHERICALINVERTEX) {
  40445. fallbacks.addFallback(fallbackRank++, "USESPHERICALINVERTEX");
  40446. }
  40447. if (defines.FOG) {
  40448. fallbacks.addFallback(fallbackRank, "FOG");
  40449. }
  40450. if (defines.POINTSIZE) {
  40451. fallbacks.addFallback(fallbackRank, "POINTSIZE");
  40452. }
  40453. if (defines.LOGARITHMICDEPTH) {
  40454. fallbacks.addFallback(fallbackRank, "LOGARITHMICDEPTH");
  40455. }
  40456. if (defines.PARALLAX) {
  40457. fallbacks.addFallback(fallbackRank, "PARALLAX");
  40458. }
  40459. if (defines.PARALLAXOCCLUSION) {
  40460. fallbacks.addFallback(fallbackRank++, "PARALLAXOCCLUSION");
  40461. }
  40462. if (defines.ENVIRONMENTBRDF) {
  40463. fallbacks.addFallback(fallbackRank++, "ENVIRONMENTBRDF");
  40464. }
  40465. if (defines.TANGENT) {
  40466. fallbacks.addFallback(fallbackRank++, "TANGENT");
  40467. }
  40468. if (defines.BUMP) {
  40469. fallbacks.addFallback(fallbackRank++, "BUMP");
  40470. }
  40471. fallbackRank = BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights, fallbackRank++);
  40472. if (defines.SPECULARTERM) {
  40473. fallbacks.addFallback(fallbackRank++, "SPECULARTERM");
  40474. }
  40475. if (defines.USESPHERICALFROMREFLECTIONMAP) {
  40476. fallbacks.addFallback(fallbackRank++, "USESPHERICALFROMREFLECTIONMAP");
  40477. }
  40478. if (defines.LIGHTMAP) {
  40479. fallbacks.addFallback(fallbackRank++, "LIGHTMAP");
  40480. }
  40481. if (defines.NORMAL) {
  40482. fallbacks.addFallback(fallbackRank++, "NORMAL");
  40483. }
  40484. if (defines.AMBIENT) {
  40485. fallbacks.addFallback(fallbackRank++, "AMBIENT");
  40486. }
  40487. if (defines.EMISSIVE) {
  40488. fallbacks.addFallback(fallbackRank++, "EMISSIVE");
  40489. }
  40490. if (defines.VERTEXCOLOR) {
  40491. fallbacks.addFallback(fallbackRank++, "VERTEXCOLOR");
  40492. }
  40493. if (defines.NUM_BONE_INFLUENCERS > 0) {
  40494. fallbacks.addCPUSkinningFallback(fallbackRank++, mesh);
  40495. }
  40496. if (defines.MORPHTARGETS) {
  40497. fallbacks.addFallback(fallbackRank++, "MORPHTARGETS");
  40498. }
  40499. //Attributes
  40500. var attribs = [BABYLON.VertexBuffer.PositionKind];
  40501. if (defines.NORMAL) {
  40502. attribs.push(BABYLON.VertexBuffer.NormalKind);
  40503. }
  40504. if (defines.TANGENT) {
  40505. attribs.push(BABYLON.VertexBuffer.TangentKind);
  40506. }
  40507. if (defines.UV1) {
  40508. attribs.push(BABYLON.VertexBuffer.UVKind);
  40509. }
  40510. if (defines.UV2) {
  40511. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  40512. }
  40513. if (defines.VERTEXCOLOR) {
  40514. attribs.push(BABYLON.VertexBuffer.ColorKind);
  40515. }
  40516. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  40517. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  40518. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, defines);
  40519. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vAlbedoColor", "vReflectivityColor", "vEmissiveColor", "vReflectionColor",
  40520. "vFogInfos", "vFogColor", "pointSize",
  40521. "vAlbedoInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vReflectionPosition", "vReflectionSize", "vEmissiveInfos", "vReflectivityInfos",
  40522. "vMicroSurfaceSamplerInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  40523. "mBones",
  40524. "vClipPlane", "albedoMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "reflectivityMatrix", "normalMatrix", "microSurfaceSamplerMatrix", "bumpMatrix", "lightmapMatrix", "refractionMatrix",
  40525. "vLightingIntensity",
  40526. "logarithmicDepthConstant",
  40527. "vSphericalX", "vSphericalY", "vSphericalZ",
  40528. "vSphericalXX", "vSphericalYY", "vSphericalZZ",
  40529. "vSphericalXY", "vSphericalYZ", "vSphericalZX",
  40530. "vReflectionMicrosurfaceInfos", "vRefractionMicrosurfaceInfos",
  40531. "vTangentSpaceParams"
  40532. ];
  40533. var samplers = ["albedoSampler", "reflectivitySampler", "ambientSampler", "emissiveSampler",
  40534. "bumpSampler", "lightmapSampler", "opacitySampler",
  40535. "refractionSampler", "refractionSamplerLow", "refractionSamplerHigh",
  40536. "reflectionSampler", "reflectionSamplerLow", "reflectionSamplerHigh",
  40537. "microSurfaceSampler", "environmentBrdfSampler"];
  40538. var uniformBuffers = ["Material", "Scene"];
  40539. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  40540. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  40541. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  40542. uniformsNames: uniforms,
  40543. uniformBuffersNames: uniformBuffers,
  40544. samplers: samplers,
  40545. defines: defines,
  40546. maxSimultaneousLights: this._maxSimultaneousLights
  40547. });
  40548. var join = defines.toString();
  40549. return engine.createEffect("pbr", {
  40550. attributes: attribs,
  40551. uniformsNames: uniforms,
  40552. uniformBuffersNames: uniformBuffers,
  40553. samplers: samplers,
  40554. defines: join,
  40555. fallbacks: fallbacks,
  40556. onCompiled: onCompiled,
  40557. onError: onError,
  40558. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights, maxSimultaneousMorphTargets: defines.NUM_MORPH_INFLUENCERS }
  40559. }, engine);
  40560. };
  40561. PBRBaseMaterial.prototype._prepareDefines = function (mesh, defines, useInstances, useClipPlane) {
  40562. if (useInstances === void 0) { useInstances = null; }
  40563. if (useClipPlane === void 0) { useClipPlane = null; }
  40564. var scene = this.getScene();
  40565. var engine = scene.getEngine();
  40566. // Lights
  40567. BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, true, this._maxSimultaneousLights, this._disableLighting);
  40568. defines._needNormals = true;
  40569. // Textures
  40570. if (defines._areTexturesDirty) {
  40571. defines._needUVs = false;
  40572. if (scene.texturesEnabled) {
  40573. if (scene.getEngine().getCaps().textureLOD) {
  40574. defines.LODBASEDMICROSFURACE = true;
  40575. }
  40576. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  40577. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._albedoTexture, defines, "ALBEDO");
  40578. }
  40579. else {
  40580. defines.ALBEDO = false;
  40581. }
  40582. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  40583. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._ambientTexture, defines, "AMBIENT");
  40584. defines.AMBIENTINGRAYSCALE = this._useAmbientInGrayScale;
  40585. }
  40586. else {
  40587. defines.AMBIENT = false;
  40588. }
  40589. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  40590. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._opacityTexture, defines, "OPACITY");
  40591. defines.OPACITYRGB = this._opacityTexture.getAlphaFromRGB;
  40592. }
  40593. else {
  40594. defines.OPACITY = false;
  40595. }
  40596. var reflectionTexture = this._getReflectionTexture();
  40597. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  40598. defines.REFLECTION = true;
  40599. defines.GAMMAREFLECTION = reflectionTexture.gammaSpace;
  40600. defines.REFLECTIONMAP_OPPOSITEZ = this.getScene().useRightHandedSystem ? !reflectionTexture.invertZ : reflectionTexture.invertZ;
  40601. defines.LODINREFLECTIONALPHA = reflectionTexture.lodLevelInAlpha;
  40602. if (reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  40603. defines.INVERTCUBICMAP = true;
  40604. }
  40605. defines.REFLECTIONMAP_3D = reflectionTexture.isCube;
  40606. switch (reflectionTexture.coordinatesMode) {
  40607. case BABYLON.Texture.CUBIC_MODE:
  40608. case BABYLON.Texture.INVCUBIC_MODE:
  40609. defines.REFLECTIONMAP_CUBIC = true;
  40610. defines.USE_LOCAL_REFLECTIONMAP_CUBIC = reflectionTexture.boundingBoxSize ? true : false;
  40611. break;
  40612. case BABYLON.Texture.EXPLICIT_MODE:
  40613. defines.REFLECTIONMAP_EXPLICIT = true;
  40614. break;
  40615. case BABYLON.Texture.PLANAR_MODE:
  40616. defines.REFLECTIONMAP_PLANAR = true;
  40617. break;
  40618. case BABYLON.Texture.PROJECTION_MODE:
  40619. defines.REFLECTIONMAP_PROJECTION = true;
  40620. break;
  40621. case BABYLON.Texture.SKYBOX_MODE:
  40622. defines.REFLECTIONMAP_SKYBOX = true;
  40623. break;
  40624. case BABYLON.Texture.SPHERICAL_MODE:
  40625. defines.REFLECTIONMAP_SPHERICAL = true;
  40626. break;
  40627. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  40628. defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  40629. break;
  40630. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  40631. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = true;
  40632. break;
  40633. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  40634. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = true;
  40635. break;
  40636. }
  40637. if (reflectionTexture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) {
  40638. if (reflectionTexture.sphericalPolynomial) {
  40639. defines.USESPHERICALFROMREFLECTIONMAP = true;
  40640. if (this._forceIrradianceInFragment || scene.getEngine().getCaps().maxVaryingVectors <= 8) {
  40641. defines.USESPHERICALINVERTEX = false;
  40642. }
  40643. else {
  40644. defines.USESPHERICALINVERTEX = true;
  40645. }
  40646. }
  40647. }
  40648. }
  40649. else {
  40650. defines.REFLECTION = false;
  40651. defines.REFLECTIONMAP_3D = false;
  40652. defines.REFLECTIONMAP_SPHERICAL = false;
  40653. defines.REFLECTIONMAP_PLANAR = false;
  40654. defines.REFLECTIONMAP_CUBIC = false;
  40655. defines.USE_LOCAL_REFLECTIONMAP_CUBIC = false;
  40656. defines.REFLECTIONMAP_PROJECTION = false;
  40657. defines.REFLECTIONMAP_SKYBOX = false;
  40658. defines.REFLECTIONMAP_EXPLICIT = false;
  40659. defines.REFLECTIONMAP_EQUIRECTANGULAR = false;
  40660. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  40661. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  40662. defines.INVERTCUBICMAP = false;
  40663. defines.USESPHERICALFROMREFLECTIONMAP = false;
  40664. defines.USESPHERICALINVERTEX = false;
  40665. defines.REFLECTIONMAP_OPPOSITEZ = false;
  40666. defines.LODINREFLECTIONALPHA = false;
  40667. defines.GAMMAREFLECTION = false;
  40668. }
  40669. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  40670. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._lightmapTexture, defines, "LIGHTMAP");
  40671. defines.USELIGHTMAPASSHADOWMAP = this._useLightmapAsShadowmap;
  40672. }
  40673. else {
  40674. defines.LIGHTMAP = false;
  40675. }
  40676. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  40677. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._emissiveTexture, defines, "EMISSIVE");
  40678. }
  40679. else {
  40680. defines.EMISSIVE = false;
  40681. }
  40682. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  40683. if (this._metallicTexture) {
  40684. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._metallicTexture, defines, "REFLECTIVITY");
  40685. defines.METALLICWORKFLOW = true;
  40686. defines.ROUGHNESSSTOREINMETALMAPALPHA = this._useRoughnessFromMetallicTextureAlpha;
  40687. defines.ROUGHNESSSTOREINMETALMAPGREEN = !this._useRoughnessFromMetallicTextureAlpha && this._useRoughnessFromMetallicTextureGreen;
  40688. defines.METALLNESSSTOREINMETALMAPBLUE = this._useMetallnessFromMetallicTextureBlue;
  40689. defines.AOSTOREINMETALMAPRED = this._useAmbientOcclusionFromMetallicTextureRed;
  40690. }
  40691. else if (this._reflectivityTexture) {
  40692. defines.METALLICWORKFLOW = false;
  40693. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._reflectivityTexture, defines, "REFLECTIVITY");
  40694. defines.MICROSURFACEFROMREFLECTIVITYMAP = this._useMicroSurfaceFromReflectivityMapAlpha;
  40695. defines.MICROSURFACEAUTOMATIC = this._useAutoMicroSurfaceFromReflectivityMap;
  40696. }
  40697. else {
  40698. defines.METALLICWORKFLOW = false;
  40699. defines.REFLECTIVITY = false;
  40700. }
  40701. if (this._microSurfaceTexture) {
  40702. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._microSurfaceTexture, defines, "MICROSURFACEMAP");
  40703. }
  40704. else {
  40705. defines.MICROSURFACEMAP = false;
  40706. }
  40707. }
  40708. else {
  40709. defines.REFLECTIVITY = false;
  40710. defines.MICROSURFACEMAP = false;
  40711. }
  40712. if (scene.getEngine().getCaps().standardDerivatives && this._bumpTexture && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  40713. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._bumpTexture, defines, "BUMP");
  40714. if (this._useParallax && this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  40715. defines.PARALLAX = true;
  40716. defines.PARALLAXOCCLUSION = !!this._useParallaxOcclusion;
  40717. }
  40718. else {
  40719. defines.PARALLAX = false;
  40720. }
  40721. defines.OBJECTSPACE_NORMALMAP = this._useObjectSpaceNormalMap;
  40722. }
  40723. else {
  40724. defines.BUMP = false;
  40725. }
  40726. var refractionTexture = this._getRefractionTexture();
  40727. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  40728. defines.REFRACTION = true;
  40729. defines.REFRACTIONMAP_3D = refractionTexture.isCube;
  40730. defines.GAMMAREFRACTION = refractionTexture.gammaSpace;
  40731. defines.REFRACTIONMAP_OPPOSITEZ = refractionTexture.invertZ;
  40732. defines.LODINREFRACTIONALPHA = refractionTexture.lodLevelInAlpha;
  40733. if (this._linkRefractionWithTransparency) {
  40734. defines.LINKREFRACTIONTOTRANSPARENCY = true;
  40735. }
  40736. }
  40737. else {
  40738. defines.REFRACTION = false;
  40739. }
  40740. if (this._environmentBRDFTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  40741. defines.ENVIRONMENTBRDF = true;
  40742. }
  40743. else {
  40744. defines.ENVIRONMENTBRDF = false;
  40745. }
  40746. if (this._shouldUseAlphaFromAlbedoTexture()) {
  40747. defines.ALPHAFROMALBEDO = true;
  40748. }
  40749. else {
  40750. defines.ALPHAFROMALBEDO = false;
  40751. }
  40752. }
  40753. defines.SPECULAROVERALPHA = this._useSpecularOverAlpha;
  40754. defines.USEPHYSICALLIGHTFALLOFF = this._usePhysicalLightFalloff;
  40755. defines.RADIANCEOVERALPHA = this._useRadianceOverAlpha;
  40756. if (this._forceMetallicWorkflow || (this._metallic !== undefined && this._metallic !== null) || (this._roughness !== undefined && this._roughness !== null)) {
  40757. defines.METALLICWORKFLOW = true;
  40758. }
  40759. else {
  40760. defines.METALLICWORKFLOW = false;
  40761. }
  40762. if (!this.backFaceCulling && this._twoSidedLighting) {
  40763. defines.TWOSIDEDLIGHTING = true;
  40764. }
  40765. else {
  40766. defines.TWOSIDEDLIGHTING = false;
  40767. }
  40768. defines.ALPHATESTVALUE = this._alphaCutOff;
  40769. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  40770. defines.ALPHABLEND = this.needAlphaBlendingForMesh(mesh);
  40771. defines.ALPHAFRESNEL = this._useAlphaFresnel || this._useLinearAlphaFresnel;
  40772. defines.LINEARALPHAFRESNEL = this._useLinearAlphaFresnel;
  40773. }
  40774. if (defines._areImageProcessingDirty) {
  40775. this._imageProcessingConfiguration.prepareDefines(defines);
  40776. }
  40777. defines.FORCENORMALFORWARD = this._forceNormalForward;
  40778. defines.RADIANCEOCCLUSION = this._useRadianceOcclusion;
  40779. defines.HORIZONOCCLUSION = this._useHorizonOcclusion;
  40780. // Misc.
  40781. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, this._useLogarithmicDepth, this.pointsCloud, this.fogEnabled, this._shouldTurnAlphaTestOn(mesh) || this._forceAlphaTest, defines);
  40782. // Values that need to be evaluated on every frame
  40783. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances ? true : false, useClipPlane);
  40784. // Attribs
  40785. BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, true, true, true, this._transparencyMode !== BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE);
  40786. };
  40787. /**
  40788. * Force shader compilation
  40789. */
  40790. PBRBaseMaterial.prototype.forceCompilation = function (mesh, onCompiled, options) {
  40791. var _this = this;
  40792. var localOptions = __assign({ clipPlane: false }, options);
  40793. var defines = new PBRMaterialDefines();
  40794. var effect = this._prepareEffect(mesh, defines, undefined, undefined, undefined, localOptions.clipPlane);
  40795. if (effect.isReady()) {
  40796. if (onCompiled) {
  40797. onCompiled(this);
  40798. }
  40799. }
  40800. else {
  40801. effect.onCompileObservable.add(function () {
  40802. if (onCompiled) {
  40803. onCompiled(_this);
  40804. }
  40805. });
  40806. }
  40807. };
  40808. /**
  40809. * Initializes the uniform buffer layout for the shader.
  40810. */
  40811. PBRBaseMaterial.prototype.buildUniformLayout = function () {
  40812. // Order is important !
  40813. this._uniformBuffer.addUniform("vAlbedoInfos", 2);
  40814. this._uniformBuffer.addUniform("vAmbientInfos", 3);
  40815. this._uniformBuffer.addUniform("vOpacityInfos", 2);
  40816. this._uniformBuffer.addUniform("vEmissiveInfos", 2);
  40817. this._uniformBuffer.addUniform("vLightmapInfos", 2);
  40818. this._uniformBuffer.addUniform("vReflectivityInfos", 3);
  40819. this._uniformBuffer.addUniform("vMicroSurfaceSamplerInfos", 2);
  40820. this._uniformBuffer.addUniform("vRefractionInfos", 4);
  40821. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  40822. this._uniformBuffer.addUniform("vReflectionPosition", 3);
  40823. this._uniformBuffer.addUniform("vReflectionSize", 3);
  40824. this._uniformBuffer.addUniform("vBumpInfos", 3);
  40825. this._uniformBuffer.addUniform("albedoMatrix", 16);
  40826. this._uniformBuffer.addUniform("ambientMatrix", 16);
  40827. this._uniformBuffer.addUniform("opacityMatrix", 16);
  40828. this._uniformBuffer.addUniform("emissiveMatrix", 16);
  40829. this._uniformBuffer.addUniform("lightmapMatrix", 16);
  40830. this._uniformBuffer.addUniform("reflectivityMatrix", 16);
  40831. this._uniformBuffer.addUniform("microSurfaceSamplerMatrix", 16);
  40832. this._uniformBuffer.addUniform("bumpMatrix", 16);
  40833. this._uniformBuffer.addUniform("vTangentSpaceParams", 2);
  40834. this._uniformBuffer.addUniform("refractionMatrix", 16);
  40835. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  40836. this._uniformBuffer.addUniform("vReflectionColor", 3);
  40837. this._uniformBuffer.addUniform("vAlbedoColor", 4);
  40838. this._uniformBuffer.addUniform("vLightingIntensity", 4);
  40839. this._uniformBuffer.addUniform("vRefractionMicrosurfaceInfos", 3);
  40840. this._uniformBuffer.addUniform("vReflectionMicrosurfaceInfos", 3);
  40841. this._uniformBuffer.addUniform("vReflectivityColor", 4);
  40842. this._uniformBuffer.addUniform("vEmissiveColor", 3);
  40843. this._uniformBuffer.addUniform("pointSize", 1);
  40844. this._uniformBuffer.create();
  40845. };
  40846. /**
  40847. * Unbinds the textures.
  40848. */
  40849. PBRBaseMaterial.prototype.unbind = function () {
  40850. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  40851. this._uniformBuffer.setTexture("reflectionSampler", null);
  40852. }
  40853. if (this._refractionTexture && this._refractionTexture.isRenderTarget) {
  40854. this._uniformBuffer.setTexture("refractionSampler", null);
  40855. }
  40856. _super.prototype.unbind.call(this);
  40857. };
  40858. /**
  40859. * Binds the submesh data.
  40860. * @param world - The world matrix.
  40861. * @param mesh - The BJS mesh.
  40862. * @param subMesh - A submesh of the BJS mesh.
  40863. */
  40864. PBRBaseMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  40865. var scene = this.getScene();
  40866. var defines = subMesh._materialDefines;
  40867. if (!defines) {
  40868. return;
  40869. }
  40870. var effect = subMesh.effect;
  40871. if (!effect) {
  40872. return;
  40873. }
  40874. this._activeEffect = effect;
  40875. // Matrices
  40876. this.bindOnlyWorldMatrix(world);
  40877. // Normal Matrix
  40878. if (defines.OBJECTSPACE_NORMALMAP) {
  40879. world.toNormalMatrix(this._normalMatrix);
  40880. this.bindOnlyNormalMatrix(this._normalMatrix);
  40881. }
  40882. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  40883. // Bones
  40884. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._activeEffect);
  40885. var reflectionTexture = null;
  40886. if (mustRebind) {
  40887. this._uniformBuffer.bindToEffect(effect, "Material");
  40888. this.bindViewProjection(effect);
  40889. reflectionTexture = this._getReflectionTexture();
  40890. var refractionTexture = this._getRefractionTexture();
  40891. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  40892. // Texture uniforms
  40893. if (scene.texturesEnabled) {
  40894. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  40895. this._uniformBuffer.updateFloat2("vAlbedoInfos", this._albedoTexture.coordinatesIndex, this._albedoTexture.level);
  40896. BABYLON.MaterialHelper.BindTextureMatrix(this._albedoTexture, this._uniformBuffer, "albedo");
  40897. }
  40898. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  40899. this._uniformBuffer.updateFloat3("vAmbientInfos", this._ambientTexture.coordinatesIndex, this._ambientTexture.level, this._ambientTextureStrength);
  40900. BABYLON.MaterialHelper.BindTextureMatrix(this._ambientTexture, this._uniformBuffer, "ambient");
  40901. }
  40902. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  40903. this._uniformBuffer.updateFloat2("vOpacityInfos", this._opacityTexture.coordinatesIndex, this._opacityTexture.level);
  40904. BABYLON.MaterialHelper.BindTextureMatrix(this._opacityTexture, this._uniformBuffer, "opacity");
  40905. }
  40906. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  40907. this._uniformBuffer.updateMatrix("reflectionMatrix", reflectionTexture.getReflectionTextureMatrix());
  40908. this._uniformBuffer.updateFloat2("vReflectionInfos", reflectionTexture.level, 0);
  40909. if (reflectionTexture.boundingBoxSize) {
  40910. var cubeTexture = reflectionTexture;
  40911. this._uniformBuffer.updateVector3("vReflectionPosition", cubeTexture.boundingBoxPosition);
  40912. this._uniformBuffer.updateVector3("vReflectionSize", cubeTexture.boundingBoxSize);
  40913. }
  40914. var polynomials = reflectionTexture.sphericalPolynomial;
  40915. if (defines.USESPHERICALFROMREFLECTIONMAP && polynomials) {
  40916. this._activeEffect.setFloat3("vSphericalX", polynomials.x.x, polynomials.x.y, polynomials.x.z);
  40917. this._activeEffect.setFloat3("vSphericalY", polynomials.y.x, polynomials.y.y, polynomials.y.z);
  40918. this._activeEffect.setFloat3("vSphericalZ", polynomials.z.x, polynomials.z.y, polynomials.z.z);
  40919. this._activeEffect.setFloat3("vSphericalXX_ZZ", polynomials.xx.x - polynomials.zz.x, polynomials.xx.y - polynomials.zz.y, polynomials.xx.z - polynomials.zz.z);
  40920. this._activeEffect.setFloat3("vSphericalYY_ZZ", polynomials.yy.x - polynomials.zz.x, polynomials.yy.y - polynomials.zz.y, polynomials.yy.z - polynomials.zz.z);
  40921. this._activeEffect.setFloat3("vSphericalZZ", polynomials.zz.x, polynomials.zz.y, polynomials.zz.z);
  40922. this._activeEffect.setFloat3("vSphericalXY", polynomials.xy.x, polynomials.xy.y, polynomials.xy.z);
  40923. this._activeEffect.setFloat3("vSphericalYZ", polynomials.yz.x, polynomials.yz.y, polynomials.yz.z);
  40924. this._activeEffect.setFloat3("vSphericalZX", polynomials.zx.x, polynomials.zx.y, polynomials.zx.z);
  40925. }
  40926. this._uniformBuffer.updateFloat3("vReflectionMicrosurfaceInfos", reflectionTexture.getSize().width, reflectionTexture.lodGenerationScale, reflectionTexture.lodGenerationOffset);
  40927. }
  40928. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  40929. this._uniformBuffer.updateFloat2("vEmissiveInfos", this._emissiveTexture.coordinatesIndex, this._emissiveTexture.level);
  40930. BABYLON.MaterialHelper.BindTextureMatrix(this._emissiveTexture, this._uniformBuffer, "emissive");
  40931. }
  40932. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  40933. this._uniformBuffer.updateFloat2("vLightmapInfos", this._lightmapTexture.coordinatesIndex, this._lightmapTexture.level);
  40934. BABYLON.MaterialHelper.BindTextureMatrix(this._lightmapTexture, this._uniformBuffer, "lightmap");
  40935. }
  40936. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  40937. if (this._metallicTexture) {
  40938. this._uniformBuffer.updateFloat3("vReflectivityInfos", this._metallicTexture.coordinatesIndex, this._metallicTexture.level, this._ambientTextureStrength);
  40939. BABYLON.MaterialHelper.BindTextureMatrix(this._metallicTexture, this._uniformBuffer, "reflectivity");
  40940. }
  40941. else if (this._reflectivityTexture) {
  40942. this._uniformBuffer.updateFloat3("vReflectivityInfos", this._reflectivityTexture.coordinatesIndex, this._reflectivityTexture.level, 1.0);
  40943. BABYLON.MaterialHelper.BindTextureMatrix(this._reflectivityTexture, this._uniformBuffer, "reflectivity");
  40944. }
  40945. if (this._microSurfaceTexture) {
  40946. this._uniformBuffer.updateFloat2("vMicroSurfaceSamplerInfos", this._microSurfaceTexture.coordinatesIndex, this._microSurfaceTexture.level);
  40947. BABYLON.MaterialHelper.BindTextureMatrix(this._microSurfaceTexture, this._uniformBuffer, "microSurfaceSampler");
  40948. }
  40949. }
  40950. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  40951. this._uniformBuffer.updateFloat3("vBumpInfos", this._bumpTexture.coordinatesIndex, this._bumpTexture.level, this._parallaxScaleBias);
  40952. BABYLON.MaterialHelper.BindTextureMatrix(this._bumpTexture, this._uniformBuffer, "bump");
  40953. if (scene._mirroredCameraPosition) {
  40954. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? 1.0 : -1.0, this._invertNormalMapY ? 1.0 : -1.0);
  40955. }
  40956. else {
  40957. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? -1.0 : 1.0, this._invertNormalMapY ? -1.0 : 1.0);
  40958. }
  40959. }
  40960. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  40961. this._uniformBuffer.updateMatrix("refractionMatrix", refractionTexture.getReflectionTextureMatrix());
  40962. var depth = 1.0;
  40963. if (!refractionTexture.isCube) {
  40964. if (refractionTexture.depth) {
  40965. depth = refractionTexture.depth;
  40966. }
  40967. }
  40968. this._uniformBuffer.updateFloat4("vRefractionInfos", refractionTexture.level, this._indexOfRefraction, depth, this._invertRefractionY ? -1 : 1);
  40969. this._uniformBuffer.updateFloat3("vRefractionMicrosurfaceInfos", refractionTexture.getSize().width, refractionTexture.lodGenerationScale, refractionTexture.lodGenerationOffset);
  40970. }
  40971. }
  40972. // Point size
  40973. if (this.pointsCloud) {
  40974. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  40975. }
  40976. // Colors
  40977. if (defines.METALLICWORKFLOW) {
  40978. BABYLON.PBRMaterial._scaledReflectivity.r = (this._metallic === undefined || this._metallic === null) ? 1 : this._metallic;
  40979. BABYLON.PBRMaterial._scaledReflectivity.g = (this._roughness === undefined || this._roughness === null) ? 1 : this._roughness;
  40980. this._uniformBuffer.updateColor4("vReflectivityColor", BABYLON.PBRMaterial._scaledReflectivity, 0);
  40981. }
  40982. else {
  40983. this._uniformBuffer.updateColor4("vReflectivityColor", this._reflectivityColor, this._microSurface);
  40984. }
  40985. this._uniformBuffer.updateColor3("vEmissiveColor", this._emissiveColor);
  40986. this._uniformBuffer.updateColor3("vReflectionColor", this._reflectionColor);
  40987. this._uniformBuffer.updateColor4("vAlbedoColor", this._albedoColor, this.alpha * mesh.visibility);
  40988. // Misc
  40989. this._lightingInfos.x = this._directIntensity;
  40990. this._lightingInfos.y = this._emissiveIntensity;
  40991. this._lightingInfos.z = this._environmentIntensity;
  40992. this._lightingInfos.w = this._specularIntensity;
  40993. this._uniformBuffer.updateVector4("vLightingIntensity", this._lightingInfos);
  40994. }
  40995. // Textures
  40996. if (scene.texturesEnabled) {
  40997. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  40998. this._uniformBuffer.setTexture("albedoSampler", this._albedoTexture);
  40999. }
  41000. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  41001. this._uniformBuffer.setTexture("ambientSampler", this._ambientTexture);
  41002. }
  41003. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  41004. this._uniformBuffer.setTexture("opacitySampler", this._opacityTexture);
  41005. }
  41006. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  41007. if (defines.LODBASEDMICROSFURACE) {
  41008. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  41009. }
  41010. else {
  41011. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture._lodTextureMid || reflectionTexture);
  41012. this._uniformBuffer.setTexture("reflectionSamplerLow", reflectionTexture._lodTextureLow || reflectionTexture);
  41013. this._uniformBuffer.setTexture("reflectionSamplerHigh", reflectionTexture._lodTextureHigh || reflectionTexture);
  41014. }
  41015. }
  41016. if (defines.ENVIRONMENTBRDF) {
  41017. this._uniformBuffer.setTexture("environmentBrdfSampler", this._environmentBRDFTexture);
  41018. }
  41019. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  41020. if (defines.LODBASEDMICROSFURACE) {
  41021. this._uniformBuffer.setTexture("refractionSampler", refractionTexture);
  41022. }
  41023. else {
  41024. this._uniformBuffer.setTexture("refractionSampler", refractionTexture._lodTextureMid || refractionTexture);
  41025. this._uniformBuffer.setTexture("refractionSamplerLow", refractionTexture._lodTextureLow || refractionTexture);
  41026. this._uniformBuffer.setTexture("refractionSamplerHigh", refractionTexture._lodTextureHigh || refractionTexture);
  41027. }
  41028. }
  41029. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  41030. this._uniformBuffer.setTexture("emissiveSampler", this._emissiveTexture);
  41031. }
  41032. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  41033. this._uniformBuffer.setTexture("lightmapSampler", this._lightmapTexture);
  41034. }
  41035. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  41036. if (this._metallicTexture) {
  41037. this._uniformBuffer.setTexture("reflectivitySampler", this._metallicTexture);
  41038. }
  41039. else if (this._reflectivityTexture) {
  41040. this._uniformBuffer.setTexture("reflectivitySampler", this._reflectivityTexture);
  41041. }
  41042. if (this._microSurfaceTexture) {
  41043. this._uniformBuffer.setTexture("microSurfaceSampler", this._microSurfaceTexture);
  41044. }
  41045. }
  41046. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  41047. this._uniformBuffer.setTexture("bumpSampler", this._bumpTexture);
  41048. }
  41049. }
  41050. // Clip plane
  41051. BABYLON.MaterialHelper.BindClipPlane(this._activeEffect, scene);
  41052. // Colors
  41053. scene.ambientColor.multiplyToRef(this._ambientColor, this._globalAmbientColor);
  41054. var eyePosition = scene._forcedViewPosition ? scene._forcedViewPosition : (scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.globalPosition);
  41055. var invertNormal = (scene.useRightHandedSystem === (scene._mirroredCameraPosition != null));
  41056. effect.setFloat4("vEyePosition", eyePosition.x, eyePosition.y, eyePosition.z, invertNormal ? -1 : 1);
  41057. effect.setColor3("vAmbientColor", this._globalAmbientColor);
  41058. }
  41059. if (mustRebind || !this.isFrozen) {
  41060. // Lights
  41061. if (scene.lightsEnabled && !this._disableLighting) {
  41062. BABYLON.MaterialHelper.BindLights(scene, mesh, this._activeEffect, defines, this._maxSimultaneousLights, this._usePhysicalLightFalloff);
  41063. }
  41064. // View
  41065. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || reflectionTexture) {
  41066. this.bindView(effect);
  41067. }
  41068. // Fog
  41069. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, this._activeEffect);
  41070. // Morph targets
  41071. if (defines.NUM_MORPH_INFLUENCERS) {
  41072. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, this._activeEffect);
  41073. }
  41074. // image processing
  41075. this._imageProcessingConfiguration.bind(this._activeEffect);
  41076. // Log. depth
  41077. BABYLON.MaterialHelper.BindLogDepth(defines, this._activeEffect, scene);
  41078. }
  41079. this._uniformBuffer.update();
  41080. this._afterBind(mesh);
  41081. };
  41082. /**
  41083. * Returns the animatable textures.
  41084. * @returns - Array of animatable textures.
  41085. */
  41086. PBRBaseMaterial.prototype.getAnimatables = function () {
  41087. var results = [];
  41088. if (this._albedoTexture && this._albedoTexture.animations && this._albedoTexture.animations.length > 0) {
  41089. results.push(this._albedoTexture);
  41090. }
  41091. if (this._ambientTexture && this._ambientTexture.animations && this._ambientTexture.animations.length > 0) {
  41092. results.push(this._ambientTexture);
  41093. }
  41094. if (this._opacityTexture && this._opacityTexture.animations && this._opacityTexture.animations.length > 0) {
  41095. results.push(this._opacityTexture);
  41096. }
  41097. if (this._reflectionTexture && this._reflectionTexture.animations && this._reflectionTexture.animations.length > 0) {
  41098. results.push(this._reflectionTexture);
  41099. }
  41100. if (this._emissiveTexture && this._emissiveTexture.animations && this._emissiveTexture.animations.length > 0) {
  41101. results.push(this._emissiveTexture);
  41102. }
  41103. if (this._metallicTexture && this._metallicTexture.animations && this._metallicTexture.animations.length > 0) {
  41104. results.push(this._metallicTexture);
  41105. }
  41106. else if (this._reflectivityTexture && this._reflectivityTexture.animations && this._reflectivityTexture.animations.length > 0) {
  41107. results.push(this._reflectivityTexture);
  41108. }
  41109. if (this._bumpTexture && this._bumpTexture.animations && this._bumpTexture.animations.length > 0) {
  41110. results.push(this._bumpTexture);
  41111. }
  41112. if (this._lightmapTexture && this._lightmapTexture.animations && this._lightmapTexture.animations.length > 0) {
  41113. results.push(this._lightmapTexture);
  41114. }
  41115. if (this._refractionTexture && this._refractionTexture.animations && this._refractionTexture.animations.length > 0) {
  41116. results.push(this._refractionTexture);
  41117. }
  41118. return results;
  41119. };
  41120. /**
  41121. * Returns the texture used for reflections.
  41122. * @returns - Reflection texture if present. Otherwise, returns the environment texture.
  41123. */
  41124. PBRBaseMaterial.prototype._getReflectionTexture = function () {
  41125. if (this._reflectionTexture) {
  41126. return this._reflectionTexture;
  41127. }
  41128. return this.getScene().environmentTexture;
  41129. };
  41130. /**
  41131. * Returns the texture used for refraction or null if none is used.
  41132. * @returns - Refection texture if present. If no refraction texture and refraction
  41133. * is linked with transparency, returns environment texture. Otherwise, returns null.
  41134. */
  41135. PBRBaseMaterial.prototype._getRefractionTexture = function () {
  41136. if (this._refractionTexture) {
  41137. return this._refractionTexture;
  41138. }
  41139. if (this._linkRefractionWithTransparency) {
  41140. return this.getScene().environmentTexture;
  41141. }
  41142. return null;
  41143. };
  41144. /**
  41145. * Disposes the resources of the material.
  41146. * @param forceDisposeEffect - Forces the disposal of effects.
  41147. * @param forceDisposeTextures - Forces the disposal of all textures.
  41148. */
  41149. PBRBaseMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  41150. if (forceDisposeTextures) {
  41151. if (this._albedoTexture) {
  41152. this._albedoTexture.dispose();
  41153. }
  41154. if (this._ambientTexture) {
  41155. this._ambientTexture.dispose();
  41156. }
  41157. if (this._opacityTexture) {
  41158. this._opacityTexture.dispose();
  41159. }
  41160. if (this._reflectionTexture) {
  41161. this._reflectionTexture.dispose();
  41162. }
  41163. if (this._environmentBRDFTexture && this.getScene()._environmentBRDFTexture !== this._environmentBRDFTexture) {
  41164. this._environmentBRDFTexture.dispose();
  41165. }
  41166. if (this._emissiveTexture) {
  41167. this._emissiveTexture.dispose();
  41168. }
  41169. if (this._metallicTexture) {
  41170. this._metallicTexture.dispose();
  41171. }
  41172. if (this._reflectivityTexture) {
  41173. this._reflectivityTexture.dispose();
  41174. }
  41175. if (this._bumpTexture) {
  41176. this._bumpTexture.dispose();
  41177. }
  41178. if (this._lightmapTexture) {
  41179. this._lightmapTexture.dispose();
  41180. }
  41181. if (this._refractionTexture) {
  41182. this._refractionTexture.dispose();
  41183. }
  41184. }
  41185. this._renderTargets.dispose();
  41186. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  41187. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  41188. }
  41189. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  41190. };
  41191. /**
  41192. * Stores the reflectivity values based on metallic roughness workflow.
  41193. */
  41194. PBRBaseMaterial._scaledReflectivity = new BABYLON.Color3();
  41195. __decorate([
  41196. BABYLON.serializeAsImageProcessingConfiguration()
  41197. ], PBRBaseMaterial.prototype, "_imageProcessingConfiguration", void 0);
  41198. __decorate([
  41199. BABYLON.serialize()
  41200. ], PBRBaseMaterial.prototype, "useLogarithmicDepth", null);
  41201. __decorate([
  41202. BABYLON.serialize()
  41203. ], PBRBaseMaterial.prototype, "transparencyMode", null);
  41204. return PBRBaseMaterial;
  41205. }(BABYLON.PushMaterial));
  41206. BABYLON.PBRBaseMaterial = PBRBaseMaterial;
  41207. })(BABYLON || (BABYLON = {}));
  41208. //# sourceMappingURL=babylon.pbrBaseMaterial.js.map
  41209. var BABYLON;
  41210. (function (BABYLON) {
  41211. /**
  41212. * The Physically based simple base material of BJS.
  41213. *
  41214. * This enables better naming and convention enforcements on top of the pbrMaterial.
  41215. * It is used as the base class for both the specGloss and metalRough conventions.
  41216. */
  41217. var PBRBaseSimpleMaterial = /** @class */ (function (_super) {
  41218. __extends(PBRBaseSimpleMaterial, _super);
  41219. /**
  41220. * Instantiates a new PBRMaterial instance.
  41221. *
  41222. * @param name The material name
  41223. * @param scene The scene the material will be use in.
  41224. */
  41225. function PBRBaseSimpleMaterial(name, scene) {
  41226. var _this = _super.call(this, name, scene) || this;
  41227. /**
  41228. * Number of Simultaneous lights allowed on the material.
  41229. */
  41230. _this.maxSimultaneousLights = 4;
  41231. /**
  41232. * If sets to true, disables all the lights affecting the material.
  41233. */
  41234. _this.disableLighting = false;
  41235. /**
  41236. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  41237. */
  41238. _this.invertNormalMapX = false;
  41239. /**
  41240. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  41241. */
  41242. _this.invertNormalMapY = false;
  41243. /**
  41244. * Emissivie color used to self-illuminate the model.
  41245. */
  41246. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  41247. /**
  41248. * Occlusion Channel Strenght.
  41249. */
  41250. _this.occlusionStrength = 1.0;
  41251. _this.useLightmapAsShadowmap = false;
  41252. _this._useAlphaFromAlbedoTexture = true;
  41253. _this._useAmbientInGrayScale = true;
  41254. return _this;
  41255. }
  41256. Object.defineProperty(PBRBaseSimpleMaterial.prototype, "doubleSided", {
  41257. /**
  41258. * Gets the current double sided mode.
  41259. */
  41260. get: function () {
  41261. return this._twoSidedLighting;
  41262. },
  41263. /**
  41264. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  41265. */
  41266. set: function (value) {
  41267. if (this._twoSidedLighting === value) {
  41268. return;
  41269. }
  41270. this._twoSidedLighting = value;
  41271. this.backFaceCulling = !value;
  41272. this._markAllSubMeshesAsTexturesDirty();
  41273. },
  41274. enumerable: true,
  41275. configurable: true
  41276. });
  41277. /**
  41278. * Return the active textures of the material.
  41279. */
  41280. PBRBaseSimpleMaterial.prototype.getActiveTextures = function () {
  41281. var activeTextures = _super.prototype.getActiveTextures.call(this);
  41282. if (this.environmentTexture) {
  41283. activeTextures.push(this.environmentTexture);
  41284. }
  41285. if (this.normalTexture) {
  41286. activeTextures.push(this.normalTexture);
  41287. }
  41288. if (this.emissiveTexture) {
  41289. activeTextures.push(this.emissiveTexture);
  41290. }
  41291. if (this.occlusionTexture) {
  41292. activeTextures.push(this.occlusionTexture);
  41293. }
  41294. if (this.lightmapTexture) {
  41295. activeTextures.push(this.lightmapTexture);
  41296. }
  41297. return activeTextures;
  41298. };
  41299. PBRBaseSimpleMaterial.prototype.hasTexture = function (texture) {
  41300. if (_super.prototype.hasTexture.call(this, texture)) {
  41301. return true;
  41302. }
  41303. if (this.lightmapTexture === texture) {
  41304. return true;
  41305. }
  41306. return false;
  41307. };
  41308. PBRBaseSimpleMaterial.prototype.getClassName = function () {
  41309. return "PBRBaseSimpleMaterial";
  41310. };
  41311. __decorate([
  41312. BABYLON.serialize(),
  41313. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  41314. ], PBRBaseSimpleMaterial.prototype, "maxSimultaneousLights", void 0);
  41315. __decorate([
  41316. BABYLON.serialize(),
  41317. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  41318. ], PBRBaseSimpleMaterial.prototype, "disableLighting", void 0);
  41319. __decorate([
  41320. BABYLON.serializeAsTexture(),
  41321. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectionTexture")
  41322. ], PBRBaseSimpleMaterial.prototype, "environmentTexture", void 0);
  41323. __decorate([
  41324. BABYLON.serialize(),
  41325. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41326. ], PBRBaseSimpleMaterial.prototype, "invertNormalMapX", void 0);
  41327. __decorate([
  41328. BABYLON.serialize(),
  41329. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41330. ], PBRBaseSimpleMaterial.prototype, "invertNormalMapY", void 0);
  41331. __decorate([
  41332. BABYLON.serializeAsTexture(),
  41333. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_bumpTexture")
  41334. ], PBRBaseSimpleMaterial.prototype, "normalTexture", void 0);
  41335. __decorate([
  41336. BABYLON.serializeAsColor3("emissive"),
  41337. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41338. ], PBRBaseSimpleMaterial.prototype, "emissiveColor", void 0);
  41339. __decorate([
  41340. BABYLON.serializeAsTexture(),
  41341. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41342. ], PBRBaseSimpleMaterial.prototype, "emissiveTexture", void 0);
  41343. __decorate([
  41344. BABYLON.serialize(),
  41345. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_ambientTextureStrength")
  41346. ], PBRBaseSimpleMaterial.prototype, "occlusionStrength", void 0);
  41347. __decorate([
  41348. BABYLON.serializeAsTexture(),
  41349. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_ambientTexture")
  41350. ], PBRBaseSimpleMaterial.prototype, "occlusionTexture", void 0);
  41351. __decorate([
  41352. BABYLON.serialize(),
  41353. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_alphaCutOff")
  41354. ], PBRBaseSimpleMaterial.prototype, "alphaCutOff", void 0);
  41355. __decorate([
  41356. BABYLON.serialize()
  41357. ], PBRBaseSimpleMaterial.prototype, "doubleSided", null);
  41358. __decorate([
  41359. BABYLON.serializeAsTexture(),
  41360. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", null)
  41361. ], PBRBaseSimpleMaterial.prototype, "lightmapTexture", void 0);
  41362. __decorate([
  41363. BABYLON.serialize(),
  41364. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41365. ], PBRBaseSimpleMaterial.prototype, "useLightmapAsShadowmap", void 0);
  41366. return PBRBaseSimpleMaterial;
  41367. }(BABYLON.PBRBaseMaterial));
  41368. BABYLON.PBRBaseSimpleMaterial = PBRBaseSimpleMaterial;
  41369. })(BABYLON || (BABYLON = {}));
  41370. //# sourceMappingURL=babylon.pbrBaseSimpleMaterial.js.map
  41371. var BABYLON;
  41372. (function (BABYLON) {
  41373. /**
  41374. * The Physically based material of BJS.
  41375. *
  41376. * This offers the main features of a standard PBR material.
  41377. * For more information, please refer to the documentation :
  41378. * http://doc.babylonjs.com/extensions/Physically_Based_Rendering
  41379. */
  41380. var PBRMaterial = /** @class */ (function (_super) {
  41381. __extends(PBRMaterial, _super);
  41382. /**
  41383. * Instantiates a new PBRMaterial instance.
  41384. *
  41385. * @param name The material name
  41386. * @param scene The scene the material will be use in.
  41387. */
  41388. function PBRMaterial(name, scene) {
  41389. var _this = _super.call(this, name, scene) || this;
  41390. /**
  41391. * Intensity of the direct lights e.g. the four lights available in your scene.
  41392. * This impacts both the direct diffuse and specular highlights.
  41393. */
  41394. _this.directIntensity = 1.0;
  41395. /**
  41396. * Intensity of the emissive part of the material.
  41397. * This helps controlling the emissive effect without modifying the emissive color.
  41398. */
  41399. _this.emissiveIntensity = 1.0;
  41400. /**
  41401. * Intensity of the environment e.g. how much the environment will light the object
  41402. * either through harmonics for rough material or through the refelction for shiny ones.
  41403. */
  41404. _this.environmentIntensity = 1.0;
  41405. /**
  41406. * This is a special control allowing the reduction of the specular highlights coming from the
  41407. * four lights of the scene. Those highlights may not be needed in full environment lighting.
  41408. */
  41409. _this.specularIntensity = 1.0;
  41410. /**
  41411. * Debug Control allowing disabling the bump map on this material.
  41412. */
  41413. _this.disableBumpMap = false;
  41414. /**
  41415. * AKA Occlusion Texture Intensity in other nomenclature.
  41416. */
  41417. _this.ambientTextureStrength = 1.0;
  41418. /**
  41419. * The color of a material in ambient lighting.
  41420. */
  41421. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  41422. /**
  41423. * AKA Diffuse Color in other nomenclature.
  41424. */
  41425. _this.albedoColor = new BABYLON.Color3(1, 1, 1);
  41426. /**
  41427. * AKA Specular Color in other nomenclature.
  41428. */
  41429. _this.reflectivityColor = new BABYLON.Color3(1, 1, 1);
  41430. /**
  41431. * The color reflected from the material.
  41432. */
  41433. _this.reflectionColor = new BABYLON.Color3(1.0, 1.0, 1.0);
  41434. /**
  41435. * The color emitted from the material.
  41436. */
  41437. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  41438. /**
  41439. * AKA Glossiness in other nomenclature.
  41440. */
  41441. _this.microSurface = 1.0;
  41442. /**
  41443. * source material index of refraction (IOR)' / 'destination material IOR.
  41444. */
  41445. _this.indexOfRefraction = 0.66;
  41446. /**
  41447. * Controls if refraction needs to be inverted on Y. This could be usefull for procedural texture.
  41448. */
  41449. _this.invertRefractionY = false;
  41450. /**
  41451. * This parameters will make the material used its opacity to control how much it is refracting aginst not.
  41452. * Materials half opaque for instance using refraction could benefit from this control.
  41453. */
  41454. _this.linkRefractionWithTransparency = false;
  41455. _this.useLightmapAsShadowmap = false;
  41456. /**
  41457. * Specifies that the alpha is coming form the albedo channel alpha channel for alpha blending.
  41458. */
  41459. _this.useAlphaFromAlbedoTexture = false;
  41460. /**
  41461. * Enforces alpha test in opaque or blend mode in order to improve the performances of some situations.
  41462. */
  41463. _this.forceAlphaTest = false;
  41464. /**
  41465. * Defines the alpha limits in alpha test mode.
  41466. */
  41467. _this.alphaCutOff = 0.4;
  41468. /**
  41469. * Specifies that the material will keeps the specular highlights over a transparent surface (only the most limunous ones).
  41470. * A car glass is a good exemple of that. When sun reflects on it you can not see what is behind.
  41471. */
  41472. _this.useSpecularOverAlpha = true;
  41473. /**
  41474. * Specifies if the reflectivity texture contains the glossiness information in its alpha channel.
  41475. */
  41476. _this.useMicroSurfaceFromReflectivityMapAlpha = false;
  41477. /**
  41478. * Specifies if the metallic texture contains the roughness information in its alpha channel.
  41479. */
  41480. _this.useRoughnessFromMetallicTextureAlpha = true;
  41481. /**
  41482. * Specifies if the metallic texture contains the roughness information in its green channel.
  41483. */
  41484. _this.useRoughnessFromMetallicTextureGreen = false;
  41485. /**
  41486. * Specifies if the metallic texture contains the metallness information in its blue channel.
  41487. */
  41488. _this.useMetallnessFromMetallicTextureBlue = false;
  41489. /**
  41490. * Specifies if the metallic texture contains the ambient occlusion information in its red channel.
  41491. */
  41492. _this.useAmbientOcclusionFromMetallicTextureRed = false;
  41493. /**
  41494. * Specifies if the ambient texture contains the ambient occlusion information in its red channel only.
  41495. */
  41496. _this.useAmbientInGrayScale = false;
  41497. /**
  41498. * In case the reflectivity map does not contain the microsurface information in its alpha channel,
  41499. * The material will try to infer what glossiness each pixel should be.
  41500. */
  41501. _this.useAutoMicroSurfaceFromReflectivityMap = false;
  41502. /**
  41503. * BJS is using an harcoded light falloff based on a manually sets up range.
  41504. * In PBR, one way to represents the fallof is to use the inverse squared root algorythm.
  41505. * This parameter can help you switch back to the BJS mode in order to create scenes using both materials.
  41506. */
  41507. _this.usePhysicalLightFalloff = true;
  41508. /**
  41509. * Specifies that the material will keeps the reflection highlights over a transparent surface (only the most limunous ones).
  41510. * A car glass is a good exemple of that. When the street lights reflects on it you can not see what is behind.
  41511. */
  41512. _this.useRadianceOverAlpha = true;
  41513. /**
  41514. * Allows using an object space normal map (instead of tangent space).
  41515. */
  41516. _this.useObjectSpaceNormalMap = false;
  41517. /**
  41518. * Allows using the bump map in parallax mode.
  41519. */
  41520. _this.useParallax = false;
  41521. /**
  41522. * Allows using the bump map in parallax occlusion mode.
  41523. */
  41524. _this.useParallaxOcclusion = false;
  41525. /**
  41526. * Controls the scale bias of the parallax mode.
  41527. */
  41528. _this.parallaxScaleBias = 0.05;
  41529. /**
  41530. * If sets to true, disables all the lights affecting the material.
  41531. */
  41532. _this.disableLighting = false;
  41533. /**
  41534. * Force the shader to compute irradiance in the fragment shader in order to take bump in account.
  41535. */
  41536. _this.forceIrradianceInFragment = false;
  41537. /**
  41538. * Number of Simultaneous lights allowed on the material.
  41539. */
  41540. _this.maxSimultaneousLights = 4;
  41541. /**
  41542. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  41543. */
  41544. _this.invertNormalMapX = false;
  41545. /**
  41546. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  41547. */
  41548. _this.invertNormalMapY = false;
  41549. /**
  41550. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  41551. */
  41552. _this.twoSidedLighting = false;
  41553. /**
  41554. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  41555. * And/Or occlude the blended part. (alpha is converted to gamma to compute the fresnel)
  41556. */
  41557. _this.useAlphaFresnel = false;
  41558. /**
  41559. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  41560. * And/Or occlude the blended part. (alpha stays linear to compute the fresnel)
  41561. */
  41562. _this.useLinearAlphaFresnel = false;
  41563. /**
  41564. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  41565. * And/Or occlude the blended part.
  41566. */
  41567. _this.environmentBRDFTexture = null;
  41568. /**
  41569. * Force normal to face away from face.
  41570. */
  41571. _this.forceNormalForward = false;
  41572. /**
  41573. * This parameters will enable/disable Horizon occlusion to prevent normal maps to look shiny when the normal
  41574. * makes the reflect vector face the model (under horizon).
  41575. */
  41576. _this.useHorizonOcclusion = true;
  41577. /**
  41578. * This parameters will enable/disable radiance occlusion by preventing the radiance to lit
  41579. * too much the area relying on ambient texture to define their ambient occlusion.
  41580. */
  41581. _this.useRadianceOcclusion = true;
  41582. _this._environmentBRDFTexture = BABYLON.TextureTools.GetEnvironmentBRDFTexture(scene);
  41583. return _this;
  41584. }
  41585. Object.defineProperty(PBRMaterial, "PBRMATERIAL_OPAQUE", {
  41586. /**
  41587. * PBRMaterialTransparencyMode: No transparency mode, Alpha channel is not use.
  41588. */
  41589. get: function () {
  41590. return this._PBRMATERIAL_OPAQUE;
  41591. },
  41592. enumerable: true,
  41593. configurable: true
  41594. });
  41595. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHATEST", {
  41596. /**
  41597. * PBRMaterialTransparencyMode: Alpha Test mode, pixel are discarded below a certain threshold defined by the alpha cutoff value.
  41598. */
  41599. get: function () {
  41600. return this._PBRMATERIAL_ALPHATEST;
  41601. },
  41602. enumerable: true,
  41603. configurable: true
  41604. });
  41605. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHABLEND", {
  41606. /**
  41607. * PBRMaterialTransparencyMode: Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  41608. */
  41609. get: function () {
  41610. return this._PBRMATERIAL_ALPHABLEND;
  41611. },
  41612. enumerable: true,
  41613. configurable: true
  41614. });
  41615. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHATESTANDBLEND", {
  41616. /**
  41617. * PBRMaterialTransparencyMode: Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  41618. * They are also discarded below the alpha cutoff threshold to improve performances.
  41619. */
  41620. get: function () {
  41621. return this._PBRMATERIAL_ALPHATESTANDBLEND;
  41622. },
  41623. enumerable: true,
  41624. configurable: true
  41625. });
  41626. Object.defineProperty(PBRMaterial.prototype, "imageProcessingConfiguration", {
  41627. /**
  41628. * Gets the image processing configuration used either in this material.
  41629. */
  41630. get: function () {
  41631. return this._imageProcessingConfiguration;
  41632. },
  41633. /**
  41634. * Sets the Default image processing configuration used either in the this material.
  41635. *
  41636. * If sets to null, the scene one is in use.
  41637. */
  41638. set: function (value) {
  41639. this._attachImageProcessingConfiguration(value);
  41640. // Ensure the effect will be rebuilt.
  41641. this._markAllSubMeshesAsTexturesDirty();
  41642. },
  41643. enumerable: true,
  41644. configurable: true
  41645. });
  41646. Object.defineProperty(PBRMaterial.prototype, "cameraColorCurvesEnabled", {
  41647. /**
  41648. * Gets wether the color curves effect is enabled.
  41649. */
  41650. get: function () {
  41651. return this.imageProcessingConfiguration.colorCurvesEnabled;
  41652. },
  41653. /**
  41654. * Sets wether the color curves effect is enabled.
  41655. */
  41656. set: function (value) {
  41657. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  41658. },
  41659. enumerable: true,
  41660. configurable: true
  41661. });
  41662. Object.defineProperty(PBRMaterial.prototype, "cameraColorGradingEnabled", {
  41663. /**
  41664. * Gets wether the color grading effect is enabled.
  41665. */
  41666. get: function () {
  41667. return this.imageProcessingConfiguration.colorGradingEnabled;
  41668. },
  41669. /**
  41670. * Gets wether the color grading effect is enabled.
  41671. */
  41672. set: function (value) {
  41673. this.imageProcessingConfiguration.colorGradingEnabled = value;
  41674. },
  41675. enumerable: true,
  41676. configurable: true
  41677. });
  41678. Object.defineProperty(PBRMaterial.prototype, "cameraToneMappingEnabled", {
  41679. /**
  41680. * Gets wether tonemapping is enabled or not.
  41681. */
  41682. get: function () {
  41683. return this._imageProcessingConfiguration.toneMappingEnabled;
  41684. },
  41685. /**
  41686. * Sets wether tonemapping is enabled or not
  41687. */
  41688. set: function (value) {
  41689. this._imageProcessingConfiguration.toneMappingEnabled = value;
  41690. },
  41691. enumerable: true,
  41692. configurable: true
  41693. });
  41694. ;
  41695. ;
  41696. Object.defineProperty(PBRMaterial.prototype, "cameraExposure", {
  41697. /**
  41698. * The camera exposure used on this material.
  41699. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  41700. * This corresponds to a photographic exposure.
  41701. */
  41702. get: function () {
  41703. return this._imageProcessingConfiguration.exposure;
  41704. },
  41705. /**
  41706. * The camera exposure used on this material.
  41707. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  41708. * This corresponds to a photographic exposure.
  41709. */
  41710. set: function (value) {
  41711. this._imageProcessingConfiguration.exposure = value;
  41712. },
  41713. enumerable: true,
  41714. configurable: true
  41715. });
  41716. ;
  41717. ;
  41718. Object.defineProperty(PBRMaterial.prototype, "cameraContrast", {
  41719. /**
  41720. * Gets The camera contrast used on this material.
  41721. */
  41722. get: function () {
  41723. return this._imageProcessingConfiguration.contrast;
  41724. },
  41725. /**
  41726. * Sets The camera contrast used on this material.
  41727. */
  41728. set: function (value) {
  41729. this._imageProcessingConfiguration.contrast = value;
  41730. },
  41731. enumerable: true,
  41732. configurable: true
  41733. });
  41734. Object.defineProperty(PBRMaterial.prototype, "cameraColorGradingTexture", {
  41735. /**
  41736. * Gets the Color Grading 2D Lookup Texture.
  41737. */
  41738. get: function () {
  41739. return this._imageProcessingConfiguration.colorGradingTexture;
  41740. },
  41741. /**
  41742. * Sets the Color Grading 2D Lookup Texture.
  41743. */
  41744. set: function (value) {
  41745. this._imageProcessingConfiguration.colorGradingTexture = value;
  41746. },
  41747. enumerable: true,
  41748. configurable: true
  41749. });
  41750. Object.defineProperty(PBRMaterial.prototype, "cameraColorCurves", {
  41751. /**
  41752. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  41753. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  41754. * 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;
  41755. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  41756. */
  41757. get: function () {
  41758. return this._imageProcessingConfiguration.colorCurves;
  41759. },
  41760. /**
  41761. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  41762. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  41763. * 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;
  41764. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  41765. */
  41766. set: function (value) {
  41767. this._imageProcessingConfiguration.colorCurves = value;
  41768. },
  41769. enumerable: true,
  41770. configurable: true
  41771. });
  41772. /**
  41773. * Returns the name of this material class.
  41774. */
  41775. PBRMaterial.prototype.getClassName = function () {
  41776. return "PBRMaterial";
  41777. };
  41778. /**
  41779. * Returns an array of the actively used textures.
  41780. * @returns - Array of BaseTextures
  41781. */
  41782. PBRMaterial.prototype.getActiveTextures = function () {
  41783. var activeTextures = _super.prototype.getActiveTextures.call(this);
  41784. if (this._albedoTexture) {
  41785. activeTextures.push(this._albedoTexture);
  41786. }
  41787. if (this._ambientTexture) {
  41788. activeTextures.push(this._ambientTexture);
  41789. }
  41790. if (this._opacityTexture) {
  41791. activeTextures.push(this._opacityTexture);
  41792. }
  41793. if (this._reflectionTexture) {
  41794. activeTextures.push(this._reflectionTexture);
  41795. }
  41796. if (this._emissiveTexture) {
  41797. activeTextures.push(this._emissiveTexture);
  41798. }
  41799. if (this._reflectivityTexture) {
  41800. activeTextures.push(this._reflectivityTexture);
  41801. }
  41802. if (this._metallicTexture) {
  41803. activeTextures.push(this._metallicTexture);
  41804. }
  41805. if (this._microSurfaceTexture) {
  41806. activeTextures.push(this._microSurfaceTexture);
  41807. }
  41808. if (this._bumpTexture) {
  41809. activeTextures.push(this._bumpTexture);
  41810. }
  41811. if (this._lightmapTexture) {
  41812. activeTextures.push(this._lightmapTexture);
  41813. }
  41814. if (this._refractionTexture) {
  41815. activeTextures.push(this._refractionTexture);
  41816. }
  41817. return activeTextures;
  41818. };
  41819. /**
  41820. * Checks to see if a texture is used in the material.
  41821. * @param texture - Base texture to use.
  41822. * @returns - Boolean specifying if a texture is used in the material.
  41823. */
  41824. PBRMaterial.prototype.hasTexture = function (texture) {
  41825. if (_super.prototype.hasTexture.call(this, texture)) {
  41826. return true;
  41827. }
  41828. if (this._albedoTexture === texture) {
  41829. return true;
  41830. }
  41831. if (this._ambientTexture === texture) {
  41832. return true;
  41833. }
  41834. if (this._opacityTexture === texture) {
  41835. return true;
  41836. }
  41837. if (this._reflectionTexture === texture) {
  41838. return true;
  41839. }
  41840. if (this._reflectivityTexture === texture) {
  41841. return true;
  41842. }
  41843. if (this._metallicTexture === texture) {
  41844. return true;
  41845. }
  41846. if (this._microSurfaceTexture === texture) {
  41847. return true;
  41848. }
  41849. if (this._bumpTexture === texture) {
  41850. return true;
  41851. }
  41852. if (this._lightmapTexture === texture) {
  41853. return true;
  41854. }
  41855. if (this._refractionTexture === texture) {
  41856. return true;
  41857. }
  41858. return false;
  41859. };
  41860. /**
  41861. * Makes a duplicate of the current material.
  41862. * @param name - name to use for the new material.
  41863. */
  41864. PBRMaterial.prototype.clone = function (name) {
  41865. var _this = this;
  41866. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRMaterial(name, _this.getScene()); }, this);
  41867. clone.id = name;
  41868. clone.name = name;
  41869. return clone;
  41870. };
  41871. /**
  41872. * Serializes this PBR Material.
  41873. * @returns - An object with the serialized material.
  41874. */
  41875. PBRMaterial.prototype.serialize = function () {
  41876. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  41877. serializationObject.customType = "BABYLON.PBRMaterial";
  41878. return serializationObject;
  41879. };
  41880. // Statics
  41881. /**
  41882. * Parses a PBR Material from a serialized object.
  41883. * @param source - Serialized object.
  41884. * @param scene - BJS scene instance.
  41885. * @param rootUrl - url for the scene object
  41886. * @returns - PBRMaterial
  41887. */
  41888. PBRMaterial.Parse = function (source, scene, rootUrl) {
  41889. return BABYLON.SerializationHelper.Parse(function () { return new PBRMaterial(source.name, scene); }, source, scene, rootUrl);
  41890. };
  41891. PBRMaterial._PBRMATERIAL_OPAQUE = 0;
  41892. /**
  41893. * Alpha Test mode, pixel are discarded below a certain threshold defined by the alpha cutoff value.
  41894. */
  41895. PBRMaterial._PBRMATERIAL_ALPHATEST = 1;
  41896. /**
  41897. * Represents the value for Alpha Blend. Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  41898. */
  41899. PBRMaterial._PBRMATERIAL_ALPHABLEND = 2;
  41900. /**
  41901. * 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.
  41902. * They are also discarded below the alpha cutoff threshold to improve performances.
  41903. */
  41904. PBRMaterial._PBRMATERIAL_ALPHATESTANDBLEND = 3;
  41905. __decorate([
  41906. BABYLON.serialize(),
  41907. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41908. ], PBRMaterial.prototype, "directIntensity", void 0);
  41909. __decorate([
  41910. BABYLON.serialize(),
  41911. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41912. ], PBRMaterial.prototype, "emissiveIntensity", void 0);
  41913. __decorate([
  41914. BABYLON.serialize(),
  41915. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41916. ], PBRMaterial.prototype, "environmentIntensity", void 0);
  41917. __decorate([
  41918. BABYLON.serialize(),
  41919. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41920. ], PBRMaterial.prototype, "specularIntensity", void 0);
  41921. __decorate([
  41922. BABYLON.serialize(),
  41923. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41924. ], PBRMaterial.prototype, "disableBumpMap", void 0);
  41925. __decorate([
  41926. BABYLON.serializeAsTexture(),
  41927. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41928. ], PBRMaterial.prototype, "albedoTexture", void 0);
  41929. __decorate([
  41930. BABYLON.serializeAsTexture(),
  41931. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41932. ], PBRMaterial.prototype, "ambientTexture", void 0);
  41933. __decorate([
  41934. BABYLON.serialize(),
  41935. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41936. ], PBRMaterial.prototype, "ambientTextureStrength", void 0);
  41937. __decorate([
  41938. BABYLON.serializeAsTexture(),
  41939. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  41940. ], PBRMaterial.prototype, "opacityTexture", void 0);
  41941. __decorate([
  41942. BABYLON.serializeAsTexture(),
  41943. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41944. ], PBRMaterial.prototype, "reflectionTexture", void 0);
  41945. __decorate([
  41946. BABYLON.serializeAsTexture(),
  41947. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41948. ], PBRMaterial.prototype, "emissiveTexture", void 0);
  41949. __decorate([
  41950. BABYLON.serializeAsTexture(),
  41951. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41952. ], PBRMaterial.prototype, "reflectivityTexture", void 0);
  41953. __decorate([
  41954. BABYLON.serializeAsTexture(),
  41955. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41956. ], PBRMaterial.prototype, "metallicTexture", void 0);
  41957. __decorate([
  41958. BABYLON.serialize(),
  41959. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41960. ], PBRMaterial.prototype, "metallic", void 0);
  41961. __decorate([
  41962. BABYLON.serialize(),
  41963. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41964. ], PBRMaterial.prototype, "roughness", void 0);
  41965. __decorate([
  41966. BABYLON.serializeAsTexture(),
  41967. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41968. ], PBRMaterial.prototype, "microSurfaceTexture", void 0);
  41969. __decorate([
  41970. BABYLON.serializeAsTexture(),
  41971. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41972. ], PBRMaterial.prototype, "bumpTexture", void 0);
  41973. __decorate([
  41974. BABYLON.serializeAsTexture(),
  41975. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", null)
  41976. ], PBRMaterial.prototype, "lightmapTexture", void 0);
  41977. __decorate([
  41978. BABYLON.serializeAsTexture(),
  41979. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41980. ], PBRMaterial.prototype, "refractionTexture", void 0);
  41981. __decorate([
  41982. BABYLON.serializeAsColor3("ambient"),
  41983. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41984. ], PBRMaterial.prototype, "ambientColor", void 0);
  41985. __decorate([
  41986. BABYLON.serializeAsColor3("albedo"),
  41987. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41988. ], PBRMaterial.prototype, "albedoColor", void 0);
  41989. __decorate([
  41990. BABYLON.serializeAsColor3("reflectivity"),
  41991. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41992. ], PBRMaterial.prototype, "reflectivityColor", void 0);
  41993. __decorate([
  41994. BABYLON.serializeAsColor3("reflection"),
  41995. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41996. ], PBRMaterial.prototype, "reflectionColor", void 0);
  41997. __decorate([
  41998. BABYLON.serializeAsColor3("emissive"),
  41999. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42000. ], PBRMaterial.prototype, "emissiveColor", void 0);
  42001. __decorate([
  42002. BABYLON.serialize(),
  42003. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42004. ], PBRMaterial.prototype, "microSurface", void 0);
  42005. __decorate([
  42006. BABYLON.serialize(),
  42007. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42008. ], PBRMaterial.prototype, "indexOfRefraction", void 0);
  42009. __decorate([
  42010. BABYLON.serialize(),
  42011. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42012. ], PBRMaterial.prototype, "invertRefractionY", void 0);
  42013. __decorate([
  42014. BABYLON.serialize(),
  42015. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42016. ], PBRMaterial.prototype, "linkRefractionWithTransparency", void 0);
  42017. __decorate([
  42018. BABYLON.serialize(),
  42019. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42020. ], PBRMaterial.prototype, "useLightmapAsShadowmap", void 0);
  42021. __decorate([
  42022. BABYLON.serialize(),
  42023. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  42024. ], PBRMaterial.prototype, "useAlphaFromAlbedoTexture", void 0);
  42025. __decorate([
  42026. BABYLON.serialize(),
  42027. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  42028. ], PBRMaterial.prototype, "forceAlphaTest", void 0);
  42029. __decorate([
  42030. BABYLON.serialize(),
  42031. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  42032. ], PBRMaterial.prototype, "alphaCutOff", void 0);
  42033. __decorate([
  42034. BABYLON.serialize(),
  42035. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42036. ], PBRMaterial.prototype, "useSpecularOverAlpha", void 0);
  42037. __decorate([
  42038. BABYLON.serialize(),
  42039. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42040. ], PBRMaterial.prototype, "useMicroSurfaceFromReflectivityMapAlpha", void 0);
  42041. __decorate([
  42042. BABYLON.serialize(),
  42043. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42044. ], PBRMaterial.prototype, "useRoughnessFromMetallicTextureAlpha", void 0);
  42045. __decorate([
  42046. BABYLON.serialize(),
  42047. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42048. ], PBRMaterial.prototype, "useRoughnessFromMetallicTextureGreen", void 0);
  42049. __decorate([
  42050. BABYLON.serialize(),
  42051. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42052. ], PBRMaterial.prototype, "useMetallnessFromMetallicTextureBlue", void 0);
  42053. __decorate([
  42054. BABYLON.serialize(),
  42055. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42056. ], PBRMaterial.prototype, "useAmbientOcclusionFromMetallicTextureRed", void 0);
  42057. __decorate([
  42058. BABYLON.serialize(),
  42059. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42060. ], PBRMaterial.prototype, "useAmbientInGrayScale", void 0);
  42061. __decorate([
  42062. BABYLON.serialize(),
  42063. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42064. ], PBRMaterial.prototype, "useAutoMicroSurfaceFromReflectivityMap", void 0);
  42065. __decorate([
  42066. BABYLON.serialize(),
  42067. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42068. ], PBRMaterial.prototype, "usePhysicalLightFalloff", void 0);
  42069. __decorate([
  42070. BABYLON.serialize(),
  42071. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42072. ], PBRMaterial.prototype, "useRadianceOverAlpha", void 0);
  42073. __decorate([
  42074. BABYLON.serialize(),
  42075. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42076. ], PBRMaterial.prototype, "useObjectSpaceNormalMap", void 0);
  42077. __decorate([
  42078. BABYLON.serialize(),
  42079. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42080. ], PBRMaterial.prototype, "useParallax", void 0);
  42081. __decorate([
  42082. BABYLON.serialize(),
  42083. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42084. ], PBRMaterial.prototype, "useParallaxOcclusion", void 0);
  42085. __decorate([
  42086. BABYLON.serialize(),
  42087. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42088. ], PBRMaterial.prototype, "parallaxScaleBias", void 0);
  42089. __decorate([
  42090. BABYLON.serialize(),
  42091. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  42092. ], PBRMaterial.prototype, "disableLighting", void 0);
  42093. __decorate([
  42094. BABYLON.serialize(),
  42095. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42096. ], PBRMaterial.prototype, "forceIrradianceInFragment", void 0);
  42097. __decorate([
  42098. BABYLON.serialize(),
  42099. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  42100. ], PBRMaterial.prototype, "maxSimultaneousLights", void 0);
  42101. __decorate([
  42102. BABYLON.serialize(),
  42103. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42104. ], PBRMaterial.prototype, "invertNormalMapX", void 0);
  42105. __decorate([
  42106. BABYLON.serialize(),
  42107. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42108. ], PBRMaterial.prototype, "invertNormalMapY", void 0);
  42109. __decorate([
  42110. BABYLON.serialize(),
  42111. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42112. ], PBRMaterial.prototype, "twoSidedLighting", void 0);
  42113. __decorate([
  42114. BABYLON.serialize(),
  42115. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42116. ], PBRMaterial.prototype, "useAlphaFresnel", void 0);
  42117. __decorate([
  42118. BABYLON.serialize(),
  42119. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42120. ], PBRMaterial.prototype, "useLinearAlphaFresnel", void 0);
  42121. __decorate([
  42122. BABYLON.serializeAsTexture(),
  42123. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42124. ], PBRMaterial.prototype, "environmentBRDFTexture", void 0);
  42125. __decorate([
  42126. BABYLON.serialize(),
  42127. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42128. ], PBRMaterial.prototype, "forceNormalForward", void 0);
  42129. __decorate([
  42130. BABYLON.serialize(),
  42131. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42132. ], PBRMaterial.prototype, "useHorizonOcclusion", void 0);
  42133. __decorate([
  42134. BABYLON.serialize(),
  42135. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42136. ], PBRMaterial.prototype, "useRadianceOcclusion", void 0);
  42137. return PBRMaterial;
  42138. }(BABYLON.PBRBaseMaterial));
  42139. BABYLON.PBRMaterial = PBRMaterial;
  42140. })(BABYLON || (BABYLON = {}));
  42141. //# sourceMappingURL=babylon.pbrMaterial.js.map
  42142. var BABYLON;
  42143. (function (BABYLON) {
  42144. /**
  42145. * The PBR material of BJS following the metal roughness convention.
  42146. *
  42147. * This fits to the PBR convention in the GLTF definition:
  42148. * https://github.com/KhronosGroup/glTF/tree/2.0/specification/2.0
  42149. */
  42150. var PBRMetallicRoughnessMaterial = /** @class */ (function (_super) {
  42151. __extends(PBRMetallicRoughnessMaterial, _super);
  42152. /**
  42153. * Instantiates a new PBRMetalRoughnessMaterial instance.
  42154. *
  42155. * @param name The material name
  42156. * @param scene The scene the material will be use in.
  42157. */
  42158. function PBRMetallicRoughnessMaterial(name, scene) {
  42159. var _this = _super.call(this, name, scene) || this;
  42160. _this._useRoughnessFromMetallicTextureAlpha = false;
  42161. _this._useRoughnessFromMetallicTextureGreen = true;
  42162. _this._useMetallnessFromMetallicTextureBlue = true;
  42163. _this._forceMetallicWorkflow = true;
  42164. return _this;
  42165. }
  42166. /**
  42167. * Return the currrent class name of the material.
  42168. */
  42169. PBRMetallicRoughnessMaterial.prototype.getClassName = function () {
  42170. return "PBRMetallicRoughnessMaterial";
  42171. };
  42172. /**
  42173. * Return the active textures of the material.
  42174. */
  42175. PBRMetallicRoughnessMaterial.prototype.getActiveTextures = function () {
  42176. var activeTextures = _super.prototype.getActiveTextures.call(this);
  42177. if (this.baseTexture) {
  42178. activeTextures.push(this.baseTexture);
  42179. }
  42180. if (this.metallicRoughnessTexture) {
  42181. activeTextures.push(this.metallicRoughnessTexture);
  42182. }
  42183. return activeTextures;
  42184. };
  42185. /**
  42186. * Checks to see if a texture is used in the material.
  42187. * @param texture - Base texture to use.
  42188. * @returns - Boolean specifying if a texture is used in the material.
  42189. */
  42190. PBRMetallicRoughnessMaterial.prototype.hasTexture = function (texture) {
  42191. if (_super.prototype.hasTexture.call(this, texture)) {
  42192. return true;
  42193. }
  42194. if (this.baseTexture === texture) {
  42195. return true;
  42196. }
  42197. if (this.metallicRoughnessTexture === texture) {
  42198. return true;
  42199. }
  42200. return false;
  42201. };
  42202. /**
  42203. * Makes a duplicate of the current material.
  42204. * @param name - name to use for the new material.
  42205. */
  42206. PBRMetallicRoughnessMaterial.prototype.clone = function (name) {
  42207. var _this = this;
  42208. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRMetallicRoughnessMaterial(name, _this.getScene()); }, this);
  42209. clone.id = name;
  42210. clone.name = name;
  42211. return clone;
  42212. };
  42213. /**
  42214. * Serialize the material to a parsable JSON object.
  42215. */
  42216. PBRMetallicRoughnessMaterial.prototype.serialize = function () {
  42217. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  42218. serializationObject.customType = "BABYLON.PBRMetallicRoughnessMaterial";
  42219. return serializationObject;
  42220. };
  42221. /**
  42222. * Parses a JSON object correponding to the serialize function.
  42223. */
  42224. PBRMetallicRoughnessMaterial.Parse = function (source, scene, rootUrl) {
  42225. return BABYLON.SerializationHelper.Parse(function () { return new PBRMetallicRoughnessMaterial(source.name, scene); }, source, scene, rootUrl);
  42226. };
  42227. __decorate([
  42228. BABYLON.serializeAsColor3(),
  42229. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoColor")
  42230. ], PBRMetallicRoughnessMaterial.prototype, "baseColor", void 0);
  42231. __decorate([
  42232. BABYLON.serializeAsTexture(),
  42233. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoTexture")
  42234. ], PBRMetallicRoughnessMaterial.prototype, "baseTexture", void 0);
  42235. __decorate([
  42236. BABYLON.serialize(),
  42237. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42238. ], PBRMetallicRoughnessMaterial.prototype, "metallic", void 0);
  42239. __decorate([
  42240. BABYLON.serialize(),
  42241. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42242. ], PBRMetallicRoughnessMaterial.prototype, "roughness", void 0);
  42243. __decorate([
  42244. BABYLON.serializeAsTexture(),
  42245. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_metallicTexture")
  42246. ], PBRMetallicRoughnessMaterial.prototype, "metallicRoughnessTexture", void 0);
  42247. return PBRMetallicRoughnessMaterial;
  42248. }(BABYLON.PBRBaseSimpleMaterial));
  42249. BABYLON.PBRMetallicRoughnessMaterial = PBRMetallicRoughnessMaterial;
  42250. })(BABYLON || (BABYLON = {}));
  42251. //# sourceMappingURL=babylon.pbrMetallicRoughnessMaterial.js.map
  42252. var BABYLON;
  42253. (function (BABYLON) {
  42254. /**
  42255. * The PBR material of BJS following the specular glossiness convention.
  42256. *
  42257. * This fits to the PBR convention in the GLTF definition:
  42258. * https://github.com/KhronosGroup/glTF/tree/2.0/extensions/Khronos/KHR_materials_pbrSpecularGlossiness
  42259. */
  42260. var PBRSpecularGlossinessMaterial = /** @class */ (function (_super) {
  42261. __extends(PBRSpecularGlossinessMaterial, _super);
  42262. /**
  42263. * Instantiates a new PBRSpecularGlossinessMaterial instance.
  42264. *
  42265. * @param name The material name
  42266. * @param scene The scene the material will be use in.
  42267. */
  42268. function PBRSpecularGlossinessMaterial(name, scene) {
  42269. var _this = _super.call(this, name, scene) || this;
  42270. _this._useMicroSurfaceFromReflectivityMapAlpha = true;
  42271. return _this;
  42272. }
  42273. /**
  42274. * Return the currrent class name of the material.
  42275. */
  42276. PBRSpecularGlossinessMaterial.prototype.getClassName = function () {
  42277. return "PBRSpecularGlossinessMaterial";
  42278. };
  42279. /**
  42280. * Return the active textures of the material.
  42281. */
  42282. PBRSpecularGlossinessMaterial.prototype.getActiveTextures = function () {
  42283. var activeTextures = _super.prototype.getActiveTextures.call(this);
  42284. if (this.diffuseTexture) {
  42285. activeTextures.push(this.diffuseTexture);
  42286. }
  42287. if (this.specularGlossinessTexture) {
  42288. activeTextures.push(this.specularGlossinessTexture);
  42289. }
  42290. return activeTextures;
  42291. };
  42292. /**
  42293. * Checks to see if a texture is used in the material.
  42294. * @param texture - Base texture to use.
  42295. * @returns - Boolean specifying if a texture is used in the material.
  42296. */
  42297. PBRSpecularGlossinessMaterial.prototype.hasTexture = function (texture) {
  42298. if (_super.prototype.hasTexture.call(this, texture)) {
  42299. return true;
  42300. }
  42301. if (this.diffuseTexture === texture) {
  42302. return true;
  42303. }
  42304. if (this.specularGlossinessTexture === texture) {
  42305. return true;
  42306. }
  42307. return false;
  42308. };
  42309. /**
  42310. * Makes a duplicate of the current material.
  42311. * @param name - name to use for the new material.
  42312. */
  42313. PBRSpecularGlossinessMaterial.prototype.clone = function (name) {
  42314. var _this = this;
  42315. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRSpecularGlossinessMaterial(name, _this.getScene()); }, this);
  42316. clone.id = name;
  42317. clone.name = name;
  42318. return clone;
  42319. };
  42320. /**
  42321. * Serialize the material to a parsable JSON object.
  42322. */
  42323. PBRSpecularGlossinessMaterial.prototype.serialize = function () {
  42324. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  42325. serializationObject.customType = "BABYLON.PBRSpecularGlossinessMaterial";
  42326. return serializationObject;
  42327. };
  42328. /**
  42329. * Parses a JSON object correponding to the serialize function.
  42330. */
  42331. PBRSpecularGlossinessMaterial.Parse = function (source, scene, rootUrl) {
  42332. return BABYLON.SerializationHelper.Parse(function () { return new PBRSpecularGlossinessMaterial(source.name, scene); }, source, scene, rootUrl);
  42333. };
  42334. __decorate([
  42335. BABYLON.serializeAsColor3("diffuse"),
  42336. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoColor")
  42337. ], PBRSpecularGlossinessMaterial.prototype, "diffuseColor", void 0);
  42338. __decorate([
  42339. BABYLON.serializeAsTexture(),
  42340. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoTexture")
  42341. ], PBRSpecularGlossinessMaterial.prototype, "diffuseTexture", void 0);
  42342. __decorate([
  42343. BABYLON.serializeAsColor3("specular"),
  42344. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectivityColor")
  42345. ], PBRSpecularGlossinessMaterial.prototype, "specularColor", void 0);
  42346. __decorate([
  42347. BABYLON.serialize(),
  42348. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_microSurface")
  42349. ], PBRSpecularGlossinessMaterial.prototype, "glossiness", void 0);
  42350. __decorate([
  42351. BABYLON.serializeAsTexture(),
  42352. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectivityTexture")
  42353. ], PBRSpecularGlossinessMaterial.prototype, "specularGlossinessTexture", void 0);
  42354. return PBRSpecularGlossinessMaterial;
  42355. }(BABYLON.PBRBaseSimpleMaterial));
  42356. BABYLON.PBRSpecularGlossinessMaterial = PBRSpecularGlossinessMaterial;
  42357. })(BABYLON || (BABYLON = {}));
  42358. //# sourceMappingURL=babylon.pbrSpecularGlossinessMaterial.js.map
  42359. var BABYLON;
  42360. (function (BABYLON) {
  42361. BABYLON.CameraInputTypes = {};
  42362. var CameraInputsManager = /** @class */ (function () {
  42363. function CameraInputsManager(camera) {
  42364. this.attached = {};
  42365. this.camera = camera;
  42366. this.checkInputs = function () { };
  42367. }
  42368. /**
  42369. * Add an input method to a camera.
  42370. * builtin inputs example: camera.inputs.addGamepad();
  42371. * custom inputs example: camera.inputs.add(new BABYLON.FreeCameraGamepadInput());
  42372. * @param input camera input method
  42373. */
  42374. CameraInputsManager.prototype.add = function (input) {
  42375. var type = input.getSimpleName();
  42376. if (this.attached[type]) {
  42377. BABYLON.Tools.Warn("camera input of type " + type + " already exists on camera");
  42378. return;
  42379. }
  42380. this.attached[type] = input;
  42381. input.camera = this.camera;
  42382. //for checkInputs, we are dynamically creating a function
  42383. //the goal is to avoid the performance penalty of looping for inputs in the render loop
  42384. if (input.checkInputs) {
  42385. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  42386. }
  42387. if (this.attachedElement) {
  42388. input.attachControl(this.attachedElement);
  42389. }
  42390. };
  42391. /**
  42392. * Remove a specific input method from a camera
  42393. * example: camera.inputs.remove(camera.inputs.attached.mouse);
  42394. * @param inputToRemove camera input method
  42395. */
  42396. CameraInputsManager.prototype.remove = function (inputToRemove) {
  42397. for (var cam in this.attached) {
  42398. var input = this.attached[cam];
  42399. if (input === inputToRemove) {
  42400. input.detachControl(this.attachedElement);
  42401. input.camera = null;
  42402. delete this.attached[cam];
  42403. this.rebuildInputCheck();
  42404. }
  42405. }
  42406. };
  42407. CameraInputsManager.prototype.removeByType = function (inputType) {
  42408. for (var cam in this.attached) {
  42409. var input = this.attached[cam];
  42410. if (input.getClassName() === inputType) {
  42411. input.detachControl(this.attachedElement);
  42412. input.camera = null;
  42413. delete this.attached[cam];
  42414. this.rebuildInputCheck();
  42415. }
  42416. }
  42417. };
  42418. CameraInputsManager.prototype._addCheckInputs = function (fn) {
  42419. var current = this.checkInputs;
  42420. return function () {
  42421. current();
  42422. fn();
  42423. };
  42424. };
  42425. CameraInputsManager.prototype.attachInput = function (input) {
  42426. if (this.attachedElement) {
  42427. input.attachControl(this.attachedElement, this.noPreventDefault);
  42428. }
  42429. };
  42430. CameraInputsManager.prototype.attachElement = function (element, noPreventDefault) {
  42431. if (noPreventDefault === void 0) { noPreventDefault = false; }
  42432. if (this.attachedElement) {
  42433. return;
  42434. }
  42435. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  42436. this.attachedElement = element;
  42437. this.noPreventDefault = noPreventDefault;
  42438. for (var cam in this.attached) {
  42439. this.attached[cam].attachControl(element, noPreventDefault);
  42440. }
  42441. };
  42442. CameraInputsManager.prototype.detachElement = function (element, disconnect) {
  42443. if (disconnect === void 0) { disconnect = false; }
  42444. if (this.attachedElement !== element) {
  42445. return;
  42446. }
  42447. for (var cam in this.attached) {
  42448. this.attached[cam].detachControl(element);
  42449. if (disconnect) {
  42450. this.attached[cam].camera = null;
  42451. }
  42452. }
  42453. this.attachedElement = null;
  42454. };
  42455. CameraInputsManager.prototype.rebuildInputCheck = function () {
  42456. this.checkInputs = function () { };
  42457. for (var cam in this.attached) {
  42458. var input = this.attached[cam];
  42459. if (input.checkInputs) {
  42460. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  42461. }
  42462. }
  42463. };
  42464. /**
  42465. * Remove all attached input methods from a camera
  42466. */
  42467. CameraInputsManager.prototype.clear = function () {
  42468. if (this.attachedElement) {
  42469. this.detachElement(this.attachedElement, true);
  42470. }
  42471. this.attached = {};
  42472. this.attachedElement = null;
  42473. this.checkInputs = function () { };
  42474. };
  42475. CameraInputsManager.prototype.serialize = function (serializedCamera) {
  42476. var inputs = {};
  42477. for (var cam in this.attached) {
  42478. var input = this.attached[cam];
  42479. var res = BABYLON.SerializationHelper.Serialize(input);
  42480. inputs[input.getClassName()] = res;
  42481. }
  42482. serializedCamera.inputsmgr = inputs;
  42483. };
  42484. CameraInputsManager.prototype.parse = function (parsedCamera) {
  42485. var parsedInputs = parsedCamera.inputsmgr;
  42486. if (parsedInputs) {
  42487. this.clear();
  42488. for (var n in parsedInputs) {
  42489. var construct = BABYLON.CameraInputTypes[n];
  42490. if (construct) {
  42491. var parsedinput = parsedInputs[n];
  42492. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedinput, null);
  42493. this.add(input);
  42494. }
  42495. }
  42496. }
  42497. else {
  42498. //2016-03-08 this part is for managing backward compatibility
  42499. for (var n in this.attached) {
  42500. var construct = BABYLON.CameraInputTypes[this.attached[n].getClassName()];
  42501. if (construct) {
  42502. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedCamera, null);
  42503. this.remove(this.attached[n]);
  42504. this.add(input);
  42505. }
  42506. }
  42507. }
  42508. };
  42509. return CameraInputsManager;
  42510. }());
  42511. BABYLON.CameraInputsManager = CameraInputsManager;
  42512. })(BABYLON || (BABYLON = {}));
  42513. //# sourceMappingURL=babylon.cameraInputsManager.js.map
  42514. var BABYLON;
  42515. (function (BABYLON) {
  42516. var TargetCamera = /** @class */ (function (_super) {
  42517. __extends(TargetCamera, _super);
  42518. function TargetCamera(name, position, scene) {
  42519. var _this = _super.call(this, name, position, scene) || this;
  42520. _this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  42521. _this.cameraRotation = new BABYLON.Vector2(0, 0);
  42522. _this.rotation = new BABYLON.Vector3(0, 0, 0);
  42523. _this.speed = 2.0;
  42524. _this.noRotationConstraint = false;
  42525. _this.lockedTarget = null;
  42526. _this._currentTarget = BABYLON.Vector3.Zero();
  42527. _this._viewMatrix = BABYLON.Matrix.Zero();
  42528. _this._camMatrix = BABYLON.Matrix.Zero();
  42529. _this._cameraTransformMatrix = BABYLON.Matrix.Zero();
  42530. _this._cameraRotationMatrix = BABYLON.Matrix.Zero();
  42531. _this._referencePoint = new BABYLON.Vector3(0, 0, 1);
  42532. _this._currentUpVector = new BABYLON.Vector3(0, 1, 0);
  42533. _this._transformedReferencePoint = BABYLON.Vector3.Zero();
  42534. _this._lookAtTemp = BABYLON.Matrix.Zero();
  42535. _this._tempMatrix = BABYLON.Matrix.Zero();
  42536. return _this;
  42537. }
  42538. TargetCamera.prototype.getFrontPosition = function (distance) {
  42539. this.getWorldMatrix();
  42540. var direction = this.getTarget().subtract(this.position);
  42541. direction.normalize();
  42542. direction.scaleInPlace(distance);
  42543. return this.globalPosition.add(direction);
  42544. };
  42545. TargetCamera.prototype._getLockedTargetPosition = function () {
  42546. if (!this.lockedTarget) {
  42547. return null;
  42548. }
  42549. if (this.lockedTarget.absolutePosition) {
  42550. this.lockedTarget.computeWorldMatrix();
  42551. }
  42552. return this.lockedTarget.absolutePosition || this.lockedTarget;
  42553. };
  42554. TargetCamera.prototype.storeState = function () {
  42555. this._storedPosition = this.position.clone();
  42556. this._storedRotation = this.rotation.clone();
  42557. if (this.rotationQuaternion) {
  42558. this._storedRotationQuaternion = this.rotationQuaternion.clone();
  42559. }
  42560. return _super.prototype.storeState.call(this);
  42561. };
  42562. /**
  42563. * Restored camera state. You must call storeState() first
  42564. */
  42565. TargetCamera.prototype._restoreStateValues = function () {
  42566. if (!_super.prototype._restoreStateValues.call(this)) {
  42567. return false;
  42568. }
  42569. this.position = this._storedPosition.clone();
  42570. this.rotation = this._storedRotation.clone();
  42571. if (this.rotationQuaternion) {
  42572. this.rotationQuaternion = this._storedRotationQuaternion.clone();
  42573. }
  42574. this.cameraDirection.copyFromFloats(0, 0, 0);
  42575. this.cameraRotation.copyFromFloats(0, 0);
  42576. return true;
  42577. };
  42578. // Cache
  42579. TargetCamera.prototype._initCache = function () {
  42580. _super.prototype._initCache.call(this);
  42581. this._cache.lockedTarget = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  42582. this._cache.rotation = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  42583. this._cache.rotationQuaternion = new BABYLON.Quaternion(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  42584. };
  42585. TargetCamera.prototype._updateCache = function (ignoreParentClass) {
  42586. if (!ignoreParentClass) {
  42587. _super.prototype._updateCache.call(this);
  42588. }
  42589. var lockedTargetPosition = this._getLockedTargetPosition();
  42590. if (!lockedTargetPosition) {
  42591. this._cache.lockedTarget = null;
  42592. }
  42593. else {
  42594. if (!this._cache.lockedTarget) {
  42595. this._cache.lockedTarget = lockedTargetPosition.clone();
  42596. }
  42597. else {
  42598. this._cache.lockedTarget.copyFrom(lockedTargetPosition);
  42599. }
  42600. }
  42601. this._cache.rotation.copyFrom(this.rotation);
  42602. if (this.rotationQuaternion)
  42603. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  42604. };
  42605. // Synchronized
  42606. TargetCamera.prototype._isSynchronizedViewMatrix = function () {
  42607. if (!_super.prototype._isSynchronizedViewMatrix.call(this)) {
  42608. return false;
  42609. }
  42610. var lockedTargetPosition = this._getLockedTargetPosition();
  42611. return (this._cache.lockedTarget ? this._cache.lockedTarget.equals(lockedTargetPosition) : !lockedTargetPosition)
  42612. && (this.rotationQuaternion ? this.rotationQuaternion.equals(this._cache.rotationQuaternion) : this._cache.rotation.equals(this.rotation));
  42613. };
  42614. // Methods
  42615. TargetCamera.prototype._computeLocalCameraSpeed = function () {
  42616. var engine = this.getEngine();
  42617. return this.speed * Math.sqrt((engine.getDeltaTime() / (engine.getFps() * 100.0)));
  42618. };
  42619. // Target
  42620. TargetCamera.prototype.setTarget = function (target) {
  42621. this.upVector.normalize();
  42622. BABYLON.Matrix.LookAtLHToRef(this.position, target, this.upVector, this._camMatrix);
  42623. this._camMatrix.invert();
  42624. this.rotation.x = Math.atan(this._camMatrix.m[6] / this._camMatrix.m[10]);
  42625. var vDir = target.subtract(this.position);
  42626. if (vDir.x >= 0.0) {
  42627. this.rotation.y = (-Math.atan(vDir.z / vDir.x) + Math.PI / 2.0);
  42628. }
  42629. else {
  42630. this.rotation.y = (-Math.atan(vDir.z / vDir.x) - Math.PI / 2.0);
  42631. }
  42632. this.rotation.z = 0;
  42633. if (isNaN(this.rotation.x)) {
  42634. this.rotation.x = 0;
  42635. }
  42636. if (isNaN(this.rotation.y)) {
  42637. this.rotation.y = 0;
  42638. }
  42639. if (isNaN(this.rotation.z)) {
  42640. this.rotation.z = 0;
  42641. }
  42642. if (this.rotationQuaternion) {
  42643. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this.rotationQuaternion);
  42644. }
  42645. };
  42646. /**
  42647. * Return the current target position of the camera. This value is expressed in local space.
  42648. */
  42649. TargetCamera.prototype.getTarget = function () {
  42650. return this._currentTarget;
  42651. };
  42652. TargetCamera.prototype._decideIfNeedsToMove = function () {
  42653. return Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  42654. };
  42655. TargetCamera.prototype._updatePosition = function () {
  42656. if (this.parent) {
  42657. this.parent.getWorldMatrix().invertToRef(BABYLON.Tmp.Matrix[0]);
  42658. BABYLON.Vector3.TransformNormalToRef(this.cameraDirection, BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Vector3[0]);
  42659. this.position.addInPlace(BABYLON.Tmp.Vector3[0]);
  42660. return;
  42661. }
  42662. this.position.addInPlace(this.cameraDirection);
  42663. };
  42664. TargetCamera.prototype._checkInputs = function () {
  42665. var needToMove = this._decideIfNeedsToMove();
  42666. var needToRotate = Math.abs(this.cameraRotation.x) > 0 || Math.abs(this.cameraRotation.y) > 0;
  42667. // Move
  42668. if (needToMove) {
  42669. this._updatePosition();
  42670. }
  42671. // Rotate
  42672. if (needToRotate) {
  42673. this.rotation.x += this.cameraRotation.x;
  42674. this.rotation.y += this.cameraRotation.y;
  42675. //rotate, if quaternion is set and rotation was used
  42676. if (this.rotationQuaternion) {
  42677. var len = this.rotation.lengthSquared();
  42678. if (len) {
  42679. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this.rotationQuaternion);
  42680. }
  42681. }
  42682. if (!this.noRotationConstraint) {
  42683. var limit = (Math.PI / 2) * 0.95;
  42684. if (this.rotation.x > limit)
  42685. this.rotation.x = limit;
  42686. if (this.rotation.x < -limit)
  42687. this.rotation.x = -limit;
  42688. }
  42689. }
  42690. // Inertia
  42691. if (needToMove) {
  42692. if (Math.abs(this.cameraDirection.x) < this.speed * BABYLON.Epsilon) {
  42693. this.cameraDirection.x = 0;
  42694. }
  42695. if (Math.abs(this.cameraDirection.y) < this.speed * BABYLON.Epsilon) {
  42696. this.cameraDirection.y = 0;
  42697. }
  42698. if (Math.abs(this.cameraDirection.z) < this.speed * BABYLON.Epsilon) {
  42699. this.cameraDirection.z = 0;
  42700. }
  42701. this.cameraDirection.scaleInPlace(this.inertia);
  42702. }
  42703. if (needToRotate) {
  42704. if (Math.abs(this.cameraRotation.x) < this.speed * BABYLON.Epsilon) {
  42705. this.cameraRotation.x = 0;
  42706. }
  42707. if (Math.abs(this.cameraRotation.y) < this.speed * BABYLON.Epsilon) {
  42708. this.cameraRotation.y = 0;
  42709. }
  42710. this.cameraRotation.scaleInPlace(this.inertia);
  42711. }
  42712. _super.prototype._checkInputs.call(this);
  42713. };
  42714. TargetCamera.prototype._updateCameraRotationMatrix = function () {
  42715. if (this.rotationQuaternion) {
  42716. this.rotationQuaternion.toRotationMatrix(this._cameraRotationMatrix);
  42717. }
  42718. else {
  42719. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  42720. }
  42721. //update the up vector!
  42722. BABYLON.Vector3.TransformNormalToRef(this.upVector, this._cameraRotationMatrix, this._currentUpVector);
  42723. };
  42724. TargetCamera.prototype._getViewMatrix = function () {
  42725. if (this.lockedTarget) {
  42726. this.setTarget(this._getLockedTargetPosition());
  42727. }
  42728. // Compute
  42729. this._updateCameraRotationMatrix();
  42730. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  42731. // Computing target and final matrix
  42732. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  42733. if (this.getScene().useRightHandedSystem) {
  42734. BABYLON.Matrix.LookAtRHToRef(this.position, this._currentTarget, this._currentUpVector, this._viewMatrix);
  42735. }
  42736. else {
  42737. BABYLON.Matrix.LookAtLHToRef(this.position, this._currentTarget, this._currentUpVector, this._viewMatrix);
  42738. }
  42739. return this._viewMatrix;
  42740. };
  42741. /**
  42742. * @override
  42743. * Override Camera.createRigCamera
  42744. */
  42745. TargetCamera.prototype.createRigCamera = function (name, cameraIndex) {
  42746. if (this.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  42747. var rigCamera = new TargetCamera(name, this.position.clone(), this.getScene());
  42748. if (this.cameraRigMode === BABYLON.Camera.RIG_MODE_VR || this.cameraRigMode === BABYLON.Camera.RIG_MODE_WEBVR) {
  42749. if (!this.rotationQuaternion) {
  42750. this.rotationQuaternion = new BABYLON.Quaternion();
  42751. }
  42752. rigCamera._cameraRigParams = {};
  42753. rigCamera.rotationQuaternion = new BABYLON.Quaternion();
  42754. }
  42755. return rigCamera;
  42756. }
  42757. return null;
  42758. };
  42759. /**
  42760. * @override
  42761. * Override Camera._updateRigCameras
  42762. */
  42763. TargetCamera.prototype._updateRigCameras = function () {
  42764. var camLeft = this._rigCameras[0];
  42765. var camRight = this._rigCameras[1];
  42766. switch (this.cameraRigMode) {
  42767. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  42768. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  42769. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  42770. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  42771. //provisionnaly using _cameraRigParams.stereoHalfAngle instead of calculations based on _cameraRigParams.interaxialDistance:
  42772. var leftSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? 1 : -1;
  42773. var rightSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? -1 : 1;
  42774. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * leftSign, camLeft.position);
  42775. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * rightSign, camRight.position);
  42776. camLeft.setTarget(this.getTarget());
  42777. camRight.setTarget(this.getTarget());
  42778. break;
  42779. case BABYLON.Camera.RIG_MODE_VR:
  42780. if (camLeft.rotationQuaternion) {
  42781. camLeft.rotationQuaternion.copyFrom(this.rotationQuaternion);
  42782. camRight.rotationQuaternion.copyFrom(this.rotationQuaternion);
  42783. }
  42784. else {
  42785. camLeft.rotation.copyFrom(this.rotation);
  42786. camRight.rotation.copyFrom(this.rotation);
  42787. }
  42788. camLeft.position.copyFrom(this.position);
  42789. camRight.position.copyFrom(this.position);
  42790. break;
  42791. }
  42792. _super.prototype._updateRigCameras.call(this);
  42793. };
  42794. TargetCamera.prototype._getRigCamPosition = function (halfSpace, result) {
  42795. if (!this._rigCamTransformMatrix) {
  42796. this._rigCamTransformMatrix = new BABYLON.Matrix();
  42797. }
  42798. var target = this.getTarget();
  42799. BABYLON.Matrix.Translation(-target.x, -target.y, -target.z).multiplyToRef(BABYLON.Matrix.RotationY(halfSpace), this._rigCamTransformMatrix);
  42800. this._rigCamTransformMatrix = this._rigCamTransformMatrix.multiply(BABYLON.Matrix.Translation(target.x, target.y, target.z));
  42801. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this._rigCamTransformMatrix, result);
  42802. };
  42803. TargetCamera.prototype.getClassName = function () {
  42804. return "TargetCamera";
  42805. };
  42806. __decorate([
  42807. BABYLON.serializeAsVector3()
  42808. ], TargetCamera.prototype, "rotation", void 0);
  42809. __decorate([
  42810. BABYLON.serialize()
  42811. ], TargetCamera.prototype, "speed", void 0);
  42812. __decorate([
  42813. BABYLON.serializeAsMeshReference("lockedTargetId")
  42814. ], TargetCamera.prototype, "lockedTarget", void 0);
  42815. return TargetCamera;
  42816. }(BABYLON.Camera));
  42817. BABYLON.TargetCamera = TargetCamera;
  42818. })(BABYLON || (BABYLON = {}));
  42819. //# sourceMappingURL=babylon.targetCamera.js.map
  42820. var BABYLON;
  42821. (function (BABYLON) {
  42822. var FreeCameraMouseInput = /** @class */ (function () {
  42823. function FreeCameraMouseInput(touchEnabled) {
  42824. if (touchEnabled === void 0) { touchEnabled = true; }
  42825. this.touchEnabled = touchEnabled;
  42826. this.buttons = [0, 1, 2];
  42827. this.angularSensibility = 2000.0;
  42828. this.previousPosition = null;
  42829. }
  42830. FreeCameraMouseInput.prototype.attachControl = function (element, noPreventDefault) {
  42831. var _this = this;
  42832. var engine = this.camera.getEngine();
  42833. if (!this._pointerInput) {
  42834. this._pointerInput = function (p, s) {
  42835. var evt = p.event;
  42836. if (engine.isInVRExclusivePointerMode) {
  42837. return;
  42838. }
  42839. if (!_this.touchEnabled && evt.pointerType === "touch") {
  42840. return;
  42841. }
  42842. if (p.type !== BABYLON.PointerEventTypes.POINTERMOVE && _this.buttons.indexOf(evt.button) === -1) {
  42843. return;
  42844. }
  42845. var srcElement = (evt.srcElement || evt.target);
  42846. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN && srcElement) {
  42847. try {
  42848. srcElement.setPointerCapture(evt.pointerId);
  42849. }
  42850. catch (e) {
  42851. //Nothing to do with the error. Execution will continue.
  42852. }
  42853. _this.previousPosition = {
  42854. x: evt.clientX,
  42855. y: evt.clientY
  42856. };
  42857. if (!noPreventDefault) {
  42858. evt.preventDefault();
  42859. element.focus();
  42860. }
  42861. }
  42862. else if (p.type === BABYLON.PointerEventTypes.POINTERUP && srcElement) {
  42863. try {
  42864. srcElement.releasePointerCapture(evt.pointerId);
  42865. }
  42866. catch (e) {
  42867. //Nothing to do with the error.
  42868. }
  42869. _this.previousPosition = null;
  42870. if (!noPreventDefault) {
  42871. evt.preventDefault();
  42872. }
  42873. }
  42874. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  42875. if (!_this.previousPosition || engine.isPointerLock) {
  42876. return;
  42877. }
  42878. var offsetX = evt.clientX - _this.previousPosition.x;
  42879. var offsetY = evt.clientY - _this.previousPosition.y;
  42880. if (_this.camera.getScene().useRightHandedSystem) {
  42881. _this.camera.cameraRotation.y -= offsetX / _this.angularSensibility;
  42882. }
  42883. else {
  42884. _this.camera.cameraRotation.y += offsetX / _this.angularSensibility;
  42885. }
  42886. _this.camera.cameraRotation.x += offsetY / _this.angularSensibility;
  42887. _this.previousPosition = {
  42888. x: evt.clientX,
  42889. y: evt.clientY
  42890. };
  42891. if (!noPreventDefault) {
  42892. evt.preventDefault();
  42893. }
  42894. }
  42895. };
  42896. }
  42897. this._onMouseMove = function (evt) {
  42898. if (!engine.isPointerLock) {
  42899. return;
  42900. }
  42901. if (engine.isInVRExclusivePointerMode) {
  42902. return;
  42903. }
  42904. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  42905. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  42906. if (_this.camera.getScene().useRightHandedSystem) {
  42907. _this.camera.cameraRotation.y -= offsetX / _this.angularSensibility;
  42908. }
  42909. else {
  42910. _this.camera.cameraRotation.y += offsetX / _this.angularSensibility;
  42911. }
  42912. _this.camera.cameraRotation.x += offsetY / _this.angularSensibility;
  42913. _this.previousPosition = null;
  42914. if (!noPreventDefault) {
  42915. evt.preventDefault();
  42916. }
  42917. };
  42918. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  42919. element.addEventListener("mousemove", this._onMouseMove, false);
  42920. };
  42921. FreeCameraMouseInput.prototype.detachControl = function (element) {
  42922. if (this._observer && element) {
  42923. this.camera.getScene().onPointerObservable.remove(this._observer);
  42924. if (this._onMouseMove) {
  42925. element.removeEventListener("mousemove", this._onMouseMove);
  42926. }
  42927. this._observer = null;
  42928. this._onMouseMove = null;
  42929. this.previousPosition = null;
  42930. }
  42931. };
  42932. FreeCameraMouseInput.prototype.getClassName = function () {
  42933. return "FreeCameraMouseInput";
  42934. };
  42935. FreeCameraMouseInput.prototype.getSimpleName = function () {
  42936. return "mouse";
  42937. };
  42938. __decorate([
  42939. BABYLON.serialize()
  42940. ], FreeCameraMouseInput.prototype, "buttons", void 0);
  42941. __decorate([
  42942. BABYLON.serialize()
  42943. ], FreeCameraMouseInput.prototype, "angularSensibility", void 0);
  42944. return FreeCameraMouseInput;
  42945. }());
  42946. BABYLON.FreeCameraMouseInput = FreeCameraMouseInput;
  42947. BABYLON.CameraInputTypes["FreeCameraMouseInput"] = FreeCameraMouseInput;
  42948. })(BABYLON || (BABYLON = {}));
  42949. //# sourceMappingURL=babylon.freeCameraMouseInput.js.map
  42950. var BABYLON;
  42951. (function (BABYLON) {
  42952. var FreeCameraKeyboardMoveInput = /** @class */ (function () {
  42953. function FreeCameraKeyboardMoveInput() {
  42954. this._keys = new Array();
  42955. this.keysUp = [38];
  42956. this.keysDown = [40];
  42957. this.keysLeft = [37];
  42958. this.keysRight = [39];
  42959. }
  42960. FreeCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  42961. var _this = this;
  42962. if (this._onCanvasBlurObserver) {
  42963. return;
  42964. }
  42965. this._scene = this.camera.getScene();
  42966. this._engine = this._scene.getEngine();
  42967. this._onCanvasBlurObserver = this._engine.onCanvasBlurObservable.add(function () {
  42968. _this._keys = [];
  42969. });
  42970. this._onKeyboardObserver = this._scene.onKeyboardObservable.add(function (info) {
  42971. var evt = info.event;
  42972. if (info.type === BABYLON.KeyboardEventTypes.KEYDOWN) {
  42973. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  42974. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  42975. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  42976. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  42977. var index = _this._keys.indexOf(evt.keyCode);
  42978. if (index === -1) {
  42979. _this._keys.push(evt.keyCode);
  42980. }
  42981. if (!noPreventDefault) {
  42982. evt.preventDefault();
  42983. }
  42984. }
  42985. }
  42986. else {
  42987. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  42988. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  42989. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  42990. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  42991. var index = _this._keys.indexOf(evt.keyCode);
  42992. if (index >= 0) {
  42993. _this._keys.splice(index, 1);
  42994. }
  42995. if (!noPreventDefault) {
  42996. evt.preventDefault();
  42997. }
  42998. }
  42999. }
  43000. });
  43001. };
  43002. FreeCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  43003. if (this._scene) {
  43004. if (this._onKeyboardObserver) {
  43005. this._scene.onKeyboardObservable.remove(this._onKeyboardObserver);
  43006. }
  43007. if (this._onCanvasBlurObserver) {
  43008. this._engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  43009. }
  43010. this._onKeyboardObserver = null;
  43011. this._onCanvasBlurObserver = null;
  43012. }
  43013. this._keys = [];
  43014. };
  43015. FreeCameraKeyboardMoveInput.prototype.checkInputs = function () {
  43016. if (this._onKeyboardObserver) {
  43017. var camera = this.camera;
  43018. // Keyboard
  43019. for (var index = 0; index < this._keys.length; index++) {
  43020. var keyCode = this._keys[index];
  43021. var speed = camera._computeLocalCameraSpeed();
  43022. if (this.keysLeft.indexOf(keyCode) !== -1) {
  43023. camera._localDirection.copyFromFloats(-speed, 0, 0);
  43024. }
  43025. else if (this.keysUp.indexOf(keyCode) !== -1) {
  43026. camera._localDirection.copyFromFloats(0, 0, speed);
  43027. }
  43028. else if (this.keysRight.indexOf(keyCode) !== -1) {
  43029. camera._localDirection.copyFromFloats(speed, 0, 0);
  43030. }
  43031. else if (this.keysDown.indexOf(keyCode) !== -1) {
  43032. camera._localDirection.copyFromFloats(0, 0, -speed);
  43033. }
  43034. if (camera.getScene().useRightHandedSystem) {
  43035. camera._localDirection.z *= -1;
  43036. }
  43037. camera.getViewMatrix().invertToRef(camera._cameraTransformMatrix);
  43038. BABYLON.Vector3.TransformNormalToRef(camera._localDirection, camera._cameraTransformMatrix, camera._transformedDirection);
  43039. camera.cameraDirection.addInPlace(camera._transformedDirection);
  43040. }
  43041. }
  43042. };
  43043. FreeCameraKeyboardMoveInput.prototype.getClassName = function () {
  43044. return "FreeCameraKeyboardMoveInput";
  43045. };
  43046. FreeCameraKeyboardMoveInput.prototype._onLostFocus = function (e) {
  43047. this._keys = [];
  43048. };
  43049. FreeCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  43050. return "keyboard";
  43051. };
  43052. __decorate([
  43053. BABYLON.serialize()
  43054. ], FreeCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  43055. __decorate([
  43056. BABYLON.serialize()
  43057. ], FreeCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  43058. __decorate([
  43059. BABYLON.serialize()
  43060. ], FreeCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  43061. __decorate([
  43062. BABYLON.serialize()
  43063. ], FreeCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  43064. return FreeCameraKeyboardMoveInput;
  43065. }());
  43066. BABYLON.FreeCameraKeyboardMoveInput = FreeCameraKeyboardMoveInput;
  43067. BABYLON.CameraInputTypes["FreeCameraKeyboardMoveInput"] = FreeCameraKeyboardMoveInput;
  43068. })(BABYLON || (BABYLON = {}));
  43069. //# sourceMappingURL=babylon.freeCameraKeyboardMoveInput.js.map
  43070. var BABYLON;
  43071. (function (BABYLON) {
  43072. var FreeCameraInputsManager = /** @class */ (function (_super) {
  43073. __extends(FreeCameraInputsManager, _super);
  43074. function FreeCameraInputsManager(camera) {
  43075. return _super.call(this, camera) || this;
  43076. }
  43077. FreeCameraInputsManager.prototype.addKeyboard = function () {
  43078. this.add(new BABYLON.FreeCameraKeyboardMoveInput());
  43079. return this;
  43080. };
  43081. FreeCameraInputsManager.prototype.addMouse = function (touchEnabled) {
  43082. if (touchEnabled === void 0) { touchEnabled = true; }
  43083. this.add(new BABYLON.FreeCameraMouseInput(touchEnabled));
  43084. return this;
  43085. };
  43086. FreeCameraInputsManager.prototype.addGamepad = function () {
  43087. this.add(new BABYLON.FreeCameraGamepadInput());
  43088. return this;
  43089. };
  43090. FreeCameraInputsManager.prototype.addDeviceOrientation = function () {
  43091. this.add(new BABYLON.FreeCameraDeviceOrientationInput());
  43092. return this;
  43093. };
  43094. FreeCameraInputsManager.prototype.addTouch = function () {
  43095. this.add(new BABYLON.FreeCameraTouchInput());
  43096. return this;
  43097. };
  43098. FreeCameraInputsManager.prototype.addVirtualJoystick = function () {
  43099. this.add(new BABYLON.FreeCameraVirtualJoystickInput());
  43100. return this;
  43101. };
  43102. return FreeCameraInputsManager;
  43103. }(BABYLON.CameraInputsManager));
  43104. BABYLON.FreeCameraInputsManager = FreeCameraInputsManager;
  43105. })(BABYLON || (BABYLON = {}));
  43106. //# sourceMappingURL=babylon.freeCameraInputsManager.js.map
  43107. var BABYLON;
  43108. (function (BABYLON) {
  43109. var FreeCamera = /** @class */ (function (_super) {
  43110. __extends(FreeCamera, _super);
  43111. function FreeCamera(name, position, scene) {
  43112. var _this = _super.call(this, name, position, scene) || this;
  43113. _this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  43114. _this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  43115. _this.checkCollisions = false;
  43116. _this.applyGravity = false;
  43117. _this._needMoveForGravity = false;
  43118. _this._oldPosition = BABYLON.Vector3.Zero();
  43119. _this._diffPosition = BABYLON.Vector3.Zero();
  43120. _this._newPosition = BABYLON.Vector3.Zero();
  43121. // Collisions
  43122. _this._collisionMask = -1;
  43123. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  43124. if (collidedMesh === void 0) { collidedMesh = null; }
  43125. //TODO move this to the collision coordinator!
  43126. if (_this.getScene().workerCollisions)
  43127. newPosition.multiplyInPlace(_this._collider._radius);
  43128. var updatePosition = function (newPos) {
  43129. _this._newPosition.copyFrom(newPos);
  43130. _this._newPosition.subtractToRef(_this._oldPosition, _this._diffPosition);
  43131. if (_this._diffPosition.length() > BABYLON.Engine.CollisionsEpsilon) {
  43132. _this.position.addInPlace(_this._diffPosition);
  43133. if (_this.onCollide && collidedMesh) {
  43134. _this.onCollide(collidedMesh);
  43135. }
  43136. }
  43137. };
  43138. updatePosition(newPosition);
  43139. };
  43140. _this.inputs = new BABYLON.FreeCameraInputsManager(_this);
  43141. _this.inputs.addKeyboard().addMouse();
  43142. return _this;
  43143. }
  43144. Object.defineProperty(FreeCamera.prototype, "angularSensibility", {
  43145. //-- begin properties for backward compatibility for inputs
  43146. /**
  43147. * Gets the input sensibility for a mouse input. (default is 2000.0)
  43148. * Higher values reduce sensitivity.
  43149. */
  43150. get: function () {
  43151. var mouse = this.inputs.attached["mouse"];
  43152. if (mouse)
  43153. return mouse.angularSensibility;
  43154. return 0;
  43155. },
  43156. /**
  43157. * Sets the input sensibility for a mouse input. (default is 2000.0)
  43158. * Higher values reduce sensitivity.
  43159. */
  43160. set: function (value) {
  43161. var mouse = this.inputs.attached["mouse"];
  43162. if (mouse)
  43163. mouse.angularSensibility = value;
  43164. },
  43165. enumerable: true,
  43166. configurable: true
  43167. });
  43168. Object.defineProperty(FreeCamera.prototype, "keysUp", {
  43169. get: function () {
  43170. var keyboard = this.inputs.attached["keyboard"];
  43171. if (keyboard)
  43172. return keyboard.keysUp;
  43173. return [];
  43174. },
  43175. set: function (value) {
  43176. var keyboard = this.inputs.attached["keyboard"];
  43177. if (keyboard)
  43178. keyboard.keysUp = value;
  43179. },
  43180. enumerable: true,
  43181. configurable: true
  43182. });
  43183. Object.defineProperty(FreeCamera.prototype, "keysDown", {
  43184. get: function () {
  43185. var keyboard = this.inputs.attached["keyboard"];
  43186. if (keyboard)
  43187. return keyboard.keysDown;
  43188. return [];
  43189. },
  43190. set: function (value) {
  43191. var keyboard = this.inputs.attached["keyboard"];
  43192. if (keyboard)
  43193. keyboard.keysDown = value;
  43194. },
  43195. enumerable: true,
  43196. configurable: true
  43197. });
  43198. Object.defineProperty(FreeCamera.prototype, "keysLeft", {
  43199. get: function () {
  43200. var keyboard = this.inputs.attached["keyboard"];
  43201. if (keyboard)
  43202. return keyboard.keysLeft;
  43203. return [];
  43204. },
  43205. set: function (value) {
  43206. var keyboard = this.inputs.attached["keyboard"];
  43207. if (keyboard)
  43208. keyboard.keysLeft = value;
  43209. },
  43210. enumerable: true,
  43211. configurable: true
  43212. });
  43213. Object.defineProperty(FreeCamera.prototype, "keysRight", {
  43214. get: function () {
  43215. var keyboard = this.inputs.attached["keyboard"];
  43216. if (keyboard)
  43217. return keyboard.keysRight;
  43218. return [];
  43219. },
  43220. set: function (value) {
  43221. var keyboard = this.inputs.attached["keyboard"];
  43222. if (keyboard)
  43223. keyboard.keysRight = value;
  43224. },
  43225. enumerable: true,
  43226. configurable: true
  43227. });
  43228. // Controls
  43229. FreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  43230. this.inputs.attachElement(element, noPreventDefault);
  43231. };
  43232. FreeCamera.prototype.detachControl = function (element) {
  43233. this.inputs.detachElement(element);
  43234. this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  43235. this.cameraRotation = new BABYLON.Vector2(0, 0);
  43236. };
  43237. Object.defineProperty(FreeCamera.prototype, "collisionMask", {
  43238. get: function () {
  43239. return this._collisionMask;
  43240. },
  43241. set: function (mask) {
  43242. this._collisionMask = !isNaN(mask) ? mask : -1;
  43243. },
  43244. enumerable: true,
  43245. configurable: true
  43246. });
  43247. FreeCamera.prototype._collideWithWorld = function (displacement) {
  43248. var globalPosition;
  43249. if (this.parent) {
  43250. globalPosition = BABYLON.Vector3.TransformCoordinates(this.position, this.parent.getWorldMatrix());
  43251. }
  43252. else {
  43253. globalPosition = this.position;
  43254. }
  43255. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPosition);
  43256. this._oldPosition.addInPlace(this.ellipsoidOffset);
  43257. if (!this._collider) {
  43258. this._collider = new BABYLON.Collider();
  43259. }
  43260. this._collider._radius = this.ellipsoid;
  43261. this._collider.collisionMask = this._collisionMask;
  43262. //no need for clone, as long as gravity is not on.
  43263. var actualDisplacement = displacement;
  43264. //add gravity to the direction to prevent the dual-collision checking
  43265. if (this.applyGravity) {
  43266. //this prevents mending with cameraDirection, a global variable of the free camera class.
  43267. actualDisplacement = displacement.add(this.getScene().gravity);
  43268. }
  43269. this.getScene().collisionCoordinator.getNewPosition(this._oldPosition, actualDisplacement, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  43270. };
  43271. FreeCamera.prototype._checkInputs = function () {
  43272. if (!this._localDirection) {
  43273. this._localDirection = BABYLON.Vector3.Zero();
  43274. this._transformedDirection = BABYLON.Vector3.Zero();
  43275. }
  43276. this.inputs.checkInputs();
  43277. _super.prototype._checkInputs.call(this);
  43278. };
  43279. FreeCamera.prototype._decideIfNeedsToMove = function () {
  43280. return this._needMoveForGravity || Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  43281. };
  43282. FreeCamera.prototype._updatePosition = function () {
  43283. if (this.checkCollisions && this.getScene().collisionsEnabled) {
  43284. this._collideWithWorld(this.cameraDirection);
  43285. }
  43286. else {
  43287. _super.prototype._updatePosition.call(this);
  43288. }
  43289. };
  43290. FreeCamera.prototype.dispose = function () {
  43291. this.inputs.clear();
  43292. _super.prototype.dispose.call(this);
  43293. };
  43294. FreeCamera.prototype.getClassName = function () {
  43295. return "FreeCamera";
  43296. };
  43297. __decorate([
  43298. BABYLON.serializeAsVector3()
  43299. ], FreeCamera.prototype, "ellipsoid", void 0);
  43300. __decorate([
  43301. BABYLON.serializeAsVector3()
  43302. ], FreeCamera.prototype, "ellipsoidOffset", void 0);
  43303. __decorate([
  43304. BABYLON.serialize()
  43305. ], FreeCamera.prototype, "checkCollisions", void 0);
  43306. __decorate([
  43307. BABYLON.serialize()
  43308. ], FreeCamera.prototype, "applyGravity", void 0);
  43309. return FreeCamera;
  43310. }(BABYLON.TargetCamera));
  43311. BABYLON.FreeCamera = FreeCamera;
  43312. })(BABYLON || (BABYLON = {}));
  43313. //# sourceMappingURL=babylon.freeCamera.js.map
  43314. var BABYLON;
  43315. (function (BABYLON) {
  43316. var ArcRotateCameraKeyboardMoveInput = /** @class */ (function () {
  43317. function ArcRotateCameraKeyboardMoveInput() {
  43318. this._keys = new Array();
  43319. this.keysUp = [38];
  43320. this.keysDown = [40];
  43321. this.keysLeft = [37];
  43322. this.keysRight = [39];
  43323. this.keysReset = [220];
  43324. this.panningSensibility = 50.0;
  43325. this.zoomingSensibility = 25.0;
  43326. this.useAltToZoom = true;
  43327. }
  43328. ArcRotateCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  43329. var _this = this;
  43330. if (this._onCanvasBlurObserver) {
  43331. return;
  43332. }
  43333. this._scene = this.camera.getScene();
  43334. this._engine = this._scene.getEngine();
  43335. this._onCanvasBlurObserver = this._engine.onCanvasBlurObservable.add(function () {
  43336. _this._keys = [];
  43337. });
  43338. this._onKeyboardObserver = this._scene.onKeyboardObservable.add(function (info) {
  43339. var evt = info.event;
  43340. if (info.type === BABYLON.KeyboardEventTypes.KEYDOWN) {
  43341. _this._ctrlPressed = evt.ctrlKey;
  43342. _this._altPressed = evt.altKey;
  43343. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  43344. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  43345. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  43346. _this.keysRight.indexOf(evt.keyCode) !== -1 ||
  43347. _this.keysReset.indexOf(evt.keyCode) !== -1) {
  43348. var index = _this._keys.indexOf(evt.keyCode);
  43349. if (index === -1) {
  43350. _this._keys.push(evt.keyCode);
  43351. }
  43352. if (evt.preventDefault) {
  43353. if (!noPreventDefault) {
  43354. evt.preventDefault();
  43355. }
  43356. }
  43357. }
  43358. }
  43359. else {
  43360. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  43361. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  43362. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  43363. _this.keysRight.indexOf(evt.keyCode) !== -1 ||
  43364. _this.keysReset.indexOf(evt.keyCode) !== -1) {
  43365. var index = _this._keys.indexOf(evt.keyCode);
  43366. if (index >= 0) {
  43367. _this._keys.splice(index, 1);
  43368. }
  43369. if (evt.preventDefault) {
  43370. if (!noPreventDefault) {
  43371. evt.preventDefault();
  43372. }
  43373. }
  43374. }
  43375. }
  43376. });
  43377. };
  43378. ArcRotateCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  43379. if (this._scene) {
  43380. if (this._onKeyboardObserver) {
  43381. this._scene.onKeyboardObservable.remove(this._onKeyboardObserver);
  43382. }
  43383. if (this._onCanvasBlurObserver) {
  43384. this._engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  43385. }
  43386. this._onKeyboardObserver = null;
  43387. this._onCanvasBlurObserver = null;
  43388. }
  43389. this._keys = [];
  43390. };
  43391. ArcRotateCameraKeyboardMoveInput.prototype.checkInputs = function () {
  43392. if (this._onKeyboardObserver) {
  43393. var camera = this.camera;
  43394. for (var index = 0; index < this._keys.length; index++) {
  43395. var keyCode = this._keys[index];
  43396. if (this.keysLeft.indexOf(keyCode) !== -1) {
  43397. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  43398. camera.inertialPanningX -= 1 / this.panningSensibility;
  43399. }
  43400. else {
  43401. camera.inertialAlphaOffset -= 0.01;
  43402. }
  43403. }
  43404. else if (this.keysUp.indexOf(keyCode) !== -1) {
  43405. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  43406. camera.inertialPanningY += 1 / this.panningSensibility;
  43407. }
  43408. else if (this._altPressed && this.useAltToZoom) {
  43409. camera.inertialRadiusOffset += 1 / this.zoomingSensibility;
  43410. }
  43411. else {
  43412. camera.inertialBetaOffset -= 0.01;
  43413. }
  43414. }
  43415. else if (this.keysRight.indexOf(keyCode) !== -1) {
  43416. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  43417. camera.inertialPanningX += 1 / this.panningSensibility;
  43418. }
  43419. else {
  43420. camera.inertialAlphaOffset += 0.01;
  43421. }
  43422. }
  43423. else if (this.keysDown.indexOf(keyCode) !== -1) {
  43424. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  43425. camera.inertialPanningY -= 1 / this.panningSensibility;
  43426. }
  43427. else if (this._altPressed && this.useAltToZoom) {
  43428. camera.inertialRadiusOffset -= 1 / this.zoomingSensibility;
  43429. }
  43430. else {
  43431. camera.inertialBetaOffset += 0.01;
  43432. }
  43433. }
  43434. else if (this.keysReset.indexOf(keyCode) !== -1) {
  43435. camera.restoreState();
  43436. }
  43437. }
  43438. }
  43439. };
  43440. ArcRotateCameraKeyboardMoveInput.prototype.getClassName = function () {
  43441. return "ArcRotateCameraKeyboardMoveInput";
  43442. };
  43443. ArcRotateCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  43444. return "keyboard";
  43445. };
  43446. __decorate([
  43447. BABYLON.serialize()
  43448. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  43449. __decorate([
  43450. BABYLON.serialize()
  43451. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  43452. __decorate([
  43453. BABYLON.serialize()
  43454. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  43455. __decorate([
  43456. BABYLON.serialize()
  43457. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  43458. __decorate([
  43459. BABYLON.serialize()
  43460. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysReset", void 0);
  43461. __decorate([
  43462. BABYLON.serialize()
  43463. ], ArcRotateCameraKeyboardMoveInput.prototype, "panningSensibility", void 0);
  43464. __decorate([
  43465. BABYLON.serialize()
  43466. ], ArcRotateCameraKeyboardMoveInput.prototype, "zoomingSensibility", void 0);
  43467. __decorate([
  43468. BABYLON.serialize()
  43469. ], ArcRotateCameraKeyboardMoveInput.prototype, "useAltToZoom", void 0);
  43470. return ArcRotateCameraKeyboardMoveInput;
  43471. }());
  43472. BABYLON.ArcRotateCameraKeyboardMoveInput = ArcRotateCameraKeyboardMoveInput;
  43473. BABYLON.CameraInputTypes["ArcRotateCameraKeyboardMoveInput"] = ArcRotateCameraKeyboardMoveInput;
  43474. })(BABYLON || (BABYLON = {}));
  43475. //# sourceMappingURL=babylon.arcRotateCameraKeyboardMoveInput.js.map
  43476. var BABYLON;
  43477. (function (BABYLON) {
  43478. var ArcRotateCameraMouseWheelInput = /** @class */ (function () {
  43479. function ArcRotateCameraMouseWheelInput() {
  43480. this.wheelPrecision = 3.0;
  43481. /**
  43482. * wheelDeltaPercentage will be used instead of wheelPrecision if different from 0.
  43483. * It defines the percentage of current camera.radius to use as delta when wheel is used.
  43484. */
  43485. this.wheelDeltaPercentage = 0;
  43486. }
  43487. ArcRotateCameraMouseWheelInput.prototype.attachControl = function (element, noPreventDefault) {
  43488. var _this = this;
  43489. this._wheel = function (p, s) {
  43490. //sanity check - this should be a PointerWheel event.
  43491. if (p.type !== BABYLON.PointerEventTypes.POINTERWHEEL)
  43492. return;
  43493. var event = p.event;
  43494. var delta = 0;
  43495. if (event.wheelDelta) {
  43496. delta = _this.wheelDeltaPercentage ? (event.wheelDelta * 0.01) * _this.camera.radius * _this.wheelDeltaPercentage : event.wheelDelta / (_this.wheelPrecision * 40);
  43497. }
  43498. else if (event.detail) {
  43499. delta = -event.detail / _this.wheelPrecision;
  43500. }
  43501. if (delta)
  43502. _this.camera.inertialRadiusOffset += delta;
  43503. if (event.preventDefault) {
  43504. if (!noPreventDefault) {
  43505. event.preventDefault();
  43506. }
  43507. }
  43508. };
  43509. this._observer = this.camera.getScene().onPointerObservable.add(this._wheel, BABYLON.PointerEventTypes.POINTERWHEEL);
  43510. };
  43511. ArcRotateCameraMouseWheelInput.prototype.detachControl = function (element) {
  43512. if (this._observer && element) {
  43513. this.camera.getScene().onPointerObservable.remove(this._observer);
  43514. this._observer = null;
  43515. this._wheel = null;
  43516. }
  43517. };
  43518. ArcRotateCameraMouseWheelInput.prototype.getClassName = function () {
  43519. return "ArcRotateCameraMouseWheelInput";
  43520. };
  43521. ArcRotateCameraMouseWheelInput.prototype.getSimpleName = function () {
  43522. return "mousewheel";
  43523. };
  43524. __decorate([
  43525. BABYLON.serialize()
  43526. ], ArcRotateCameraMouseWheelInput.prototype, "wheelPrecision", void 0);
  43527. __decorate([
  43528. BABYLON.serialize()
  43529. ], ArcRotateCameraMouseWheelInput.prototype, "wheelDeltaPercentage", void 0);
  43530. return ArcRotateCameraMouseWheelInput;
  43531. }());
  43532. BABYLON.ArcRotateCameraMouseWheelInput = ArcRotateCameraMouseWheelInput;
  43533. BABYLON.CameraInputTypes["ArcRotateCameraMouseWheelInput"] = ArcRotateCameraMouseWheelInput;
  43534. })(BABYLON || (BABYLON = {}));
  43535. //# sourceMappingURL=babylon.arcRotateCameraMouseWheelInput.js.map
  43536. var BABYLON;
  43537. (function (BABYLON) {
  43538. var ArcRotateCameraPointersInput = /** @class */ (function () {
  43539. function ArcRotateCameraPointersInput() {
  43540. this.buttons = [0, 1, 2];
  43541. this.angularSensibilityX = 1000.0;
  43542. this.angularSensibilityY = 1000.0;
  43543. this.pinchPrecision = 12.0;
  43544. /**
  43545. * pinchDeltaPercentage will be used instead of pinchPrecision if different from 0.
  43546. * It defines the percentage of current camera.radius to use as delta when pinch zoom is used.
  43547. */
  43548. this.pinchDeltaPercentage = 0;
  43549. this.panningSensibility = 1000.0;
  43550. this.multiTouchPanning = true;
  43551. this.multiTouchPanAndZoom = true;
  43552. this._isPanClick = false;
  43553. this.pinchInwards = true;
  43554. }
  43555. ArcRotateCameraPointersInput.prototype.attachControl = function (element, noPreventDefault) {
  43556. var _this = this;
  43557. var engine = this.camera.getEngine();
  43558. var cacheSoloPointer; // cache pointer object for better perf on camera rotation
  43559. var pointA = null;
  43560. var pointB = null;
  43561. var previousPinchSquaredDistance = 0;
  43562. var initialDistance = 0;
  43563. var twoFingerActivityCount = 0;
  43564. var previousMultiTouchPanPosition = { x: 0, y: 0, isPaning: false, isPinching: false };
  43565. this._pointerInput = function (p, s) {
  43566. var evt = p.event;
  43567. var isTouch = p.event.pointerType === "touch";
  43568. if (engine.isInVRExclusivePointerMode) {
  43569. return;
  43570. }
  43571. if (p.type !== BABYLON.PointerEventTypes.POINTERMOVE && _this.buttons.indexOf(evt.button) === -1) {
  43572. return;
  43573. }
  43574. var srcElement = (evt.srcElement || evt.target);
  43575. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN && srcElement) {
  43576. try {
  43577. srcElement.setPointerCapture(evt.pointerId);
  43578. }
  43579. catch (e) {
  43580. //Nothing to do with the error. Execution will continue.
  43581. }
  43582. // Manage panning with pan button click
  43583. _this._isPanClick = evt.button === _this.camera._panningMouseButton;
  43584. // manage pointers
  43585. cacheSoloPointer = { x: evt.clientX, y: evt.clientY, pointerId: evt.pointerId, type: evt.pointerType };
  43586. if (pointA === null) {
  43587. pointA = cacheSoloPointer;
  43588. }
  43589. else if (pointB === null) {
  43590. pointB = cacheSoloPointer;
  43591. }
  43592. if (!noPreventDefault) {
  43593. evt.preventDefault();
  43594. element.focus();
  43595. }
  43596. }
  43597. else if (p.type === BABYLON.PointerEventTypes.POINTERDOUBLETAP) {
  43598. _this.camera.restoreState();
  43599. }
  43600. else if (p.type === BABYLON.PointerEventTypes.POINTERUP && srcElement) {
  43601. try {
  43602. srcElement.releasePointerCapture(evt.pointerId);
  43603. }
  43604. catch (e) {
  43605. //Nothing to do with the error.
  43606. }
  43607. cacheSoloPointer = null;
  43608. previousPinchSquaredDistance = 0;
  43609. previousMultiTouchPanPosition.isPaning = false;
  43610. previousMultiTouchPanPosition.isPinching = false;
  43611. twoFingerActivityCount = 0;
  43612. initialDistance = 0;
  43613. if (!isTouch) {
  43614. pointB = null; // Mouse and pen are mono pointer
  43615. }
  43616. //would be better to use pointers.remove(evt.pointerId) for multitouch gestures,
  43617. //but emptying completly pointers collection is required to fix a bug on iPhone :
  43618. //when changing orientation while pinching camera, one pointer stay pressed forever if we don't release all pointers
  43619. //will be ok to put back pointers.remove(evt.pointerId); when iPhone bug corrected
  43620. if (engine.badOS) {
  43621. pointA = pointB = null;
  43622. }
  43623. else {
  43624. //only remove the impacted pointer in case of multitouch allowing on most
  43625. //platforms switching from rotate to zoom and pan seamlessly.
  43626. if (pointB && pointA && pointA.pointerId == evt.pointerId) {
  43627. pointA = pointB;
  43628. pointB = null;
  43629. cacheSoloPointer = { x: pointA.x, y: pointA.y, pointerId: pointA.pointerId, type: evt.pointerType };
  43630. }
  43631. else if (pointA && pointB && pointB.pointerId == evt.pointerId) {
  43632. pointB = null;
  43633. cacheSoloPointer = { x: pointA.x, y: pointA.y, pointerId: pointA.pointerId, type: evt.pointerType };
  43634. }
  43635. else {
  43636. pointA = pointB = null;
  43637. }
  43638. }
  43639. if (!noPreventDefault) {
  43640. evt.preventDefault();
  43641. }
  43642. }
  43643. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  43644. if (!noPreventDefault) {
  43645. evt.preventDefault();
  43646. }
  43647. // One button down
  43648. if (pointA && pointB === null && cacheSoloPointer) {
  43649. if (_this.panningSensibility !== 0 &&
  43650. ((evt.ctrlKey && _this.camera._useCtrlForPanning) || _this._isPanClick)) {
  43651. _this.camera.inertialPanningX += -(evt.clientX - cacheSoloPointer.x) / _this.panningSensibility;
  43652. _this.camera.inertialPanningY += (evt.clientY - cacheSoloPointer.y) / _this.panningSensibility;
  43653. }
  43654. else {
  43655. var offsetX = evt.clientX - cacheSoloPointer.x;
  43656. var offsetY = evt.clientY - cacheSoloPointer.y;
  43657. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  43658. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  43659. }
  43660. cacheSoloPointer.x = evt.clientX;
  43661. cacheSoloPointer.y = evt.clientY;
  43662. }
  43663. else if (pointA && pointB) {
  43664. //if (noPreventDefault) { evt.preventDefault(); } //if pinch gesture, could be useful to force preventDefault to avoid html page scroll/zoom in some mobile browsers
  43665. var ed = (pointA.pointerId === evt.pointerId) ? pointA : pointB;
  43666. ed.x = evt.clientX;
  43667. ed.y = evt.clientY;
  43668. var direction = _this.pinchInwards ? 1 : -1;
  43669. var distX = pointA.x - pointB.x;
  43670. var distY = pointA.y - pointB.y;
  43671. var pinchSquaredDistance = (distX * distX) + (distY * distY);
  43672. var pinchDistance = Math.sqrt(pinchSquaredDistance);
  43673. if (previousPinchSquaredDistance === 0) {
  43674. initialDistance = pinchDistance;
  43675. previousPinchSquaredDistance = pinchSquaredDistance;
  43676. previousMultiTouchPanPosition.x = (pointA.x + pointB.x) / 2;
  43677. previousMultiTouchPanPosition.y = (pointA.y + pointB.y) / 2;
  43678. return;
  43679. }
  43680. if (_this.multiTouchPanAndZoom) {
  43681. if (_this.pinchDeltaPercentage) {
  43682. _this.camera.inertialRadiusOffset += ((pinchSquaredDistance - previousPinchSquaredDistance) * 0.001) * _this.camera.radius * _this.pinchDeltaPercentage;
  43683. }
  43684. else {
  43685. _this.camera.inertialRadiusOffset += (pinchSquaredDistance - previousPinchSquaredDistance) /
  43686. (_this.pinchPrecision *
  43687. ((_this.angularSensibilityX + _this.angularSensibilityY) / 2) *
  43688. direction);
  43689. }
  43690. if (_this.panningSensibility !== 0) {
  43691. var pointersCenterX = (pointA.x + pointB.x) / 2;
  43692. var pointersCenterY = (pointA.y + pointB.y) / 2;
  43693. var pointersCenterDistX = pointersCenterX - previousMultiTouchPanPosition.x;
  43694. var pointersCenterDistY = pointersCenterY - previousMultiTouchPanPosition.y;
  43695. previousMultiTouchPanPosition.x = pointersCenterX;
  43696. previousMultiTouchPanPosition.y = pointersCenterY;
  43697. _this.camera.inertialPanningX += -(pointersCenterDistX) / (_this.panningSensibility);
  43698. _this.camera.inertialPanningY += (pointersCenterDistY) / (_this.panningSensibility);
  43699. }
  43700. }
  43701. else {
  43702. twoFingerActivityCount++;
  43703. if (previousMultiTouchPanPosition.isPinching || (twoFingerActivityCount < 20 && Math.abs(pinchDistance - initialDistance) > _this.camera.pinchToPanMaxDistance)) {
  43704. if (_this.pinchDeltaPercentage) {
  43705. _this.camera.inertialRadiusOffset += ((pinchSquaredDistance - previousPinchSquaredDistance) * 0.001) * _this.camera.radius * _this.pinchDeltaPercentage;
  43706. }
  43707. else {
  43708. _this.camera.inertialRadiusOffset += (pinchSquaredDistance - previousPinchSquaredDistance) /
  43709. (_this.pinchPrecision *
  43710. ((_this.angularSensibilityX + _this.angularSensibilityY) / 2) *
  43711. direction);
  43712. }
  43713. previousMultiTouchPanPosition.isPaning = false;
  43714. previousMultiTouchPanPosition.isPinching = true;
  43715. }
  43716. else {
  43717. if (cacheSoloPointer && cacheSoloPointer.pointerId === ed.pointerId && _this.panningSensibility !== 0 && _this.multiTouchPanning) {
  43718. if (!previousMultiTouchPanPosition.isPaning) {
  43719. previousMultiTouchPanPosition.isPaning = true;
  43720. previousMultiTouchPanPosition.isPinching = false;
  43721. previousMultiTouchPanPosition.x = ed.x;
  43722. previousMultiTouchPanPosition.y = ed.y;
  43723. return;
  43724. }
  43725. _this.camera.inertialPanningX += -(ed.x - previousMultiTouchPanPosition.x) / (_this.panningSensibility);
  43726. _this.camera.inertialPanningY += (ed.y - previousMultiTouchPanPosition.y) / (_this.panningSensibility);
  43727. }
  43728. }
  43729. if (cacheSoloPointer && cacheSoloPointer.pointerId === evt.pointerId) {
  43730. previousMultiTouchPanPosition.x = ed.x;
  43731. previousMultiTouchPanPosition.y = ed.y;
  43732. }
  43733. }
  43734. previousPinchSquaredDistance = pinchSquaredDistance;
  43735. }
  43736. }
  43737. };
  43738. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE | BABYLON.PointerEventTypes._POINTERDOUBLETAP);
  43739. this._onContextMenu = function (evt) {
  43740. evt.preventDefault();
  43741. };
  43742. if (!this.camera._useCtrlForPanning) {
  43743. element.addEventListener("contextmenu", this._onContextMenu, false);
  43744. }
  43745. this._onLostFocus = function () {
  43746. //this._keys = [];
  43747. pointA = pointB = null;
  43748. previousPinchSquaredDistance = 0;
  43749. previousMultiTouchPanPosition.isPaning = false;
  43750. previousMultiTouchPanPosition.isPinching = false;
  43751. twoFingerActivityCount = 0;
  43752. cacheSoloPointer = null;
  43753. initialDistance = 0;
  43754. };
  43755. this._onMouseMove = function (evt) {
  43756. if (!engine.isPointerLock) {
  43757. return;
  43758. }
  43759. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  43760. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  43761. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  43762. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  43763. if (!noPreventDefault) {
  43764. evt.preventDefault();
  43765. }
  43766. };
  43767. this._onGestureStart = function (e) {
  43768. if (window.MSGesture === undefined) {
  43769. return;
  43770. }
  43771. if (!_this._MSGestureHandler) {
  43772. _this._MSGestureHandler = new MSGesture();
  43773. _this._MSGestureHandler.target = element;
  43774. }
  43775. _this._MSGestureHandler.addPointer(e.pointerId);
  43776. };
  43777. this._onGesture = function (e) {
  43778. _this.camera.radius *= e.scale;
  43779. if (e.preventDefault) {
  43780. if (!noPreventDefault) {
  43781. e.stopPropagation();
  43782. e.preventDefault();
  43783. }
  43784. }
  43785. };
  43786. element.addEventListener("mousemove", this._onMouseMove, false);
  43787. element.addEventListener("MSPointerDown", this._onGestureStart, false);
  43788. element.addEventListener("MSGestureChange", this._onGesture, false);
  43789. BABYLON.Tools.RegisterTopRootEvents([
  43790. { name: "blur", handler: this._onLostFocus }
  43791. ]);
  43792. };
  43793. ArcRotateCameraPointersInput.prototype.detachControl = function (element) {
  43794. if (this._onLostFocus) {
  43795. BABYLON.Tools.UnregisterTopRootEvents([
  43796. { name: "blur", handler: this._onLostFocus }
  43797. ]);
  43798. }
  43799. if (element && this._observer) {
  43800. this.camera.getScene().onPointerObservable.remove(this._observer);
  43801. this._observer = null;
  43802. if (this._onContextMenu) {
  43803. element.removeEventListener("contextmenu", this._onContextMenu);
  43804. }
  43805. if (this._onMouseMove) {
  43806. element.removeEventListener("mousemove", this._onMouseMove);
  43807. }
  43808. if (this._onGestureStart) {
  43809. element.removeEventListener("MSPointerDown", this._onGestureStart);
  43810. }
  43811. if (this._onGesture) {
  43812. element.removeEventListener("MSGestureChange", this._onGesture);
  43813. }
  43814. this._isPanClick = false;
  43815. this.pinchInwards = true;
  43816. this._onMouseMove = null;
  43817. this._onGestureStart = null;
  43818. this._onGesture = null;
  43819. this._MSGestureHandler = null;
  43820. this._onLostFocus = null;
  43821. this._onContextMenu = null;
  43822. }
  43823. };
  43824. ArcRotateCameraPointersInput.prototype.getClassName = function () {
  43825. return "ArcRotateCameraPointersInput";
  43826. };
  43827. ArcRotateCameraPointersInput.prototype.getSimpleName = function () {
  43828. return "pointers";
  43829. };
  43830. __decorate([
  43831. BABYLON.serialize()
  43832. ], ArcRotateCameraPointersInput.prototype, "buttons", void 0);
  43833. __decorate([
  43834. BABYLON.serialize()
  43835. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityX", void 0);
  43836. __decorate([
  43837. BABYLON.serialize()
  43838. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityY", void 0);
  43839. __decorate([
  43840. BABYLON.serialize()
  43841. ], ArcRotateCameraPointersInput.prototype, "pinchPrecision", void 0);
  43842. __decorate([
  43843. BABYLON.serialize()
  43844. ], ArcRotateCameraPointersInput.prototype, "pinchDeltaPercentage", void 0);
  43845. __decorate([
  43846. BABYLON.serialize()
  43847. ], ArcRotateCameraPointersInput.prototype, "panningSensibility", void 0);
  43848. __decorate([
  43849. BABYLON.serialize()
  43850. ], ArcRotateCameraPointersInput.prototype, "multiTouchPanning", void 0);
  43851. __decorate([
  43852. BABYLON.serialize()
  43853. ], ArcRotateCameraPointersInput.prototype, "multiTouchPanAndZoom", void 0);
  43854. return ArcRotateCameraPointersInput;
  43855. }());
  43856. BABYLON.ArcRotateCameraPointersInput = ArcRotateCameraPointersInput;
  43857. BABYLON.CameraInputTypes["ArcRotateCameraPointersInput"] = ArcRotateCameraPointersInput;
  43858. })(BABYLON || (BABYLON = {}));
  43859. //# sourceMappingURL=babylon.arcRotateCameraPointersInput.js.map
  43860. var BABYLON;
  43861. (function (BABYLON) {
  43862. var ArcRotateCameraInputsManager = /** @class */ (function (_super) {
  43863. __extends(ArcRotateCameraInputsManager, _super);
  43864. function ArcRotateCameraInputsManager(camera) {
  43865. return _super.call(this, camera) || this;
  43866. }
  43867. ArcRotateCameraInputsManager.prototype.addMouseWheel = function () {
  43868. this.add(new BABYLON.ArcRotateCameraMouseWheelInput());
  43869. return this;
  43870. };
  43871. ArcRotateCameraInputsManager.prototype.addPointers = function () {
  43872. this.add(new BABYLON.ArcRotateCameraPointersInput());
  43873. return this;
  43874. };
  43875. ArcRotateCameraInputsManager.prototype.addKeyboard = function () {
  43876. this.add(new BABYLON.ArcRotateCameraKeyboardMoveInput());
  43877. return this;
  43878. };
  43879. ArcRotateCameraInputsManager.prototype.addGamepad = function () {
  43880. this.add(new BABYLON.ArcRotateCameraGamepadInput());
  43881. return this;
  43882. };
  43883. ArcRotateCameraInputsManager.prototype.addVRDeviceOrientation = function () {
  43884. this.add(new BABYLON.ArcRotateCameraVRDeviceOrientationInput());
  43885. return this;
  43886. };
  43887. return ArcRotateCameraInputsManager;
  43888. }(BABYLON.CameraInputsManager));
  43889. BABYLON.ArcRotateCameraInputsManager = ArcRotateCameraInputsManager;
  43890. })(BABYLON || (BABYLON = {}));
  43891. //# sourceMappingURL=babylon.arcRotateCameraInputsManager.js.map
  43892. var BABYLON;
  43893. (function (BABYLON) {
  43894. var ArcRotateCamera = /** @class */ (function (_super) {
  43895. __extends(ArcRotateCamera, _super);
  43896. function ArcRotateCamera(name, alpha, beta, radius, target, scene) {
  43897. var _this = _super.call(this, name, BABYLON.Vector3.Zero(), scene) || this;
  43898. _this.inertialAlphaOffset = 0;
  43899. _this.inertialBetaOffset = 0;
  43900. _this.inertialRadiusOffset = 0;
  43901. _this.lowerAlphaLimit = null;
  43902. _this.upperAlphaLimit = null;
  43903. _this.lowerBetaLimit = 0.01;
  43904. _this.upperBetaLimit = Math.PI;
  43905. _this.lowerRadiusLimit = null;
  43906. _this.upperRadiusLimit = null;
  43907. _this.inertialPanningX = 0;
  43908. _this.inertialPanningY = 0;
  43909. _this.pinchToPanMaxDistance = 20;
  43910. _this.panningDistanceLimit = null;
  43911. _this.panningOriginTarget = BABYLON.Vector3.Zero();
  43912. _this.panningInertia = 0.9;
  43913. //-- end properties for backward compatibility for inputs
  43914. _this.zoomOnFactor = 1;
  43915. _this.targetScreenOffset = BABYLON.Vector2.Zero();
  43916. _this.allowUpsideDown = true;
  43917. _this._viewMatrix = new BABYLON.Matrix();
  43918. // Panning
  43919. _this.panningAxis = new BABYLON.Vector3(1, 1, 0);
  43920. _this.onMeshTargetChangedObservable = new BABYLON.Observable();
  43921. _this.checkCollisions = false;
  43922. _this.collisionRadius = new BABYLON.Vector3(0.5, 0.5, 0.5);
  43923. _this._previousPosition = BABYLON.Vector3.Zero();
  43924. _this._collisionVelocity = BABYLON.Vector3.Zero();
  43925. _this._newPosition = BABYLON.Vector3.Zero();
  43926. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  43927. if (collidedMesh === void 0) { collidedMesh = null; }
  43928. if (_this.getScene().workerCollisions && _this.checkCollisions) {
  43929. newPosition.multiplyInPlace(_this._collider._radius);
  43930. }
  43931. if (!collidedMesh) {
  43932. _this._previousPosition.copyFrom(_this.position);
  43933. }
  43934. else {
  43935. _this.setPosition(newPosition);
  43936. if (_this.onCollide) {
  43937. _this.onCollide(collidedMesh);
  43938. }
  43939. }
  43940. // Recompute because of constraints
  43941. var cosa = Math.cos(_this.alpha);
  43942. var sina = Math.sin(_this.alpha);
  43943. var cosb = Math.cos(_this.beta);
  43944. var sinb = Math.sin(_this.beta);
  43945. if (sinb === 0) {
  43946. sinb = 0.0001;
  43947. }
  43948. var target = _this._getTargetPosition();
  43949. target.addToRef(new BABYLON.Vector3(_this.radius * cosa * sinb, _this.radius * cosb, _this.radius * sina * sinb), _this._newPosition);
  43950. _this.position.copyFrom(_this._newPosition);
  43951. var up = _this.upVector;
  43952. if (_this.allowUpsideDown && _this.beta < 0) {
  43953. up = up.clone();
  43954. up = up.negate();
  43955. }
  43956. BABYLON.Matrix.LookAtLHToRef(_this.position, target, up, _this._viewMatrix);
  43957. _this._viewMatrix.m[12] += _this.targetScreenOffset.x;
  43958. _this._viewMatrix.m[13] += _this.targetScreenOffset.y;
  43959. _this._collisionTriggered = false;
  43960. };
  43961. _this._target = BABYLON.Vector3.Zero();
  43962. if (target) {
  43963. _this.setTarget(target);
  43964. }
  43965. _this.alpha = alpha;
  43966. _this.beta = beta;
  43967. _this.radius = radius;
  43968. _this.getViewMatrix();
  43969. _this.inputs = new BABYLON.ArcRotateCameraInputsManager(_this);
  43970. _this.inputs.addKeyboard().addMouseWheel().addPointers();
  43971. return _this;
  43972. }
  43973. Object.defineProperty(ArcRotateCamera.prototype, "target", {
  43974. get: function () {
  43975. return this._target;
  43976. },
  43977. set: function (value) {
  43978. this.setTarget(value);
  43979. },
  43980. enumerable: true,
  43981. configurable: true
  43982. });
  43983. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityX", {
  43984. //-- begin properties for backward compatibility for inputs
  43985. get: function () {
  43986. var pointers = this.inputs.attached["pointers"];
  43987. if (pointers)
  43988. return pointers.angularSensibilityX;
  43989. return 0;
  43990. },
  43991. set: function (value) {
  43992. var pointers = this.inputs.attached["pointers"];
  43993. if (pointers) {
  43994. pointers.angularSensibilityX = value;
  43995. }
  43996. },
  43997. enumerable: true,
  43998. configurable: true
  43999. });
  44000. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityY", {
  44001. get: function () {
  44002. var pointers = this.inputs.attached["pointers"];
  44003. if (pointers)
  44004. return pointers.angularSensibilityY;
  44005. return 0;
  44006. },
  44007. set: function (value) {
  44008. var pointers = this.inputs.attached["pointers"];
  44009. if (pointers) {
  44010. pointers.angularSensibilityY = value;
  44011. }
  44012. },
  44013. enumerable: true,
  44014. configurable: true
  44015. });
  44016. Object.defineProperty(ArcRotateCamera.prototype, "pinchPrecision", {
  44017. get: function () {
  44018. var pointers = this.inputs.attached["pointers"];
  44019. if (pointers)
  44020. return pointers.pinchPrecision;
  44021. return 0;
  44022. },
  44023. set: function (value) {
  44024. var pointers = this.inputs.attached["pointers"];
  44025. if (pointers) {
  44026. pointers.pinchPrecision = value;
  44027. }
  44028. },
  44029. enumerable: true,
  44030. configurable: true
  44031. });
  44032. Object.defineProperty(ArcRotateCamera.prototype, "pinchDeltaPercentage", {
  44033. get: function () {
  44034. var pointers = this.inputs.attached["pointers"];
  44035. if (pointers)
  44036. return pointers.pinchDeltaPercentage;
  44037. return 0;
  44038. },
  44039. set: function (value) {
  44040. var pointers = this.inputs.attached["pointers"];
  44041. if (pointers) {
  44042. pointers.pinchDeltaPercentage = value;
  44043. }
  44044. },
  44045. enumerable: true,
  44046. configurable: true
  44047. });
  44048. Object.defineProperty(ArcRotateCamera.prototype, "panningSensibility", {
  44049. get: function () {
  44050. var pointers = this.inputs.attached["pointers"];
  44051. if (pointers)
  44052. return pointers.panningSensibility;
  44053. return 0;
  44054. },
  44055. set: function (value) {
  44056. var pointers = this.inputs.attached["pointers"];
  44057. if (pointers) {
  44058. pointers.panningSensibility = value;
  44059. }
  44060. },
  44061. enumerable: true,
  44062. configurable: true
  44063. });
  44064. Object.defineProperty(ArcRotateCamera.prototype, "keysUp", {
  44065. get: function () {
  44066. var keyboard = this.inputs.attached["keyboard"];
  44067. if (keyboard)
  44068. return keyboard.keysUp;
  44069. return [];
  44070. },
  44071. set: function (value) {
  44072. var keyboard = this.inputs.attached["keyboard"];
  44073. if (keyboard)
  44074. keyboard.keysUp = value;
  44075. },
  44076. enumerable: true,
  44077. configurable: true
  44078. });
  44079. Object.defineProperty(ArcRotateCamera.prototype, "keysDown", {
  44080. get: function () {
  44081. var keyboard = this.inputs.attached["keyboard"];
  44082. if (keyboard)
  44083. return keyboard.keysDown;
  44084. return [];
  44085. },
  44086. set: function (value) {
  44087. var keyboard = this.inputs.attached["keyboard"];
  44088. if (keyboard)
  44089. keyboard.keysDown = value;
  44090. },
  44091. enumerable: true,
  44092. configurable: true
  44093. });
  44094. Object.defineProperty(ArcRotateCamera.prototype, "keysLeft", {
  44095. get: function () {
  44096. var keyboard = this.inputs.attached["keyboard"];
  44097. if (keyboard)
  44098. return keyboard.keysLeft;
  44099. return [];
  44100. },
  44101. set: function (value) {
  44102. var keyboard = this.inputs.attached["keyboard"];
  44103. if (keyboard)
  44104. keyboard.keysLeft = value;
  44105. },
  44106. enumerable: true,
  44107. configurable: true
  44108. });
  44109. Object.defineProperty(ArcRotateCamera.prototype, "keysRight", {
  44110. get: function () {
  44111. var keyboard = this.inputs.attached["keyboard"];
  44112. if (keyboard)
  44113. return keyboard.keysRight;
  44114. return [];
  44115. },
  44116. set: function (value) {
  44117. var keyboard = this.inputs.attached["keyboard"];
  44118. if (keyboard)
  44119. keyboard.keysRight = value;
  44120. },
  44121. enumerable: true,
  44122. configurable: true
  44123. });
  44124. Object.defineProperty(ArcRotateCamera.prototype, "wheelPrecision", {
  44125. get: function () {
  44126. var mousewheel = this.inputs.attached["mousewheel"];
  44127. if (mousewheel)
  44128. return mousewheel.wheelPrecision;
  44129. return 0;
  44130. },
  44131. set: function (value) {
  44132. var mousewheel = this.inputs.attached["mousewheel"];
  44133. if (mousewheel)
  44134. mousewheel.wheelPrecision = value;
  44135. },
  44136. enumerable: true,
  44137. configurable: true
  44138. });
  44139. Object.defineProperty(ArcRotateCamera.prototype, "wheelDeltaPercentage", {
  44140. get: function () {
  44141. var mousewheel = this.inputs.attached["mousewheel"];
  44142. if (mousewheel)
  44143. return mousewheel.wheelDeltaPercentage;
  44144. return 0;
  44145. },
  44146. set: function (value) {
  44147. var mousewheel = this.inputs.attached["mousewheel"];
  44148. if (mousewheel)
  44149. mousewheel.wheelDeltaPercentage = value;
  44150. },
  44151. enumerable: true,
  44152. configurable: true
  44153. });
  44154. Object.defineProperty(ArcRotateCamera.prototype, "bouncingBehavior", {
  44155. get: function () {
  44156. return this._bouncingBehavior;
  44157. },
  44158. enumerable: true,
  44159. configurable: true
  44160. });
  44161. Object.defineProperty(ArcRotateCamera.prototype, "useBouncingBehavior", {
  44162. get: function () {
  44163. return this._bouncingBehavior != null;
  44164. },
  44165. set: function (value) {
  44166. if (value === this.useBouncingBehavior) {
  44167. return;
  44168. }
  44169. if (value) {
  44170. this._bouncingBehavior = new BABYLON.BouncingBehavior();
  44171. this.addBehavior(this._bouncingBehavior);
  44172. }
  44173. else if (this._bouncingBehavior) {
  44174. this.removeBehavior(this._bouncingBehavior);
  44175. this._bouncingBehavior = null;
  44176. }
  44177. },
  44178. enumerable: true,
  44179. configurable: true
  44180. });
  44181. Object.defineProperty(ArcRotateCamera.prototype, "framingBehavior", {
  44182. get: function () {
  44183. return this._framingBehavior;
  44184. },
  44185. enumerable: true,
  44186. configurable: true
  44187. });
  44188. Object.defineProperty(ArcRotateCamera.prototype, "useFramingBehavior", {
  44189. get: function () {
  44190. return this._framingBehavior != null;
  44191. },
  44192. set: function (value) {
  44193. if (value === this.useFramingBehavior) {
  44194. return;
  44195. }
  44196. if (value) {
  44197. this._framingBehavior = new BABYLON.FramingBehavior();
  44198. this.addBehavior(this._framingBehavior);
  44199. }
  44200. else if (this._framingBehavior) {
  44201. this.removeBehavior(this._framingBehavior);
  44202. this._framingBehavior = null;
  44203. }
  44204. },
  44205. enumerable: true,
  44206. configurable: true
  44207. });
  44208. Object.defineProperty(ArcRotateCamera.prototype, "autoRotationBehavior", {
  44209. get: function () {
  44210. return this._autoRotationBehavior;
  44211. },
  44212. enumerable: true,
  44213. configurable: true
  44214. });
  44215. Object.defineProperty(ArcRotateCamera.prototype, "useAutoRotationBehavior", {
  44216. get: function () {
  44217. return this._autoRotationBehavior != null;
  44218. },
  44219. set: function (value) {
  44220. if (value === this.useAutoRotationBehavior) {
  44221. return;
  44222. }
  44223. if (value) {
  44224. this._autoRotationBehavior = new BABYLON.AutoRotationBehavior();
  44225. this.addBehavior(this._autoRotationBehavior);
  44226. }
  44227. else if (this._autoRotationBehavior) {
  44228. this.removeBehavior(this._autoRotationBehavior);
  44229. this._autoRotationBehavior = null;
  44230. }
  44231. },
  44232. enumerable: true,
  44233. configurable: true
  44234. });
  44235. // Cache
  44236. ArcRotateCamera.prototype._initCache = function () {
  44237. _super.prototype._initCache.call(this);
  44238. this._cache._target = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  44239. this._cache.alpha = undefined;
  44240. this._cache.beta = undefined;
  44241. this._cache.radius = undefined;
  44242. this._cache.targetScreenOffset = BABYLON.Vector2.Zero();
  44243. };
  44244. ArcRotateCamera.prototype._updateCache = function (ignoreParentClass) {
  44245. if (!ignoreParentClass) {
  44246. _super.prototype._updateCache.call(this);
  44247. }
  44248. this._cache._target.copyFrom(this._getTargetPosition());
  44249. this._cache.alpha = this.alpha;
  44250. this._cache.beta = this.beta;
  44251. this._cache.radius = this.radius;
  44252. this._cache.targetScreenOffset.copyFrom(this.targetScreenOffset);
  44253. };
  44254. ArcRotateCamera.prototype._getTargetPosition = function () {
  44255. if (this._targetHost && this._targetHost.getAbsolutePosition) {
  44256. var pos = this._targetHost.getAbsolutePosition();
  44257. if (this._targetBoundingCenter) {
  44258. pos.addToRef(this._targetBoundingCenter, this._target);
  44259. }
  44260. else {
  44261. this._target.copyFrom(pos);
  44262. }
  44263. }
  44264. var lockedTargetPosition = this._getLockedTargetPosition();
  44265. if (lockedTargetPosition) {
  44266. return lockedTargetPosition;
  44267. }
  44268. return this._target;
  44269. };
  44270. ArcRotateCamera.prototype.storeState = function () {
  44271. this._storedAlpha = this.alpha;
  44272. this._storedBeta = this.beta;
  44273. this._storedRadius = this.radius;
  44274. this._storedTarget = this._getTargetPosition().clone();
  44275. return _super.prototype.storeState.call(this);
  44276. };
  44277. /**
  44278. * Restored camera state. You must call storeState() first
  44279. */
  44280. ArcRotateCamera.prototype._restoreStateValues = function () {
  44281. if (!_super.prototype._restoreStateValues.call(this)) {
  44282. return false;
  44283. }
  44284. this.alpha = this._storedAlpha;
  44285. this.beta = this._storedBeta;
  44286. this.radius = this._storedRadius;
  44287. this.setTarget(this._storedTarget.clone());
  44288. this.inertialAlphaOffset = 0;
  44289. this.inertialBetaOffset = 0;
  44290. this.inertialRadiusOffset = 0;
  44291. this.inertialPanningX = 0;
  44292. this.inertialPanningY = 0;
  44293. return true;
  44294. };
  44295. // Synchronized
  44296. ArcRotateCamera.prototype._isSynchronizedViewMatrix = function () {
  44297. if (!_super.prototype._isSynchronizedViewMatrix.call(this))
  44298. return false;
  44299. return this._cache._target.equals(this._getTargetPosition())
  44300. && this._cache.alpha === this.alpha
  44301. && this._cache.beta === this.beta
  44302. && this._cache.radius === this.radius
  44303. && this._cache.targetScreenOffset.equals(this.targetScreenOffset);
  44304. };
  44305. // Methods
  44306. ArcRotateCamera.prototype.attachControl = function (element, noPreventDefault, useCtrlForPanning, panningMouseButton) {
  44307. var _this = this;
  44308. if (useCtrlForPanning === void 0) { useCtrlForPanning = true; }
  44309. if (panningMouseButton === void 0) { panningMouseButton = 2; }
  44310. this._useCtrlForPanning = useCtrlForPanning;
  44311. this._panningMouseButton = panningMouseButton;
  44312. this.inputs.attachElement(element, noPreventDefault);
  44313. this._reset = function () {
  44314. _this.inertialAlphaOffset = 0;
  44315. _this.inertialBetaOffset = 0;
  44316. _this.inertialRadiusOffset = 0;
  44317. _this.inertialPanningX = 0;
  44318. _this.inertialPanningY = 0;
  44319. };
  44320. };
  44321. ArcRotateCamera.prototype.detachControl = function (element) {
  44322. this.inputs.detachElement(element);
  44323. if (this._reset) {
  44324. this._reset();
  44325. }
  44326. };
  44327. ArcRotateCamera.prototype._checkInputs = function () {
  44328. //if (async) collision inspection was triggered, don't update the camera's position - until the collision callback was called.
  44329. if (this._collisionTriggered) {
  44330. return;
  44331. }
  44332. this.inputs.checkInputs();
  44333. // Inertia
  44334. if (this.inertialAlphaOffset !== 0 || this.inertialBetaOffset !== 0 || this.inertialRadiusOffset !== 0) {
  44335. if (this.getScene().useRightHandedSystem) {
  44336. this.alpha -= this.beta <= 0 ? -this.inertialAlphaOffset : this.inertialAlphaOffset;
  44337. }
  44338. else {
  44339. this.alpha += this.beta <= 0 ? -this.inertialAlphaOffset : this.inertialAlphaOffset;
  44340. }
  44341. this.beta += this.inertialBetaOffset;
  44342. this.radius -= this.inertialRadiusOffset;
  44343. this.inertialAlphaOffset *= this.inertia;
  44344. this.inertialBetaOffset *= this.inertia;
  44345. this.inertialRadiusOffset *= this.inertia;
  44346. if (Math.abs(this.inertialAlphaOffset) < BABYLON.Epsilon)
  44347. this.inertialAlphaOffset = 0;
  44348. if (Math.abs(this.inertialBetaOffset) < BABYLON.Epsilon)
  44349. this.inertialBetaOffset = 0;
  44350. if (Math.abs(this.inertialRadiusOffset) < this.speed * BABYLON.Epsilon)
  44351. this.inertialRadiusOffset = 0;
  44352. }
  44353. // Panning inertia
  44354. if (this.inertialPanningX !== 0 || this.inertialPanningY !== 0) {
  44355. if (!this._localDirection) {
  44356. this._localDirection = BABYLON.Vector3.Zero();
  44357. this._transformedDirection = BABYLON.Vector3.Zero();
  44358. }
  44359. this._localDirection.copyFromFloats(this.inertialPanningX, this.inertialPanningY, this.inertialPanningY);
  44360. this._localDirection.multiplyInPlace(this.panningAxis);
  44361. this._viewMatrix.invertToRef(this._cameraTransformMatrix);
  44362. BABYLON.Vector3.TransformNormalToRef(this._localDirection, this._cameraTransformMatrix, this._transformedDirection);
  44363. //Eliminate y if map panning is enabled (panningAxis == 1,0,1)
  44364. if (!this.panningAxis.y) {
  44365. this._transformedDirection.y = 0;
  44366. }
  44367. if (!this._targetHost) {
  44368. if (this.panningDistanceLimit) {
  44369. this._transformedDirection.addInPlace(this._target);
  44370. var distanceSquared = BABYLON.Vector3.DistanceSquared(this._transformedDirection, this.panningOriginTarget);
  44371. if (distanceSquared <= (this.panningDistanceLimit * this.panningDistanceLimit)) {
  44372. this._target.copyFrom(this._transformedDirection);
  44373. }
  44374. }
  44375. else {
  44376. this._target.addInPlace(this._transformedDirection);
  44377. }
  44378. }
  44379. this.inertialPanningX *= this.panningInertia;
  44380. this.inertialPanningY *= this.panningInertia;
  44381. if (Math.abs(this.inertialPanningX) < this.speed * BABYLON.Epsilon)
  44382. this.inertialPanningX = 0;
  44383. if (Math.abs(this.inertialPanningY) < this.speed * BABYLON.Epsilon)
  44384. this.inertialPanningY = 0;
  44385. }
  44386. // Limits
  44387. this._checkLimits();
  44388. _super.prototype._checkInputs.call(this);
  44389. };
  44390. ArcRotateCamera.prototype._checkLimits = function () {
  44391. if (this.lowerBetaLimit === null || this.lowerBetaLimit === undefined) {
  44392. if (this.allowUpsideDown && this.beta > Math.PI) {
  44393. this.beta = this.beta - (2 * Math.PI);
  44394. }
  44395. }
  44396. else {
  44397. if (this.beta < this.lowerBetaLimit) {
  44398. this.beta = this.lowerBetaLimit;
  44399. }
  44400. }
  44401. if (this.upperBetaLimit === null || this.upperBetaLimit === undefined) {
  44402. if (this.allowUpsideDown && this.beta < -Math.PI) {
  44403. this.beta = this.beta + (2 * Math.PI);
  44404. }
  44405. }
  44406. else {
  44407. if (this.beta > this.upperBetaLimit) {
  44408. this.beta = this.upperBetaLimit;
  44409. }
  44410. }
  44411. if (this.lowerAlphaLimit && this.alpha < this.lowerAlphaLimit) {
  44412. this.alpha = this.lowerAlphaLimit;
  44413. }
  44414. if (this.upperAlphaLimit && this.alpha > this.upperAlphaLimit) {
  44415. this.alpha = this.upperAlphaLimit;
  44416. }
  44417. if (this.lowerRadiusLimit && this.radius < this.lowerRadiusLimit) {
  44418. this.radius = this.lowerRadiusLimit;
  44419. }
  44420. if (this.upperRadiusLimit && this.radius > this.upperRadiusLimit) {
  44421. this.radius = this.upperRadiusLimit;
  44422. }
  44423. };
  44424. ArcRotateCamera.prototype.rebuildAnglesAndRadius = function () {
  44425. var radiusv3 = this.position.subtract(this._getTargetPosition());
  44426. this.radius = radiusv3.length();
  44427. if (this.radius === 0) {
  44428. this.radius = 0.0001; // Just to avoid division by zero
  44429. }
  44430. // Alpha
  44431. this.alpha = Math.acos(radiusv3.x / Math.sqrt(Math.pow(radiusv3.x, 2) + Math.pow(radiusv3.z, 2)));
  44432. if (radiusv3.z < 0) {
  44433. this.alpha = 2 * Math.PI - this.alpha;
  44434. }
  44435. // Beta
  44436. this.beta = Math.acos(radiusv3.y / this.radius);
  44437. this._checkLimits();
  44438. };
  44439. ArcRotateCamera.prototype.setPosition = function (position) {
  44440. if (this.position.equals(position)) {
  44441. return;
  44442. }
  44443. this.position.copyFrom(position);
  44444. this.rebuildAnglesAndRadius();
  44445. };
  44446. ArcRotateCamera.prototype.setTarget = function (target, toBoundingCenter, allowSamePosition) {
  44447. if (toBoundingCenter === void 0) { toBoundingCenter = false; }
  44448. if (allowSamePosition === void 0) { allowSamePosition = false; }
  44449. if (target.getBoundingInfo) {
  44450. if (toBoundingCenter) {
  44451. this._targetBoundingCenter = target.getBoundingInfo().boundingBox.centerWorld.clone();
  44452. }
  44453. else {
  44454. this._targetBoundingCenter = null;
  44455. }
  44456. this._targetHost = target;
  44457. this._target = this._getTargetPosition();
  44458. this.onMeshTargetChangedObservable.notifyObservers(this._targetHost);
  44459. }
  44460. else {
  44461. var newTarget = target;
  44462. var currentTarget = this._getTargetPosition();
  44463. if (currentTarget && !allowSamePosition && currentTarget.equals(newTarget)) {
  44464. return;
  44465. }
  44466. this._targetHost = null;
  44467. this._target = newTarget;
  44468. this._targetBoundingCenter = null;
  44469. this.onMeshTargetChangedObservable.notifyObservers(null);
  44470. }
  44471. this.rebuildAnglesAndRadius();
  44472. };
  44473. ArcRotateCamera.prototype._getViewMatrix = function () {
  44474. // Compute
  44475. var cosa = Math.cos(this.alpha);
  44476. var sina = Math.sin(this.alpha);
  44477. var cosb = Math.cos(this.beta);
  44478. var sinb = Math.sin(this.beta);
  44479. if (sinb === 0) {
  44480. sinb = 0.0001;
  44481. }
  44482. var target = this._getTargetPosition();
  44483. target.addToRef(new BABYLON.Vector3(this.radius * cosa * sinb, this.radius * cosb, this.radius * sina * sinb), this._newPosition);
  44484. if (this.getScene().collisionsEnabled && this.checkCollisions) {
  44485. if (!this._collider) {
  44486. this._collider = new BABYLON.Collider();
  44487. }
  44488. this._collider._radius = this.collisionRadius;
  44489. this._newPosition.subtractToRef(this.position, this._collisionVelocity);
  44490. this._collisionTriggered = true;
  44491. this.getScene().collisionCoordinator.getNewPosition(this.position, this._collisionVelocity, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  44492. }
  44493. else {
  44494. this.position.copyFrom(this._newPosition);
  44495. var up = this.upVector;
  44496. if (this.allowUpsideDown && sinb < 0) {
  44497. up = up.clone();
  44498. up = up.negate();
  44499. }
  44500. if (this.getScene().useRightHandedSystem) {
  44501. BABYLON.Matrix.LookAtRHToRef(this.position, target, up, this._viewMatrix);
  44502. }
  44503. else {
  44504. BABYLON.Matrix.LookAtLHToRef(this.position, target, up, this._viewMatrix);
  44505. }
  44506. this._viewMatrix.m[12] += this.targetScreenOffset.x;
  44507. this._viewMatrix.m[13] += this.targetScreenOffset.y;
  44508. }
  44509. this._currentTarget = target;
  44510. return this._viewMatrix;
  44511. };
  44512. ArcRotateCamera.prototype.zoomOn = function (meshes, doNotUpdateMaxZ) {
  44513. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  44514. meshes = meshes || this.getScene().meshes;
  44515. var minMaxVector = BABYLON.Mesh.MinMax(meshes);
  44516. var distance = BABYLON.Vector3.Distance(minMaxVector.min, minMaxVector.max);
  44517. this.radius = distance * this.zoomOnFactor;
  44518. this.focusOn({ min: minMaxVector.min, max: minMaxVector.max, distance: distance }, doNotUpdateMaxZ);
  44519. };
  44520. ArcRotateCamera.prototype.focusOn = function (meshesOrMinMaxVectorAndDistance, doNotUpdateMaxZ) {
  44521. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  44522. var meshesOrMinMaxVector;
  44523. var distance;
  44524. if (meshesOrMinMaxVectorAndDistance.min === undefined) {
  44525. var meshes = meshesOrMinMaxVectorAndDistance || this.getScene().meshes;
  44526. meshesOrMinMaxVector = BABYLON.Mesh.MinMax(meshes);
  44527. distance = BABYLON.Vector3.Distance(meshesOrMinMaxVector.min, meshesOrMinMaxVector.max);
  44528. }
  44529. else {
  44530. var minMaxVectorAndDistance = meshesOrMinMaxVectorAndDistance;
  44531. meshesOrMinMaxVector = minMaxVectorAndDistance;
  44532. distance = minMaxVectorAndDistance.distance;
  44533. }
  44534. this._target = BABYLON.Mesh.Center(meshesOrMinMaxVector);
  44535. if (!doNotUpdateMaxZ) {
  44536. this.maxZ = distance * 2;
  44537. }
  44538. };
  44539. /**
  44540. * @override
  44541. * Override Camera.createRigCamera
  44542. */
  44543. ArcRotateCamera.prototype.createRigCamera = function (name, cameraIndex) {
  44544. var alphaShift = 0;
  44545. switch (this.cameraRigMode) {
  44546. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  44547. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  44548. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  44549. case BABYLON.Camera.RIG_MODE_VR:
  44550. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? 1 : -1);
  44551. break;
  44552. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  44553. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? -1 : 1);
  44554. break;
  44555. }
  44556. var rigCam = new ArcRotateCamera(name, this.alpha + alphaShift, this.beta, this.radius, this._target, this.getScene());
  44557. rigCam._cameraRigParams = {};
  44558. return rigCam;
  44559. };
  44560. /**
  44561. * @override
  44562. * Override Camera._updateRigCameras
  44563. */
  44564. ArcRotateCamera.prototype._updateRigCameras = function () {
  44565. var camLeft = this._rigCameras[0];
  44566. var camRight = this._rigCameras[1];
  44567. camLeft.beta = camRight.beta = this.beta;
  44568. camLeft.radius = camRight.radius = this.radius;
  44569. switch (this.cameraRigMode) {
  44570. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  44571. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  44572. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  44573. case BABYLON.Camera.RIG_MODE_VR:
  44574. camLeft.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  44575. camRight.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  44576. break;
  44577. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  44578. camLeft.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  44579. camRight.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  44580. break;
  44581. }
  44582. _super.prototype._updateRigCameras.call(this);
  44583. };
  44584. ArcRotateCamera.prototype.dispose = function () {
  44585. this.inputs.clear();
  44586. _super.prototype.dispose.call(this);
  44587. };
  44588. ArcRotateCamera.prototype.getClassName = function () {
  44589. return "ArcRotateCamera";
  44590. };
  44591. __decorate([
  44592. BABYLON.serialize()
  44593. ], ArcRotateCamera.prototype, "alpha", void 0);
  44594. __decorate([
  44595. BABYLON.serialize()
  44596. ], ArcRotateCamera.prototype, "beta", void 0);
  44597. __decorate([
  44598. BABYLON.serialize()
  44599. ], ArcRotateCamera.prototype, "radius", void 0);
  44600. __decorate([
  44601. BABYLON.serializeAsVector3("target")
  44602. ], ArcRotateCamera.prototype, "_target", void 0);
  44603. __decorate([
  44604. BABYLON.serialize()
  44605. ], ArcRotateCamera.prototype, "inertialAlphaOffset", void 0);
  44606. __decorate([
  44607. BABYLON.serialize()
  44608. ], ArcRotateCamera.prototype, "inertialBetaOffset", void 0);
  44609. __decorate([
  44610. BABYLON.serialize()
  44611. ], ArcRotateCamera.prototype, "inertialRadiusOffset", void 0);
  44612. __decorate([
  44613. BABYLON.serialize()
  44614. ], ArcRotateCamera.prototype, "lowerAlphaLimit", void 0);
  44615. __decorate([
  44616. BABYLON.serialize()
  44617. ], ArcRotateCamera.prototype, "upperAlphaLimit", void 0);
  44618. __decorate([
  44619. BABYLON.serialize()
  44620. ], ArcRotateCamera.prototype, "lowerBetaLimit", void 0);
  44621. __decorate([
  44622. BABYLON.serialize()
  44623. ], ArcRotateCamera.prototype, "upperBetaLimit", void 0);
  44624. __decorate([
  44625. BABYLON.serialize()
  44626. ], ArcRotateCamera.prototype, "lowerRadiusLimit", void 0);
  44627. __decorate([
  44628. BABYLON.serialize()
  44629. ], ArcRotateCamera.prototype, "upperRadiusLimit", void 0);
  44630. __decorate([
  44631. BABYLON.serialize()
  44632. ], ArcRotateCamera.prototype, "inertialPanningX", void 0);
  44633. __decorate([
  44634. BABYLON.serialize()
  44635. ], ArcRotateCamera.prototype, "inertialPanningY", void 0);
  44636. __decorate([
  44637. BABYLON.serialize()
  44638. ], ArcRotateCamera.prototype, "pinchToPanMaxDistance", void 0);
  44639. __decorate([
  44640. BABYLON.serialize()
  44641. ], ArcRotateCamera.prototype, "panningDistanceLimit", void 0);
  44642. __decorate([
  44643. BABYLON.serializeAsVector3()
  44644. ], ArcRotateCamera.prototype, "panningOriginTarget", void 0);
  44645. __decorate([
  44646. BABYLON.serialize()
  44647. ], ArcRotateCamera.prototype, "panningInertia", void 0);
  44648. __decorate([
  44649. BABYLON.serialize()
  44650. ], ArcRotateCamera.prototype, "zoomOnFactor", void 0);
  44651. __decorate([
  44652. BABYLON.serialize()
  44653. ], ArcRotateCamera.prototype, "allowUpsideDown", void 0);
  44654. return ArcRotateCamera;
  44655. }(BABYLON.TargetCamera));
  44656. BABYLON.ArcRotateCamera = ArcRotateCamera;
  44657. })(BABYLON || (BABYLON = {}));
  44658. //# sourceMappingURL=babylon.arcRotateCamera.js.map
  44659. var BABYLON;
  44660. (function (BABYLON) {
  44661. /**
  44662. * The HemisphericLight simulates the ambient environment light,
  44663. * so the passed direction is the light reflection direction, not the incoming direction.
  44664. */
  44665. var HemisphericLight = /** @class */ (function (_super) {
  44666. __extends(HemisphericLight, _super);
  44667. /**
  44668. * Creates a HemisphericLight object in the scene according to the passed direction (Vector3).
  44669. * The HemisphericLight simulates the ambient environment light, so the passed direction is the light reflection direction, not the incoming direction.
  44670. * The HemisphericLight can't cast shadows.
  44671. * Documentation : http://doc.babylonjs.com/tutorials/lights
  44672. * @param name The friendly name of the light
  44673. * @param direction The direction of the light reflection
  44674. * @param scene The scene the light belongs to
  44675. */
  44676. function HemisphericLight(name, direction, scene) {
  44677. var _this = _super.call(this, name, scene) || this;
  44678. /**
  44679. * The groundColor is the light in the opposite direction to the one specified during creation.
  44680. * 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.
  44681. */
  44682. _this.groundColor = new BABYLON.Color3(0.0, 0.0, 0.0);
  44683. _this.direction = direction || BABYLON.Vector3.Up();
  44684. return _this;
  44685. }
  44686. HemisphericLight.prototype._buildUniformLayout = function () {
  44687. this._uniformBuffer.addUniform("vLightData", 4);
  44688. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  44689. this._uniformBuffer.addUniform("vLightSpecular", 3);
  44690. this._uniformBuffer.addUniform("vLightGround", 3);
  44691. this._uniformBuffer.addUniform("shadowsInfo", 3);
  44692. this._uniformBuffer.addUniform("depthValues", 2);
  44693. this._uniformBuffer.create();
  44694. };
  44695. /**
  44696. * Returns the string "HemisphericLight".
  44697. * @return The class name
  44698. */
  44699. HemisphericLight.prototype.getClassName = function () {
  44700. return "HemisphericLight";
  44701. };
  44702. /**
  44703. * Sets the HemisphericLight direction towards the passed target (Vector3).
  44704. * Returns the updated direction.
  44705. * @param target The target the direction should point to
  44706. * @return The computed direction
  44707. */
  44708. HemisphericLight.prototype.setDirectionToTarget = function (target) {
  44709. this.direction = BABYLON.Vector3.Normalize(target.subtract(BABYLON.Vector3.Zero()));
  44710. return this.direction;
  44711. };
  44712. /**
  44713. * Returns the shadow generator associated to the light.
  44714. * @returns Always null for hemispheric lights because it does not support shadows.
  44715. */
  44716. HemisphericLight.prototype.getShadowGenerator = function () {
  44717. return null;
  44718. };
  44719. /**
  44720. * Sets the passed Effect object with the HemisphericLight normalized direction and color and the passed name (string).
  44721. * @param effect The effect to update
  44722. * @param lightIndex The index of the light in the effect to update
  44723. * @returns The hemispheric light
  44724. */
  44725. HemisphericLight.prototype.transferToEffect = function (effect, lightIndex) {
  44726. var normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  44727. this._uniformBuffer.updateFloat4("vLightData", normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, 0.0, lightIndex);
  44728. this._uniformBuffer.updateColor3("vLightGround", this.groundColor.scale(this.intensity), lightIndex);
  44729. return this;
  44730. };
  44731. /**
  44732. * @ignore internal use only.
  44733. */
  44734. HemisphericLight.prototype._getWorldMatrix = function () {
  44735. if (!this._worldMatrix) {
  44736. this._worldMatrix = BABYLON.Matrix.Identity();
  44737. }
  44738. return this._worldMatrix;
  44739. };
  44740. /**
  44741. * Returns the integer 3.
  44742. * @return The light Type id as a constant defines in Light.LIGHTTYPEID_x
  44743. */
  44744. HemisphericLight.prototype.getTypeID = function () {
  44745. return BABYLON.Light.LIGHTTYPEID_HEMISPHERICLIGHT;
  44746. };
  44747. __decorate([
  44748. BABYLON.serializeAsColor3()
  44749. ], HemisphericLight.prototype, "groundColor", void 0);
  44750. __decorate([
  44751. BABYLON.serializeAsVector3()
  44752. ], HemisphericLight.prototype, "direction", void 0);
  44753. return HemisphericLight;
  44754. }(BABYLON.Light));
  44755. BABYLON.HemisphericLight = HemisphericLight;
  44756. })(BABYLON || (BABYLON = {}));
  44757. //# sourceMappingURL=babylon.hemisphericLight.js.map
  44758. var BABYLON;
  44759. (function (BABYLON) {
  44760. /**
  44761. * Base implementation of @see IShadowLight
  44762. * It groups all the common behaviour in order to reduce dupplication and better follow the DRY pattern.
  44763. */
  44764. var ShadowLight = /** @class */ (function (_super) {
  44765. __extends(ShadowLight, _super);
  44766. function ShadowLight() {
  44767. var _this = _super !== null && _super.apply(this, arguments) || this;
  44768. _this._needProjectionMatrixCompute = true;
  44769. return _this;
  44770. }
  44771. ShadowLight.prototype._setPosition = function (value) {
  44772. this._position = value;
  44773. };
  44774. Object.defineProperty(ShadowLight.prototype, "position", {
  44775. /**
  44776. * Sets the position the shadow will be casted from. Also use as the light position for both
  44777. * point and spot lights.
  44778. */
  44779. get: function () {
  44780. return this._position;
  44781. },
  44782. /**
  44783. * Sets the position the shadow will be casted from. Also use as the light position for both
  44784. * point and spot lights.
  44785. */
  44786. set: function (value) {
  44787. this._setPosition(value);
  44788. },
  44789. enumerable: true,
  44790. configurable: true
  44791. });
  44792. ShadowLight.prototype._setDirection = function (value) {
  44793. this._direction = value;
  44794. };
  44795. Object.defineProperty(ShadowLight.prototype, "direction", {
  44796. /**
  44797. * In 2d mode (needCube being false), gets the direction used to cast the shadow.
  44798. * Also use as the light direction on spot and directional lights.
  44799. */
  44800. get: function () {
  44801. return this._direction;
  44802. },
  44803. /**
  44804. * In 2d mode (needCube being false), sets the direction used to cast the shadow.
  44805. * Also use as the light direction on spot and directional lights.
  44806. */
  44807. set: function (value) {
  44808. this._setDirection(value);
  44809. },
  44810. enumerable: true,
  44811. configurable: true
  44812. });
  44813. Object.defineProperty(ShadowLight.prototype, "shadowMinZ", {
  44814. /**
  44815. * Gets the shadow projection clipping minimum z value.
  44816. */
  44817. get: function () {
  44818. return this._shadowMinZ;
  44819. },
  44820. /**
  44821. * Sets the shadow projection clipping minimum z value.
  44822. */
  44823. set: function (value) {
  44824. this._shadowMinZ = value;
  44825. this.forceProjectionMatrixCompute();
  44826. },
  44827. enumerable: true,
  44828. configurable: true
  44829. });
  44830. Object.defineProperty(ShadowLight.prototype, "shadowMaxZ", {
  44831. /**
  44832. * Sets the shadow projection clipping maximum z value.
  44833. */
  44834. get: function () {
  44835. return this._shadowMaxZ;
  44836. },
  44837. /**
  44838. * Gets the shadow projection clipping maximum z value.
  44839. */
  44840. set: function (value) {
  44841. this._shadowMaxZ = value;
  44842. this.forceProjectionMatrixCompute();
  44843. },
  44844. enumerable: true,
  44845. configurable: true
  44846. });
  44847. /**
  44848. * Computes the transformed information (transformedPosition and transformedDirection in World space) of the current light
  44849. * @returns true if the information has been computed, false if it does not need to (no parenting)
  44850. */
  44851. ShadowLight.prototype.computeTransformedInformation = function () {
  44852. if (this.parent && this.parent.getWorldMatrix) {
  44853. if (!this.transformedPosition) {
  44854. this.transformedPosition = BABYLON.Vector3.Zero();
  44855. }
  44856. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  44857. // In case the direction is present.
  44858. if (this.direction) {
  44859. if (!this.transformedDirection) {
  44860. this.transformedDirection = BABYLON.Vector3.Zero();
  44861. }
  44862. BABYLON.Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this.transformedDirection);
  44863. }
  44864. return true;
  44865. }
  44866. return false;
  44867. };
  44868. /**
  44869. * Return the depth scale used for the shadow map.
  44870. * @returns the depth scale.
  44871. */
  44872. ShadowLight.prototype.getDepthScale = function () {
  44873. return 50.0;
  44874. };
  44875. /**
  44876. * Get the direction to use to render the shadow map. In case of cube texture, the face index can be passed.
  44877. * @param faceIndex The index of the face we are computed the direction to generate shadow
  44878. * @returns The set direction in 2d mode otherwise the direction to the cubemap face if needCube() is true
  44879. */
  44880. ShadowLight.prototype.getShadowDirection = function (faceIndex) {
  44881. return this.transformedDirection ? this.transformedDirection : this.direction;
  44882. };
  44883. /**
  44884. * Returns the ShadowLight absolute position in the World.
  44885. * @returns the position vector in world space
  44886. */
  44887. ShadowLight.prototype.getAbsolutePosition = function () {
  44888. return this.transformedPosition ? this.transformedPosition : this.position;
  44889. };
  44890. /**
  44891. * Sets the ShadowLight direction toward the passed target.
  44892. * @param target The point tot target in local space
  44893. * @returns the updated ShadowLight direction
  44894. */
  44895. ShadowLight.prototype.setDirectionToTarget = function (target) {
  44896. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  44897. return this.direction;
  44898. };
  44899. /**
  44900. * Returns the light rotation in euler definition.
  44901. * @returns the x y z rotation in local space.
  44902. */
  44903. ShadowLight.prototype.getRotation = function () {
  44904. this.direction.normalize();
  44905. var xaxis = BABYLON.Vector3.Cross(this.direction, BABYLON.Axis.Y);
  44906. var yaxis = BABYLON.Vector3.Cross(xaxis, this.direction);
  44907. return BABYLON.Vector3.RotationFromAxis(xaxis, yaxis, this.direction);
  44908. };
  44909. /**
  44910. * Returns whether or not the shadow generation require a cube texture or a 2d texture.
  44911. * @returns true if a cube texture needs to be use
  44912. */
  44913. ShadowLight.prototype.needCube = function () {
  44914. return false;
  44915. };
  44916. /**
  44917. * Detects if the projection matrix requires to be recomputed this frame.
  44918. * @returns true if it requires to be recomputed otherwise, false.
  44919. */
  44920. ShadowLight.prototype.needProjectionMatrixCompute = function () {
  44921. return this._needProjectionMatrixCompute;
  44922. };
  44923. /**
  44924. * Forces the shadow generator to recompute the projection matrix even if position and direction did not changed.
  44925. */
  44926. ShadowLight.prototype.forceProjectionMatrixCompute = function () {
  44927. this._needProjectionMatrixCompute = true;
  44928. };
  44929. /**
  44930. * Get the world matrix of the sahdow lights.
  44931. * @ignore Internal Use Only
  44932. */
  44933. ShadowLight.prototype._getWorldMatrix = function () {
  44934. if (!this._worldMatrix) {
  44935. this._worldMatrix = BABYLON.Matrix.Identity();
  44936. }
  44937. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  44938. return this._worldMatrix;
  44939. };
  44940. /**
  44941. * Gets the minZ used for shadow according to both the scene and the light.
  44942. * @param activeCamera The camera we are returning the min for
  44943. * @returns the depth min z
  44944. */
  44945. ShadowLight.prototype.getDepthMinZ = function (activeCamera) {
  44946. return this.shadowMinZ !== undefined ? this.shadowMinZ : activeCamera.minZ;
  44947. };
  44948. /**
  44949. * Gets the maxZ used for shadow according to both the scene and the light.
  44950. * @param activeCamera The camera we are returning the max for
  44951. * @returns the depth max z
  44952. */
  44953. ShadowLight.prototype.getDepthMaxZ = function (activeCamera) {
  44954. return this.shadowMaxZ !== undefined ? this.shadowMaxZ : activeCamera.maxZ;
  44955. };
  44956. /**
  44957. * Sets the shadow projection matrix in parameter to the generated projection matrix.
  44958. * @param matrix The materix to updated with the projection information
  44959. * @param viewMatrix The transform matrix of the light
  44960. * @param renderList The list of mesh to render in the map
  44961. * @returns The current light
  44962. */
  44963. ShadowLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  44964. if (this.customProjectionMatrixBuilder) {
  44965. this.customProjectionMatrixBuilder(viewMatrix, renderList, matrix);
  44966. }
  44967. else {
  44968. this._setDefaultShadowProjectionMatrix(matrix, viewMatrix, renderList);
  44969. }
  44970. return this;
  44971. };
  44972. __decorate([
  44973. BABYLON.serializeAsVector3()
  44974. ], ShadowLight.prototype, "position", null);
  44975. __decorate([
  44976. BABYLON.serializeAsVector3()
  44977. ], ShadowLight.prototype, "direction", null);
  44978. __decorate([
  44979. BABYLON.serialize()
  44980. ], ShadowLight.prototype, "shadowMinZ", null);
  44981. __decorate([
  44982. BABYLON.serialize()
  44983. ], ShadowLight.prototype, "shadowMaxZ", null);
  44984. return ShadowLight;
  44985. }(BABYLON.Light));
  44986. BABYLON.ShadowLight = ShadowLight;
  44987. })(BABYLON || (BABYLON = {}));
  44988. //# sourceMappingURL=babylon.shadowLight.js.map
  44989. var BABYLON;
  44990. (function (BABYLON) {
  44991. /**
  44992. * A point light is a light defined by an unique point in world space.
  44993. * The light is emitted in every direction from this point.
  44994. * A good example of a point light is a standard light bulb.
  44995. * Documentation: https://doc.babylonjs.com/babylon101/lights
  44996. */
  44997. var PointLight = /** @class */ (function (_super) {
  44998. __extends(PointLight, _super);
  44999. /**
  45000. * Creates a PointLight object from the passed name and position (Vector3) and adds it in the scene.
  45001. * A PointLight emits the light in every direction.
  45002. * It can cast shadows.
  45003. * If the scene camera is already defined and you want to set your PointLight at the camera position, just set it :
  45004. * ```javascript
  45005. * var pointLight = new BABYLON.PointLight("pl", camera.position, scene);
  45006. * ```
  45007. * Documentation : http://doc.babylonjs.com/tutorials/lights
  45008. * @param name The light friendly name
  45009. * @param position The position of the point light in the scene
  45010. * @param scene The scene the lights belongs to
  45011. */
  45012. function PointLight(name, position, scene) {
  45013. var _this = _super.call(this, name, scene) || this;
  45014. _this._shadowAngle = Math.PI / 2;
  45015. _this.position = position;
  45016. return _this;
  45017. }
  45018. Object.defineProperty(PointLight.prototype, "shadowAngle", {
  45019. /**
  45020. * Getter: In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  45021. * This specifies what angle the shadow will use to be created.
  45022. *
  45023. * It default to 90 degrees to work nicely with the cube texture generation for point lights shadow maps.
  45024. */
  45025. get: function () {
  45026. return this._shadowAngle;
  45027. },
  45028. /**
  45029. * Setter: In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  45030. * This specifies what angle the shadow will use to be created.
  45031. *
  45032. * It default to 90 degrees to work nicely with the cube texture generation for point lights shadow maps.
  45033. */
  45034. set: function (value) {
  45035. this._shadowAngle = value;
  45036. this.forceProjectionMatrixCompute();
  45037. },
  45038. enumerable: true,
  45039. configurable: true
  45040. });
  45041. Object.defineProperty(PointLight.prototype, "direction", {
  45042. /**
  45043. * Gets the direction if it has been set.
  45044. * In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  45045. */
  45046. get: function () {
  45047. return this._direction;
  45048. },
  45049. /**
  45050. * In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  45051. */
  45052. set: function (value) {
  45053. var previousNeedCube = this.needCube();
  45054. this._direction = value;
  45055. if (this.needCube() !== previousNeedCube && this._shadowGenerator) {
  45056. this._shadowGenerator.recreateShadowMap();
  45057. }
  45058. },
  45059. enumerable: true,
  45060. configurable: true
  45061. });
  45062. /**
  45063. * Returns the string "PointLight"
  45064. * @returns the class name
  45065. */
  45066. PointLight.prototype.getClassName = function () {
  45067. return "PointLight";
  45068. };
  45069. /**
  45070. * Returns the integer 0.
  45071. * @returns The light Type id as a constant defines in Light.LIGHTTYPEID_x
  45072. */
  45073. PointLight.prototype.getTypeID = function () {
  45074. return BABYLON.Light.LIGHTTYPEID_POINTLIGHT;
  45075. };
  45076. /**
  45077. * Specifies wether or not the shadowmap should be a cube texture.
  45078. * @returns true if the shadowmap needs to be a cube texture.
  45079. */
  45080. PointLight.prototype.needCube = function () {
  45081. return !this.direction;
  45082. };
  45083. /**
  45084. * Returns a new Vector3 aligned with the PointLight cube system according to the passed cube face index (integer).
  45085. * @param faceIndex The index of the face we are computed the direction to generate shadow
  45086. * @returns The set direction in 2d mode otherwise the direction to the cubemap face if needCube() is true
  45087. */
  45088. PointLight.prototype.getShadowDirection = function (faceIndex) {
  45089. if (this.direction) {
  45090. return _super.prototype.getShadowDirection.call(this, faceIndex);
  45091. }
  45092. else {
  45093. switch (faceIndex) {
  45094. case 0:
  45095. return new BABYLON.Vector3(1.0, 0.0, 0.0);
  45096. case 1:
  45097. return new BABYLON.Vector3(-1.0, 0.0, 0.0);
  45098. case 2:
  45099. return new BABYLON.Vector3(0.0, -1.0, 0.0);
  45100. case 3:
  45101. return new BABYLON.Vector3(0.0, 1.0, 0.0);
  45102. case 4:
  45103. return new BABYLON.Vector3(0.0, 0.0, 1.0);
  45104. case 5:
  45105. return new BABYLON.Vector3(0.0, 0.0, -1.0);
  45106. }
  45107. }
  45108. return BABYLON.Vector3.Zero();
  45109. };
  45110. /**
  45111. * Sets the passed matrix "matrix" as a left-handed perspective projection matrix with the following settings :
  45112. * - fov = PI / 2
  45113. * - aspect ratio : 1.0
  45114. * - z-near and far equal to the active camera minZ and maxZ.
  45115. * Returns the PointLight.
  45116. */
  45117. PointLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  45118. var activeCamera = this.getScene().activeCamera;
  45119. if (!activeCamera) {
  45120. return;
  45121. }
  45122. BABYLON.Matrix.PerspectiveFovLHToRef(this.shadowAngle, 1.0, this.getDepthMinZ(activeCamera), this.getDepthMaxZ(activeCamera), matrix);
  45123. };
  45124. PointLight.prototype._buildUniformLayout = function () {
  45125. this._uniformBuffer.addUniform("vLightData", 4);
  45126. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  45127. this._uniformBuffer.addUniform("vLightSpecular", 3);
  45128. this._uniformBuffer.addUniform("shadowsInfo", 3);
  45129. this._uniformBuffer.addUniform("depthValues", 2);
  45130. this._uniformBuffer.create();
  45131. };
  45132. /**
  45133. * Sets the passed Effect "effect" with the PointLight transformed position (or position, if none) and passed name (string).
  45134. * @param effect The effect to update
  45135. * @param lightIndex The index of the light in the effect to update
  45136. * @returns The point light
  45137. */
  45138. PointLight.prototype.transferToEffect = function (effect, lightIndex) {
  45139. if (this.computeTransformedInformation()) {
  45140. this._uniformBuffer.updateFloat4("vLightData", this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, 0.0, lightIndex);
  45141. return this;
  45142. }
  45143. this._uniformBuffer.updateFloat4("vLightData", this.position.x, this.position.y, this.position.z, 0, lightIndex);
  45144. return this;
  45145. };
  45146. __decorate([
  45147. BABYLON.serialize()
  45148. ], PointLight.prototype, "shadowAngle", null);
  45149. return PointLight;
  45150. }(BABYLON.ShadowLight));
  45151. BABYLON.PointLight = PointLight;
  45152. })(BABYLON || (BABYLON = {}));
  45153. //# sourceMappingURL=babylon.pointLight.js.map
  45154. var BABYLON;
  45155. (function (BABYLON) {
  45156. /**
  45157. * A directional light is defined by a direction (what a surprise!).
  45158. * The light is emitted from everywhere in the specified direction, and has an infinite range.
  45159. * 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.
  45160. * Documentation: https://doc.babylonjs.com/babylon101/lights
  45161. */
  45162. var DirectionalLight = /** @class */ (function (_super) {
  45163. __extends(DirectionalLight, _super);
  45164. /**
  45165. * Creates a DirectionalLight object in the scene, oriented towards the passed direction (Vector3).
  45166. * The directional light is emitted from everywhere in the given direction.
  45167. * It can cast shawdows.
  45168. * Documentation : http://doc.babylonjs.com/tutorials/lights
  45169. * @param name The friendly name of the light
  45170. * @param direction The direction of the light
  45171. * @param scene The scene the light belongs to
  45172. */
  45173. function DirectionalLight(name, direction, scene) {
  45174. var _this = _super.call(this, name, scene) || this;
  45175. _this._shadowFrustumSize = 0;
  45176. _this._shadowOrthoScale = 0.5;
  45177. /**
  45178. * Automatically compute the projection matrix to best fit (including all the casters)
  45179. * on each frame.
  45180. */
  45181. _this.autoUpdateExtends = true;
  45182. // Cache
  45183. _this._orthoLeft = Number.MAX_VALUE;
  45184. _this._orthoRight = Number.MIN_VALUE;
  45185. _this._orthoTop = Number.MIN_VALUE;
  45186. _this._orthoBottom = Number.MAX_VALUE;
  45187. _this.position = direction.scale(-1.0);
  45188. _this.direction = direction;
  45189. return _this;
  45190. }
  45191. Object.defineProperty(DirectionalLight.prototype, "shadowFrustumSize", {
  45192. /**
  45193. * Fix frustum size for the shadow generation. This is disabled if the value is 0.
  45194. */
  45195. get: function () {
  45196. return this._shadowFrustumSize;
  45197. },
  45198. /**
  45199. * Specifies a fix frustum size for the shadow generation.
  45200. */
  45201. set: function (value) {
  45202. this._shadowFrustumSize = value;
  45203. this.forceProjectionMatrixCompute();
  45204. },
  45205. enumerable: true,
  45206. configurable: true
  45207. });
  45208. Object.defineProperty(DirectionalLight.prototype, "shadowOrthoScale", {
  45209. /**
  45210. * Gets the shadow projection scale against the optimal computed one.
  45211. * 0.1 by default which means that the projection window is increase by 10% from the optimal size.
  45212. * This does not impact in fixed frustum size (shadowFrustumSize being set)
  45213. */
  45214. get: function () {
  45215. return this._shadowOrthoScale;
  45216. },
  45217. /**
  45218. * Sets the shadow projection scale against the optimal computed one.
  45219. * 0.1 by default which means that the projection window is increase by 10% from the optimal size.
  45220. * This does not impact in fixed frustum size (shadowFrustumSize being set)
  45221. */
  45222. set: function (value) {
  45223. this._shadowOrthoScale = value;
  45224. this.forceProjectionMatrixCompute();
  45225. },
  45226. enumerable: true,
  45227. configurable: true
  45228. });
  45229. /**
  45230. * Returns the string "DirectionalLight".
  45231. * @return The class name
  45232. */
  45233. DirectionalLight.prototype.getClassName = function () {
  45234. return "DirectionalLight";
  45235. };
  45236. /**
  45237. * Returns the integer 1.
  45238. * @return The light Type id as a constant defines in Light.LIGHTTYPEID_x
  45239. */
  45240. DirectionalLight.prototype.getTypeID = function () {
  45241. return BABYLON.Light.LIGHTTYPEID_DIRECTIONALLIGHT;
  45242. };
  45243. /**
  45244. * Sets the passed matrix "matrix" as projection matrix for the shadows cast by the light according to the passed view matrix.
  45245. * Returns the DirectionalLight Shadow projection matrix.
  45246. */
  45247. DirectionalLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  45248. if (this.shadowFrustumSize > 0) {
  45249. this._setDefaultFixedFrustumShadowProjectionMatrix(matrix, viewMatrix);
  45250. }
  45251. else {
  45252. this._setDefaultAutoExtendShadowProjectionMatrix(matrix, viewMatrix, renderList);
  45253. }
  45254. };
  45255. /**
  45256. * Sets the passed matrix "matrix" as fixed frustum projection matrix for the shadows cast by the light according to the passed view matrix.
  45257. * Returns the DirectionalLight Shadow projection matrix.
  45258. */
  45259. DirectionalLight.prototype._setDefaultFixedFrustumShadowProjectionMatrix = function (matrix, viewMatrix) {
  45260. var activeCamera = this.getScene().activeCamera;
  45261. if (!activeCamera) {
  45262. return;
  45263. }
  45264. BABYLON.Matrix.OrthoLHToRef(this.shadowFrustumSize, this.shadowFrustumSize, this.shadowMinZ !== undefined ? this.shadowMinZ : activeCamera.minZ, this.shadowMaxZ !== undefined ? this.shadowMaxZ : activeCamera.maxZ, matrix);
  45265. };
  45266. /**
  45267. * Sets the passed matrix "matrix" as auto extend projection matrix for the shadows cast by the light according to the passed view matrix.
  45268. * Returns the DirectionalLight Shadow projection matrix.
  45269. */
  45270. DirectionalLight.prototype._setDefaultAutoExtendShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  45271. var activeCamera = this.getScene().activeCamera;
  45272. if (!activeCamera) {
  45273. return;
  45274. }
  45275. // Check extends
  45276. if (this.autoUpdateExtends || this._orthoLeft === Number.MAX_VALUE) {
  45277. var tempVector3 = BABYLON.Vector3.Zero();
  45278. this._orthoLeft = Number.MAX_VALUE;
  45279. this._orthoRight = Number.MIN_VALUE;
  45280. this._orthoTop = Number.MIN_VALUE;
  45281. this._orthoBottom = Number.MAX_VALUE;
  45282. for (var meshIndex = 0; meshIndex < renderList.length; meshIndex++) {
  45283. var mesh = renderList[meshIndex];
  45284. if (!mesh) {
  45285. continue;
  45286. }
  45287. var boundingInfo = mesh.getBoundingInfo();
  45288. var boundingBox = boundingInfo.boundingBox;
  45289. for (var index = 0; index < boundingBox.vectorsWorld.length; index++) {
  45290. BABYLON.Vector3.TransformCoordinatesToRef(boundingBox.vectorsWorld[index], viewMatrix, tempVector3);
  45291. if (tempVector3.x < this._orthoLeft)
  45292. this._orthoLeft = tempVector3.x;
  45293. if (tempVector3.y < this._orthoBottom)
  45294. this._orthoBottom = tempVector3.y;
  45295. if (tempVector3.x > this._orthoRight)
  45296. this._orthoRight = tempVector3.x;
  45297. if (tempVector3.y > this._orthoTop)
  45298. this._orthoTop = tempVector3.y;
  45299. }
  45300. }
  45301. }
  45302. var xOffset = this._orthoRight - this._orthoLeft;
  45303. var yOffset = this._orthoTop - this._orthoBottom;
  45304. 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);
  45305. };
  45306. DirectionalLight.prototype._buildUniformLayout = function () {
  45307. this._uniformBuffer.addUniform("vLightData", 4);
  45308. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  45309. this._uniformBuffer.addUniform("vLightSpecular", 3);
  45310. this._uniformBuffer.addUniform("shadowsInfo", 3);
  45311. this._uniformBuffer.addUniform("depthValues", 2);
  45312. this._uniformBuffer.create();
  45313. };
  45314. /**
  45315. * Sets the passed Effect object with the DirectionalLight transformed position (or position if not parented) and the passed name.
  45316. * @param effect The effect to update
  45317. * @param lightIndex The index of the light in the effect to update
  45318. * @returns The directional light
  45319. */
  45320. DirectionalLight.prototype.transferToEffect = function (effect, lightIndex) {
  45321. if (this.computeTransformedInformation()) {
  45322. this._uniformBuffer.updateFloat4("vLightData", this.transformedDirection.x, this.transformedDirection.y, this.transformedDirection.z, 1, lightIndex);
  45323. return this;
  45324. }
  45325. this._uniformBuffer.updateFloat4("vLightData", this.direction.x, this.direction.y, this.direction.z, 1, lightIndex);
  45326. return this;
  45327. };
  45328. /**
  45329. * Gets the minZ used for shadow according to both the scene and the light.
  45330. *
  45331. * Values are fixed on directional lights as it relies on an ortho projection hence the need to convert being
  45332. * -1 and 1 to 0 and 1 doing (depth + min) / (min + max) -> (depth + 1) / (1 + 1) -> (depth * 0.5) + 0.5.
  45333. * @param activeCamera The camera we are returning the min for
  45334. * @returns the depth min z
  45335. */
  45336. DirectionalLight.prototype.getDepthMinZ = function (activeCamera) {
  45337. return 1;
  45338. };
  45339. /**
  45340. * Gets the maxZ used for shadow according to both the scene and the light.
  45341. *
  45342. * Values are fixed on directional lights as it relies on an ortho projection hence the need to convert being
  45343. * -1 and 1 to 0 and 1 doing (depth + min) / (min + max) -> (depth + 1) / (1 + 1) -> (depth * 0.5) + 0.5.
  45344. * @param activeCamera The camera we are returning the max for
  45345. * @returns the depth max z
  45346. */
  45347. DirectionalLight.prototype.getDepthMaxZ = function (activeCamera) {
  45348. return 1;
  45349. };
  45350. __decorate([
  45351. BABYLON.serialize()
  45352. ], DirectionalLight.prototype, "shadowFrustumSize", null);
  45353. __decorate([
  45354. BABYLON.serialize()
  45355. ], DirectionalLight.prototype, "shadowOrthoScale", null);
  45356. __decorate([
  45357. BABYLON.serialize()
  45358. ], DirectionalLight.prototype, "autoUpdateExtends", void 0);
  45359. return DirectionalLight;
  45360. }(BABYLON.ShadowLight));
  45361. BABYLON.DirectionalLight = DirectionalLight;
  45362. })(BABYLON || (BABYLON = {}));
  45363. //# sourceMappingURL=babylon.directionalLight.js.map
  45364. var BABYLON;
  45365. (function (BABYLON) {
  45366. /**
  45367. * A spot light is defined by a position, a direction, an angle, and an exponent.
  45368. * These values define a cone of light starting from the position, emitting toward the direction.
  45369. * The angle, in radians, defines the size (field of illumination) of the spotlight's conical beam,
  45370. * and the exponent defines the speed of the decay of the light with distance (reach).
  45371. * Documentation: https://doc.babylonjs.com/babylon101/lights
  45372. */
  45373. var SpotLight = /** @class */ (function (_super) {
  45374. __extends(SpotLight, _super);
  45375. /**
  45376. * Creates a SpotLight object in the scene. A spot light is a simply light oriented cone.
  45377. * It can cast shadows.
  45378. * Documentation : http://doc.babylonjs.com/tutorials/lights
  45379. * @param name The light friendly name
  45380. * @param position The position of the spot light in the scene
  45381. * @param direction The direction of the light in the scene
  45382. * @param angle The cone angle of the light in Radians
  45383. * @param exponent The light decay speed with the distance from the emission spot
  45384. * @param scene The scene the lights belongs to
  45385. */
  45386. function SpotLight(name, position, direction, angle, exponent, scene) {
  45387. var _this = _super.call(this, name, scene) || this;
  45388. _this._projectionTextureMatrix = BABYLON.Matrix.Zero();
  45389. _this._projectionTextureLightNear = 1e-6;
  45390. _this._projectionTextureLightFar = 1000.0;
  45391. _this._projectionTextureUpDirection = BABYLON.Vector3.Up();
  45392. _this._projectionTextureViewLightDirty = true;
  45393. _this._projectionTextureProjectionLightDirty = true;
  45394. _this._projectionTextureDirty = true;
  45395. _this._projectionTextureViewTargetVector = BABYLON.Vector3.Zero();
  45396. _this._projectionTextureViewLightMatrix = BABYLON.Matrix.Zero();
  45397. _this._projectionTextureProjectionLightMatrix = BABYLON.Matrix.Zero();
  45398. _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);
  45399. _this.position = position;
  45400. _this.direction = direction;
  45401. _this.angle = angle;
  45402. _this.exponent = exponent;
  45403. return _this;
  45404. }
  45405. Object.defineProperty(SpotLight.prototype, "angle", {
  45406. /**
  45407. * Gets the cone angle of the spot light in Radians.
  45408. */
  45409. get: function () {
  45410. return this._angle;
  45411. },
  45412. /**
  45413. * Sets the cone angle of the spot light in Radians.
  45414. */
  45415. set: function (value) {
  45416. this._angle = value;
  45417. this._projectionTextureProjectionLightDirty = true;
  45418. this.forceProjectionMatrixCompute();
  45419. },
  45420. enumerable: true,
  45421. configurable: true
  45422. });
  45423. Object.defineProperty(SpotLight.prototype, "shadowAngleScale", {
  45424. /**
  45425. * Allows scaling the angle of the light for shadow generation only.
  45426. */
  45427. get: function () {
  45428. return this._shadowAngleScale;
  45429. },
  45430. /**
  45431. * Allows scaling the angle of the light for shadow generation only.
  45432. */
  45433. set: function (value) {
  45434. this._shadowAngleScale = value;
  45435. this.forceProjectionMatrixCompute();
  45436. },
  45437. enumerable: true,
  45438. configurable: true
  45439. });
  45440. Object.defineProperty(SpotLight.prototype, "projectionTextureMatrix", {
  45441. /**
  45442. * Allows reading the projecton texture
  45443. */
  45444. get: function () {
  45445. return this._projectionTextureMatrix;
  45446. },
  45447. enumerable: true,
  45448. configurable: true
  45449. });
  45450. ;
  45451. Object.defineProperty(SpotLight.prototype, "projectionTextureLightNear", {
  45452. /**
  45453. * Gets the near clip of the Spotlight for texture projection.
  45454. */
  45455. get: function () {
  45456. return this._projectionTextureLightNear;
  45457. },
  45458. /**
  45459. * Sets the near clip of the Spotlight for texture projection.
  45460. */
  45461. set: function (value) {
  45462. this._projectionTextureLightNear = value;
  45463. this._projectionTextureProjectionLightDirty = true;
  45464. },
  45465. enumerable: true,
  45466. configurable: true
  45467. });
  45468. Object.defineProperty(SpotLight.prototype, "projectionTextureLightFar", {
  45469. /**
  45470. * Gets the far clip of the Spotlight for texture projection.
  45471. */
  45472. get: function () {
  45473. return this._projectionTextureLightFar;
  45474. },
  45475. /**
  45476. * Sets the far clip of the Spotlight for texture projection.
  45477. */
  45478. set: function (value) {
  45479. this._projectionTextureLightFar = value;
  45480. this._projectionTextureProjectionLightDirty = true;
  45481. },
  45482. enumerable: true,
  45483. configurable: true
  45484. });
  45485. Object.defineProperty(SpotLight.prototype, "projectionTextureUpDirection", {
  45486. /**
  45487. * Gets the Up vector of the Spotlight for texture projection.
  45488. */
  45489. get: function () {
  45490. return this._projectionTextureUpDirection;
  45491. },
  45492. /**
  45493. * Sets the Up vector of the Spotlight for texture projection.
  45494. */
  45495. set: function (value) {
  45496. this._projectionTextureUpDirection = value;
  45497. this._projectionTextureProjectionLightDirty = true;
  45498. },
  45499. enumerable: true,
  45500. configurable: true
  45501. });
  45502. ;
  45503. Object.defineProperty(SpotLight.prototype, "projectionTexture", {
  45504. /**
  45505. * Gets the projection texture of the light.
  45506. */
  45507. get: function () {
  45508. return this._projectionTexture;
  45509. },
  45510. /**
  45511. * Sets the projection texture of the light.
  45512. */
  45513. set: function (value) {
  45514. this._projectionTexture = value;
  45515. this._projectionTextureDirty = true;
  45516. },
  45517. enumerable: true,
  45518. configurable: true
  45519. });
  45520. /**
  45521. * Returns the string "SpotLight".
  45522. * @returns the class name
  45523. */
  45524. SpotLight.prototype.getClassName = function () {
  45525. return "SpotLight";
  45526. };
  45527. /**
  45528. * Returns the integer 2.
  45529. * @returns The light Type id as a constant defines in Light.LIGHTTYPEID_x
  45530. */
  45531. SpotLight.prototype.getTypeID = function () {
  45532. return BABYLON.Light.LIGHTTYPEID_SPOTLIGHT;
  45533. };
  45534. /**
  45535. * Overrides the direction setter to recompute the projection texture view light Matrix.
  45536. */
  45537. SpotLight.prototype._setDirection = function (value) {
  45538. _super.prototype._setDirection.call(this, value);
  45539. this._projectionTextureViewLightDirty = true;
  45540. };
  45541. /**
  45542. * Overrides the position setter to recompute the projection texture view light Matrix.
  45543. */
  45544. SpotLight.prototype._setPosition = function (value) {
  45545. _super.prototype._setPosition.call(this, value);
  45546. this._projectionTextureViewLightDirty = true;
  45547. };
  45548. /**
  45549. * 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.
  45550. * Returns the SpotLight.
  45551. */
  45552. SpotLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  45553. var activeCamera = this.getScene().activeCamera;
  45554. if (!activeCamera) {
  45555. return;
  45556. }
  45557. this._shadowAngleScale = this._shadowAngleScale || 1;
  45558. var angle = this._shadowAngleScale * this._angle;
  45559. BABYLON.Matrix.PerspectiveFovLHToRef(angle, 1.0, this.getDepthMinZ(activeCamera), this.getDepthMaxZ(activeCamera), matrix);
  45560. };
  45561. SpotLight.prototype._computeProjectionTextureViewLightMatrix = function () {
  45562. this._projectionTextureViewLightDirty = false;
  45563. this._projectionTextureDirty = true;
  45564. this.position.addToRef(this.direction, this._projectionTextureViewTargetVector);
  45565. BABYLON.Matrix.LookAtLHToRef(this.position, this._projectionTextureViewTargetVector, this._projectionTextureUpDirection, this._projectionTextureViewLightMatrix);
  45566. };
  45567. SpotLight.prototype._computeProjectionTextureProjectionLightMatrix = function () {
  45568. this._projectionTextureProjectionLightDirty = false;
  45569. this._projectionTextureDirty = true;
  45570. var light_far = this.projectionTextureLightFar;
  45571. var light_near = this.projectionTextureLightNear;
  45572. var P = light_far / (light_far - light_near);
  45573. var Q = -P * light_near;
  45574. var S = 1.0 / Math.tan(this._angle / 2.0);
  45575. var A = 1.0;
  45576. 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);
  45577. };
  45578. /**
  45579. * Main function for light texture projection matrix computing.
  45580. */
  45581. SpotLight.prototype._computeProjectionTextureMatrix = function () {
  45582. this._projectionTextureDirty = false;
  45583. this._projectionTextureViewLightMatrix.multiplyToRef(this._projectionTextureProjectionLightMatrix, this._projectionTextureMatrix);
  45584. this._projectionTextureMatrix.multiplyToRef(this._projectionTextureScalingMatrix, this._projectionTextureMatrix);
  45585. };
  45586. SpotLight.prototype._buildUniformLayout = function () {
  45587. this._uniformBuffer.addUniform("vLightData", 4);
  45588. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  45589. this._uniformBuffer.addUniform("vLightSpecular", 3);
  45590. this._uniformBuffer.addUniform("vLightDirection", 3);
  45591. this._uniformBuffer.addUniform("shadowsInfo", 3);
  45592. this._uniformBuffer.addUniform("depthValues", 2);
  45593. this._uniformBuffer.create();
  45594. };
  45595. /**
  45596. * Sets the passed Effect object with the SpotLight transfomed position (or position if not parented) and normalized direction.
  45597. * @param effect The effect to update
  45598. * @param lightIndex The index of the light in the effect to update
  45599. * @returns The spot light
  45600. */
  45601. SpotLight.prototype.transferToEffect = function (effect, lightIndex) {
  45602. var normalizeDirection;
  45603. if (this.computeTransformedInformation()) {
  45604. this._uniformBuffer.updateFloat4("vLightData", this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, this.exponent, lightIndex);
  45605. normalizeDirection = BABYLON.Vector3.Normalize(this.transformedDirection);
  45606. }
  45607. else {
  45608. this._uniformBuffer.updateFloat4("vLightData", this.position.x, this.position.y, this.position.z, this.exponent, lightIndex);
  45609. normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  45610. }
  45611. this._uniformBuffer.updateFloat4("vLightDirection", normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, Math.cos(this.angle * 0.5), lightIndex);
  45612. if (this.projectionTexture && this.projectionTexture.isReady()) {
  45613. if (this._projectionTextureViewLightDirty) {
  45614. this._computeProjectionTextureViewLightMatrix();
  45615. }
  45616. if (this._projectionTextureProjectionLightDirty) {
  45617. this._computeProjectionTextureProjectionLightMatrix();
  45618. }
  45619. if (this._projectionTextureDirty) {
  45620. this._computeProjectionTextureMatrix();
  45621. }
  45622. effect.setMatrix("textureProjectionMatrix" + lightIndex, this._projectionTextureMatrix);
  45623. effect.setTexture("projectionLightSampler" + lightIndex, this.projectionTexture);
  45624. }
  45625. return this;
  45626. };
  45627. /**
  45628. * Disposes the light and the associated resources.
  45629. */
  45630. SpotLight.prototype.dispose = function () {
  45631. _super.prototype.dispose.call(this);
  45632. if (this._projectionTexture) {
  45633. this._projectionTexture.dispose();
  45634. }
  45635. };
  45636. __decorate([
  45637. BABYLON.serialize()
  45638. ], SpotLight.prototype, "angle", null);
  45639. __decorate([
  45640. BABYLON.serialize()
  45641. ], SpotLight.prototype, "shadowAngleScale", null);
  45642. __decorate([
  45643. BABYLON.serialize()
  45644. ], SpotLight.prototype, "exponent", void 0);
  45645. __decorate([
  45646. BABYLON.serialize()
  45647. ], SpotLight.prototype, "projectionTextureLightNear", null);
  45648. __decorate([
  45649. BABYLON.serialize()
  45650. ], SpotLight.prototype, "projectionTextureLightFar", null);
  45651. __decorate([
  45652. BABYLON.serialize()
  45653. ], SpotLight.prototype, "projectionTextureUpDirection", null);
  45654. __decorate([
  45655. BABYLON.serializeAsTexture("projectedLightTexture")
  45656. ], SpotLight.prototype, "_projectionTexture", void 0);
  45657. return SpotLight;
  45658. }(BABYLON.ShadowLight));
  45659. BABYLON.SpotLight = SpotLight;
  45660. })(BABYLON || (BABYLON = {}));
  45661. //# sourceMappingURL=babylon.spotLight.js.map
  45662. var BABYLON;
  45663. (function (BABYLON) {
  45664. var AnimationRange = /** @class */ (function () {
  45665. function AnimationRange(name, from, to) {
  45666. this.name = name;
  45667. this.from = from;
  45668. this.to = to;
  45669. }
  45670. AnimationRange.prototype.clone = function () {
  45671. return new AnimationRange(this.name, this.from, this.to);
  45672. };
  45673. return AnimationRange;
  45674. }());
  45675. BABYLON.AnimationRange = AnimationRange;
  45676. /**
  45677. * Composed of a frame, and an action function
  45678. */
  45679. var AnimationEvent = /** @class */ (function () {
  45680. function AnimationEvent(frame, action, onlyOnce) {
  45681. this.frame = frame;
  45682. this.action = action;
  45683. this.onlyOnce = onlyOnce;
  45684. this.isDone = false;
  45685. }
  45686. return AnimationEvent;
  45687. }());
  45688. BABYLON.AnimationEvent = AnimationEvent;
  45689. var PathCursor = /** @class */ (function () {
  45690. function PathCursor(path) {
  45691. this.path = path;
  45692. this._onchange = new Array();
  45693. this.value = 0;
  45694. this.animations = new Array();
  45695. }
  45696. PathCursor.prototype.getPoint = function () {
  45697. var point = this.path.getPointAtLengthPosition(this.value);
  45698. return new BABYLON.Vector3(point.x, 0, point.y);
  45699. };
  45700. PathCursor.prototype.moveAhead = function (step) {
  45701. if (step === void 0) { step = 0.002; }
  45702. this.move(step);
  45703. return this;
  45704. };
  45705. PathCursor.prototype.moveBack = function (step) {
  45706. if (step === void 0) { step = 0.002; }
  45707. this.move(-step);
  45708. return this;
  45709. };
  45710. PathCursor.prototype.move = function (step) {
  45711. if (Math.abs(step) > 1) {
  45712. throw "step size should be less than 1.";
  45713. }
  45714. this.value += step;
  45715. this.ensureLimits();
  45716. this.raiseOnChange();
  45717. return this;
  45718. };
  45719. PathCursor.prototype.ensureLimits = function () {
  45720. while (this.value > 1) {
  45721. this.value -= 1;
  45722. }
  45723. while (this.value < 0) {
  45724. this.value += 1;
  45725. }
  45726. return this;
  45727. };
  45728. // used by animation engine
  45729. PathCursor.prototype.raiseOnChange = function () {
  45730. var _this = this;
  45731. this._onchange.forEach(function (f) { return f(_this); });
  45732. return this;
  45733. };
  45734. PathCursor.prototype.onchange = function (f) {
  45735. this._onchange.push(f);
  45736. return this;
  45737. };
  45738. return PathCursor;
  45739. }());
  45740. BABYLON.PathCursor = PathCursor;
  45741. var AnimationKeyInterpolation;
  45742. (function (AnimationKeyInterpolation) {
  45743. /**
  45744. * Do not interpolate between keys and use the start key value only. Tangents are ignored.
  45745. */
  45746. AnimationKeyInterpolation[AnimationKeyInterpolation["STEP"] = 1] = "STEP";
  45747. })(AnimationKeyInterpolation = BABYLON.AnimationKeyInterpolation || (BABYLON.AnimationKeyInterpolation = {}));
  45748. var Animation = /** @class */ (function () {
  45749. function Animation(name, targetProperty, framePerSecond, dataType, loopMode, enableBlending) {
  45750. this.name = name;
  45751. this.targetProperty = targetProperty;
  45752. this.framePerSecond = framePerSecond;
  45753. this.dataType = dataType;
  45754. this.loopMode = loopMode;
  45755. this.enableBlending = enableBlending;
  45756. this._runtimeAnimations = new Array();
  45757. // The set of event that will be linked to this animation
  45758. this._events = new Array();
  45759. this.blendingSpeed = 0.01;
  45760. this._ranges = {};
  45761. this.targetPropertyPath = targetProperty.split(".");
  45762. this.dataType = dataType;
  45763. this.loopMode = loopMode === undefined ? Animation.ANIMATIONLOOPMODE_CYCLE : loopMode;
  45764. }
  45765. Animation._PrepareAnimation = function (name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction) {
  45766. var dataType = undefined;
  45767. if (!isNaN(parseFloat(from)) && isFinite(from)) {
  45768. dataType = Animation.ANIMATIONTYPE_FLOAT;
  45769. }
  45770. else if (from instanceof BABYLON.Quaternion) {
  45771. dataType = Animation.ANIMATIONTYPE_QUATERNION;
  45772. }
  45773. else if (from instanceof BABYLON.Vector3) {
  45774. dataType = Animation.ANIMATIONTYPE_VECTOR3;
  45775. }
  45776. else if (from instanceof BABYLON.Vector2) {
  45777. dataType = Animation.ANIMATIONTYPE_VECTOR2;
  45778. }
  45779. else if (from instanceof BABYLON.Color3) {
  45780. dataType = Animation.ANIMATIONTYPE_COLOR3;
  45781. }
  45782. else if (from instanceof BABYLON.Size) {
  45783. dataType = Animation.ANIMATIONTYPE_SIZE;
  45784. }
  45785. if (dataType == undefined) {
  45786. return null;
  45787. }
  45788. var animation = new Animation(name, targetProperty, framePerSecond, dataType, loopMode);
  45789. var keys = [{ frame: 0, value: from }, { frame: totalFrame, value: to }];
  45790. animation.setKeys(keys);
  45791. if (easingFunction !== undefined) {
  45792. animation.setEasingFunction(easingFunction);
  45793. }
  45794. return animation;
  45795. };
  45796. /**
  45797. * Sets up an animation.
  45798. * @param property the property to animate
  45799. * @param animationType the animation type to apply
  45800. * @param easingFunction the easing function used in the animation
  45801. * @returns The created animation
  45802. */
  45803. Animation.CreateAnimation = function (property, animationType, framePerSecond, easingFunction) {
  45804. var animation = new Animation(property + "Animation", property, framePerSecond, animationType, Animation.ANIMATIONLOOPMODE_CONSTANT);
  45805. animation.setEasingFunction(easingFunction);
  45806. return animation;
  45807. };
  45808. /**
  45809. * Create and start an animation on a node
  45810. * @param {string} name defines the name of the global animation that will be run on all nodes
  45811. * @param {BABYLON.Node} node defines the root node where the animation will take place
  45812. * @param {string} targetProperty defines property to animate
  45813. * @param {number} framePerSecond defines the number of frame per second yo use
  45814. * @param {number} totalFrame defines the number of frames in total
  45815. * @param {any} from defines the initial value
  45816. * @param {any} to defines the final value
  45817. * @param {number} loopMode defines which loop mode you want to use (off by default)
  45818. * @param {BABYLON.EasingFunction} easingFunction defines the easing function to use (linear by default)
  45819. * @param onAnimationEnd defines the callback to call when animation end
  45820. * @returns the animatable created for this animation
  45821. */
  45822. Animation.CreateAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  45823. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  45824. if (!animation) {
  45825. return null;
  45826. }
  45827. return node.getScene().beginDirectAnimation(node, [animation], 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  45828. };
  45829. /**
  45830. * Create and start an animation on a node and its descendants
  45831. * @param {string} name defines the name of the global animation that will be run on all nodes
  45832. * @param {BABYLON.Node} node defines the root node where the animation will take place
  45833. * @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.
  45834. * @param {string} targetProperty defines property to animate
  45835. * @param {number} framePerSecond defines the number of frame per second yo use
  45836. * @param {number} totalFrame defines the number of frames in total
  45837. * @param {any} from defines the initial value
  45838. * @param {any} to defines the final value
  45839. * @param {number} loopMode defines which loop mode you want to use (off by default)
  45840. * @param {BABYLON.EasingFunction} easingFunction defines the easing function to use (linear by default)
  45841. * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)
  45842. * @returns the list of animatables created for all nodes
  45843. * @example https://www.babylonjs-playground.com/#MH0VLI
  45844. */
  45845. Animation.CreateAndStartHierarchyAnimation = function (name, node, directDescendantsOnly, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  45846. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  45847. if (!animation) {
  45848. return null;
  45849. }
  45850. var scene = node.getScene();
  45851. return scene.beginDirectHierarchyAnimation(node, directDescendantsOnly, [animation], 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  45852. };
  45853. Animation.CreateMergeAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  45854. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  45855. if (!animation) {
  45856. return null;
  45857. }
  45858. node.animations.push(animation);
  45859. return node.getScene().beginAnimation(node, 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  45860. };
  45861. /**
  45862. * Transition property of the Camera to the target Value.
  45863. * @param property The property to transition
  45864. * @param targetValue The target Value of the property
  45865. * @param host The object where the property to animate belongs
  45866. * @param scene Scene used to run the animation
  45867. * @param frameRate Framerate (in frame/s) to use
  45868. * @param transition The transition type we want to use
  45869. * @param duration The duration of the animation, in milliseconds
  45870. * @param onAnimationEnd Call back trigger at the end of the animation.
  45871. */
  45872. Animation.TransitionTo = function (property, targetValue, host, scene, frameRate, transition, duration, onAnimationEnd) {
  45873. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  45874. if (duration <= 0) {
  45875. host[property] = targetValue;
  45876. if (onAnimationEnd) {
  45877. onAnimationEnd();
  45878. }
  45879. return null;
  45880. }
  45881. var endFrame = frameRate * (duration / 1000);
  45882. transition.setKeys([{
  45883. frame: 0,
  45884. value: host[property].clone ? host[property].clone() : host[property]
  45885. },
  45886. {
  45887. frame: endFrame,
  45888. value: targetValue
  45889. }]);
  45890. if (!host.animations) {
  45891. host.animations = [];
  45892. }
  45893. host.animations.push(transition);
  45894. var animation = scene.beginAnimation(host, 0, endFrame, false);
  45895. animation.onAnimationEnd = onAnimationEnd;
  45896. return animation;
  45897. };
  45898. Object.defineProperty(Animation.prototype, "runtimeAnimations", {
  45899. /**
  45900. * Return the array of runtime animations currently using this animation
  45901. */
  45902. get: function () {
  45903. return this._runtimeAnimations;
  45904. },
  45905. enumerable: true,
  45906. configurable: true
  45907. });
  45908. Object.defineProperty(Animation.prototype, "hasRunningRuntimeAnimations", {
  45909. get: function () {
  45910. for (var _i = 0, _a = this._runtimeAnimations; _i < _a.length; _i++) {
  45911. var runtimeAnimation = _a[_i];
  45912. if (!runtimeAnimation.isStopped) {
  45913. return true;
  45914. }
  45915. }
  45916. return false;
  45917. },
  45918. enumerable: true,
  45919. configurable: true
  45920. });
  45921. // Methods
  45922. /**
  45923. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  45924. */
  45925. Animation.prototype.toString = function (fullDetails) {
  45926. var ret = "Name: " + this.name + ", property: " + this.targetProperty;
  45927. ret += ", datatype: " + (["Float", "Vector3", "Quaternion", "Matrix", "Color3", "Vector2"])[this.dataType];
  45928. ret += ", nKeys: " + (this._keys ? this._keys.length : "none");
  45929. ret += ", nRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  45930. if (fullDetails) {
  45931. ret += ", Ranges: {";
  45932. var first = true;
  45933. for (var name in this._ranges) {
  45934. if (first) {
  45935. ret += ", ";
  45936. first = false;
  45937. }
  45938. ret += name;
  45939. }
  45940. ret += "}";
  45941. }
  45942. return ret;
  45943. };
  45944. /**
  45945. * Add an event to this animation.
  45946. */
  45947. Animation.prototype.addEvent = function (event) {
  45948. this._events.push(event);
  45949. };
  45950. /**
  45951. * Remove all events found at the given frame
  45952. * @param frame
  45953. */
  45954. Animation.prototype.removeEvents = function (frame) {
  45955. for (var index = 0; index < this._events.length; index++) {
  45956. if (this._events[index].frame === frame) {
  45957. this._events.splice(index, 1);
  45958. index--;
  45959. }
  45960. }
  45961. };
  45962. Animation.prototype.getEvents = function () {
  45963. return this._events;
  45964. };
  45965. Animation.prototype.createRange = function (name, from, to) {
  45966. // check name not already in use; could happen for bones after serialized
  45967. if (!this._ranges[name]) {
  45968. this._ranges[name] = new AnimationRange(name, from, to);
  45969. }
  45970. };
  45971. Animation.prototype.deleteRange = function (name, deleteFrames) {
  45972. if (deleteFrames === void 0) { deleteFrames = true; }
  45973. var range = this._ranges[name];
  45974. if (!range) {
  45975. return;
  45976. }
  45977. if (deleteFrames) {
  45978. var from = range.from;
  45979. var to = range.to;
  45980. // this loop MUST go high to low for multiple splices to work
  45981. for (var key = this._keys.length - 1; key >= 0; key--) {
  45982. if (this._keys[key].frame >= from && this._keys[key].frame <= to) {
  45983. this._keys.splice(key, 1);
  45984. }
  45985. }
  45986. }
  45987. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  45988. };
  45989. Animation.prototype.getRange = function (name) {
  45990. return this._ranges[name];
  45991. };
  45992. Animation.prototype.getKeys = function () {
  45993. return this._keys;
  45994. };
  45995. Animation.prototype.getHighestFrame = function () {
  45996. var ret = 0;
  45997. for (var key = 0, nKeys = this._keys.length; key < nKeys; key++) {
  45998. if (ret < this._keys[key].frame) {
  45999. ret = this._keys[key].frame;
  46000. }
  46001. }
  46002. return ret;
  46003. };
  46004. Animation.prototype.getEasingFunction = function () {
  46005. return this._easingFunction;
  46006. };
  46007. Animation.prototype.setEasingFunction = function (easingFunction) {
  46008. this._easingFunction = easingFunction;
  46009. };
  46010. Animation.prototype.floatInterpolateFunction = function (startValue, endValue, gradient) {
  46011. return BABYLON.Scalar.Lerp(startValue, endValue, gradient);
  46012. };
  46013. Animation.prototype.floatInterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  46014. return BABYLON.Scalar.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  46015. };
  46016. Animation.prototype.quaternionInterpolateFunction = function (startValue, endValue, gradient) {
  46017. return BABYLON.Quaternion.Slerp(startValue, endValue, gradient);
  46018. };
  46019. Animation.prototype.quaternionInterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  46020. return BABYLON.Quaternion.Hermite(startValue, outTangent, endValue, inTangent, gradient).normalize();
  46021. };
  46022. Animation.prototype.vector3InterpolateFunction = function (startValue, endValue, gradient) {
  46023. return BABYLON.Vector3.Lerp(startValue, endValue, gradient);
  46024. };
  46025. Animation.prototype.vector3InterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  46026. return BABYLON.Vector3.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  46027. };
  46028. Animation.prototype.vector2InterpolateFunction = function (startValue, endValue, gradient) {
  46029. return BABYLON.Vector2.Lerp(startValue, endValue, gradient);
  46030. };
  46031. Animation.prototype.vector2InterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  46032. return BABYLON.Vector2.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  46033. };
  46034. Animation.prototype.sizeInterpolateFunction = function (startValue, endValue, gradient) {
  46035. return BABYLON.Size.Lerp(startValue, endValue, gradient);
  46036. };
  46037. Animation.prototype.color3InterpolateFunction = function (startValue, endValue, gradient) {
  46038. return BABYLON.Color3.Lerp(startValue, endValue, gradient);
  46039. };
  46040. Animation.prototype.matrixInterpolateFunction = function (startValue, endValue, gradient) {
  46041. return BABYLON.Matrix.Lerp(startValue, endValue, gradient);
  46042. };
  46043. Animation.prototype.clone = function () {
  46044. var clone = new Animation(this.name, this.targetPropertyPath.join("."), this.framePerSecond, this.dataType, this.loopMode);
  46045. clone.enableBlending = this.enableBlending;
  46046. clone.blendingSpeed = this.blendingSpeed;
  46047. if (this._keys) {
  46048. clone.setKeys(this._keys);
  46049. }
  46050. if (this._ranges) {
  46051. clone._ranges = {};
  46052. for (var name in this._ranges) {
  46053. var range = this._ranges[name];
  46054. if (!range) {
  46055. continue;
  46056. }
  46057. clone._ranges[name] = range.clone();
  46058. }
  46059. }
  46060. return clone;
  46061. };
  46062. Animation.prototype.setKeys = function (values) {
  46063. this._keys = values.slice(0);
  46064. };
  46065. Animation.prototype.serialize = function () {
  46066. var serializationObject = {};
  46067. serializationObject.name = this.name;
  46068. serializationObject.property = this.targetProperty;
  46069. serializationObject.framePerSecond = this.framePerSecond;
  46070. serializationObject.dataType = this.dataType;
  46071. serializationObject.loopBehavior = this.loopMode;
  46072. serializationObject.enableBlending = this.enableBlending;
  46073. serializationObject.blendingSpeed = this.blendingSpeed;
  46074. var dataType = this.dataType;
  46075. serializationObject.keys = [];
  46076. var keys = this.getKeys();
  46077. for (var index = 0; index < keys.length; index++) {
  46078. var animationKey = keys[index];
  46079. var key = {};
  46080. key.frame = animationKey.frame;
  46081. switch (dataType) {
  46082. case Animation.ANIMATIONTYPE_FLOAT:
  46083. key.values = [animationKey.value];
  46084. break;
  46085. case Animation.ANIMATIONTYPE_QUATERNION:
  46086. case Animation.ANIMATIONTYPE_MATRIX:
  46087. case Animation.ANIMATIONTYPE_VECTOR3:
  46088. case Animation.ANIMATIONTYPE_COLOR3:
  46089. key.values = animationKey.value.asArray();
  46090. break;
  46091. }
  46092. serializationObject.keys.push(key);
  46093. }
  46094. serializationObject.ranges = [];
  46095. for (var name in this._ranges) {
  46096. var source = this._ranges[name];
  46097. if (!source) {
  46098. continue;
  46099. }
  46100. var range = {};
  46101. range.name = name;
  46102. range.from = source.from;
  46103. range.to = source.to;
  46104. serializationObject.ranges.push(range);
  46105. }
  46106. return serializationObject;
  46107. };
  46108. Object.defineProperty(Animation, "ANIMATIONTYPE_FLOAT", {
  46109. get: function () {
  46110. return Animation._ANIMATIONTYPE_FLOAT;
  46111. },
  46112. enumerable: true,
  46113. configurable: true
  46114. });
  46115. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR3", {
  46116. get: function () {
  46117. return Animation._ANIMATIONTYPE_VECTOR3;
  46118. },
  46119. enumerable: true,
  46120. configurable: true
  46121. });
  46122. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR2", {
  46123. get: function () {
  46124. return Animation._ANIMATIONTYPE_VECTOR2;
  46125. },
  46126. enumerable: true,
  46127. configurable: true
  46128. });
  46129. Object.defineProperty(Animation, "ANIMATIONTYPE_SIZE", {
  46130. get: function () {
  46131. return Animation._ANIMATIONTYPE_SIZE;
  46132. },
  46133. enumerable: true,
  46134. configurable: true
  46135. });
  46136. Object.defineProperty(Animation, "ANIMATIONTYPE_QUATERNION", {
  46137. get: function () {
  46138. return Animation._ANIMATIONTYPE_QUATERNION;
  46139. },
  46140. enumerable: true,
  46141. configurable: true
  46142. });
  46143. Object.defineProperty(Animation, "ANIMATIONTYPE_MATRIX", {
  46144. get: function () {
  46145. return Animation._ANIMATIONTYPE_MATRIX;
  46146. },
  46147. enumerable: true,
  46148. configurable: true
  46149. });
  46150. Object.defineProperty(Animation, "ANIMATIONTYPE_COLOR3", {
  46151. get: function () {
  46152. return Animation._ANIMATIONTYPE_COLOR3;
  46153. },
  46154. enumerable: true,
  46155. configurable: true
  46156. });
  46157. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_RELATIVE", {
  46158. get: function () {
  46159. return Animation._ANIMATIONLOOPMODE_RELATIVE;
  46160. },
  46161. enumerable: true,
  46162. configurable: true
  46163. });
  46164. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CYCLE", {
  46165. get: function () {
  46166. return Animation._ANIMATIONLOOPMODE_CYCLE;
  46167. },
  46168. enumerable: true,
  46169. configurable: true
  46170. });
  46171. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CONSTANT", {
  46172. get: function () {
  46173. return Animation._ANIMATIONLOOPMODE_CONSTANT;
  46174. },
  46175. enumerable: true,
  46176. configurable: true
  46177. });
  46178. Animation.Parse = function (parsedAnimation) {
  46179. var animation = new Animation(parsedAnimation.name, parsedAnimation.property, parsedAnimation.framePerSecond, parsedAnimation.dataType, parsedAnimation.loopBehavior);
  46180. var dataType = parsedAnimation.dataType;
  46181. var keys = [];
  46182. var data;
  46183. var index;
  46184. if (parsedAnimation.enableBlending) {
  46185. animation.enableBlending = parsedAnimation.enableBlending;
  46186. }
  46187. if (parsedAnimation.blendingSpeed) {
  46188. animation.blendingSpeed = parsedAnimation.blendingSpeed;
  46189. }
  46190. for (index = 0; index < parsedAnimation.keys.length; index++) {
  46191. var key = parsedAnimation.keys[index];
  46192. var inTangent;
  46193. var outTangent;
  46194. switch (dataType) {
  46195. case Animation.ANIMATIONTYPE_FLOAT:
  46196. data = key.values[0];
  46197. if (key.values.length >= 1) {
  46198. inTangent = key.values[1];
  46199. }
  46200. if (key.values.length >= 2) {
  46201. outTangent = key.values[2];
  46202. }
  46203. break;
  46204. case Animation.ANIMATIONTYPE_QUATERNION:
  46205. data = BABYLON.Quaternion.FromArray(key.values);
  46206. if (key.values.length >= 8) {
  46207. var _inTangent = BABYLON.Quaternion.FromArray(key.values.slice(4, 8));
  46208. if (!_inTangent.equals(BABYLON.Quaternion.Zero())) {
  46209. inTangent = _inTangent;
  46210. }
  46211. }
  46212. if (key.values.length >= 12) {
  46213. var _outTangent = BABYLON.Quaternion.FromArray(key.values.slice(8, 12));
  46214. if (!_outTangent.equals(BABYLON.Quaternion.Zero())) {
  46215. outTangent = _outTangent;
  46216. }
  46217. }
  46218. break;
  46219. case Animation.ANIMATIONTYPE_MATRIX:
  46220. data = BABYLON.Matrix.FromArray(key.values);
  46221. break;
  46222. case Animation.ANIMATIONTYPE_COLOR3:
  46223. data = BABYLON.Color3.FromArray(key.values);
  46224. break;
  46225. case Animation.ANIMATIONTYPE_VECTOR3:
  46226. default:
  46227. data = BABYLON.Vector3.FromArray(key.values);
  46228. break;
  46229. }
  46230. var keyData = {};
  46231. keyData.frame = key.frame;
  46232. keyData.value = data;
  46233. if (inTangent != undefined) {
  46234. keyData.inTangent = inTangent;
  46235. }
  46236. if (outTangent != undefined) {
  46237. keyData.outTangent = outTangent;
  46238. }
  46239. keys.push(keyData);
  46240. }
  46241. animation.setKeys(keys);
  46242. if (parsedAnimation.ranges) {
  46243. for (index = 0; index < parsedAnimation.ranges.length; index++) {
  46244. data = parsedAnimation.ranges[index];
  46245. animation.createRange(data.name, data.from, data.to);
  46246. }
  46247. }
  46248. return animation;
  46249. };
  46250. Animation.AppendSerializedAnimations = function (source, destination) {
  46251. if (source.animations) {
  46252. destination.animations = [];
  46253. for (var animationIndex = 0; animationIndex < source.animations.length; animationIndex++) {
  46254. var animation = source.animations[animationIndex];
  46255. destination.animations.push(animation.serialize());
  46256. }
  46257. }
  46258. };
  46259. Animation.AllowMatricesInterpolation = false;
  46260. // Statics
  46261. Animation._ANIMATIONTYPE_FLOAT = 0;
  46262. Animation._ANIMATIONTYPE_VECTOR3 = 1;
  46263. Animation._ANIMATIONTYPE_QUATERNION = 2;
  46264. Animation._ANIMATIONTYPE_MATRIX = 3;
  46265. Animation._ANIMATIONTYPE_COLOR3 = 4;
  46266. Animation._ANIMATIONTYPE_VECTOR2 = 5;
  46267. Animation._ANIMATIONTYPE_SIZE = 6;
  46268. Animation._ANIMATIONLOOPMODE_RELATIVE = 0;
  46269. Animation._ANIMATIONLOOPMODE_CYCLE = 1;
  46270. Animation._ANIMATIONLOOPMODE_CONSTANT = 2;
  46271. return Animation;
  46272. }());
  46273. BABYLON.Animation = Animation;
  46274. })(BABYLON || (BABYLON = {}));
  46275. //# sourceMappingURL=babylon.animation.js.map
  46276. var BABYLON;
  46277. (function (BABYLON) {
  46278. /**
  46279. * This class defines the direct association between an animation and a target
  46280. */
  46281. var TargetedAnimation = /** @class */ (function () {
  46282. function TargetedAnimation() {
  46283. }
  46284. return TargetedAnimation;
  46285. }());
  46286. BABYLON.TargetedAnimation = TargetedAnimation;
  46287. /**
  46288. * Use this class to create coordinated animations on multiple targets
  46289. */
  46290. var AnimationGroup = /** @class */ (function () {
  46291. function AnimationGroup(name, scene) {
  46292. if (scene === void 0) { scene = null; }
  46293. this.name = name;
  46294. this._targetedAnimations = new Array();
  46295. this._animatables = new Array();
  46296. this._from = Number.MAX_VALUE;
  46297. this._to = -Number.MAX_VALUE;
  46298. this._speedRatio = 1;
  46299. this.onAnimationEndObservable = new BABYLON.Observable();
  46300. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  46301. this._scene.animationGroups.push(this);
  46302. }
  46303. Object.defineProperty(AnimationGroup.prototype, "isStarted", {
  46304. /**
  46305. * Define if the animations are started
  46306. */
  46307. get: function () {
  46308. return this._isStarted;
  46309. },
  46310. enumerable: true,
  46311. configurable: true
  46312. });
  46313. Object.defineProperty(AnimationGroup.prototype, "speedRatio", {
  46314. /**
  46315. * Gets or sets the speed ratio to use for all animations
  46316. */
  46317. get: function () {
  46318. return this._speedRatio;
  46319. },
  46320. /**
  46321. * Gets or sets the speed ratio to use for all animations
  46322. */
  46323. set: function (value) {
  46324. if (this._speedRatio === value) {
  46325. return;
  46326. }
  46327. this._speedRatio = value;
  46328. for (var index = 0; index < this._animatables.length; index++) {
  46329. var animatable = this._animatables[index];
  46330. animatable.speedRatio = this._speedRatio;
  46331. }
  46332. },
  46333. enumerable: true,
  46334. configurable: true
  46335. });
  46336. Object.defineProperty(AnimationGroup.prototype, "targetedAnimations", {
  46337. /**
  46338. * Gets the targeted animations for this animation group
  46339. */
  46340. get: function () {
  46341. return this._targetedAnimations;
  46342. },
  46343. enumerable: true,
  46344. configurable: true
  46345. });
  46346. /**
  46347. * Add an animation (with its target) in the group
  46348. * @param animation defines the animation we want to add
  46349. * @param target defines the target of the animation
  46350. * @returns the {BABYLON.TargetedAnimation} object
  46351. */
  46352. AnimationGroup.prototype.addTargetedAnimation = function (animation, target) {
  46353. var targetedAnimation = {
  46354. animation: animation,
  46355. target: target
  46356. };
  46357. var keys = animation.getKeys();
  46358. if (this._from > keys[0].frame) {
  46359. this._from = keys[0].frame;
  46360. }
  46361. if (this._to < keys[keys.length - 1].frame) {
  46362. this._to = keys[keys.length - 1].frame;
  46363. }
  46364. this._targetedAnimations.push(targetedAnimation);
  46365. return targetedAnimation;
  46366. };
  46367. /**
  46368. * This function will normalize every animation in the group to make sure they all go from beginFrame to endFrame
  46369. * It can add constant keys at begin or end
  46370. * @param beginFrame defines the new begin frame for all animations. It can't be bigger than the smallest begin frame of all animations
  46371. * @param endFrame defines the new end frame for all animations. It can't be smaller than the largest end frame of all animations
  46372. */
  46373. AnimationGroup.prototype.normalize = function (beginFrame, endFrame) {
  46374. if (beginFrame === void 0) { beginFrame = -Number.MAX_VALUE; }
  46375. if (endFrame === void 0) { endFrame = Number.MAX_VALUE; }
  46376. beginFrame = Math.max(beginFrame, this._from);
  46377. endFrame = Math.min(endFrame, this._to);
  46378. for (var index = 0; index < this._targetedAnimations.length; index++) {
  46379. var targetedAnimation = this._targetedAnimations[index];
  46380. var keys = targetedAnimation.animation.getKeys();
  46381. var startKey = keys[0];
  46382. var endKey = keys[keys.length - 1];
  46383. if (startKey.frame > beginFrame) {
  46384. var newKey = {
  46385. frame: beginFrame,
  46386. value: startKey.value,
  46387. inTangent: startKey.inTangent,
  46388. outTangent: startKey.outTangent,
  46389. interpolation: startKey.interpolation
  46390. };
  46391. keys.splice(0, 0, newKey);
  46392. }
  46393. if (endKey.frame < endFrame) {
  46394. var newKey = {
  46395. frame: endFrame,
  46396. value: endKey.value,
  46397. inTangent: endKey.outTangent,
  46398. outTangent: endKey.outTangent,
  46399. interpolation: endKey.interpolation
  46400. };
  46401. keys.push(newKey);
  46402. }
  46403. }
  46404. return this;
  46405. };
  46406. /**
  46407. * Start all animations on given targets
  46408. * @param loop defines if animations must loop
  46409. * @param speedRatio defines the ratio to apply to animation speed (1 by default)
  46410. */
  46411. AnimationGroup.prototype.start = function (loop, speedRatio) {
  46412. var _this = this;
  46413. if (loop === void 0) { loop = false; }
  46414. if (speedRatio === void 0) { speedRatio = 1; }
  46415. if (this._isStarted || this._targetedAnimations.length === 0) {
  46416. return this;
  46417. }
  46418. var _loop_1 = function () {
  46419. var targetedAnimation = this_1._targetedAnimations[index];
  46420. this_1._animatables.push(this_1._scene.beginDirectAnimation(targetedAnimation.target, [targetedAnimation.animation], this_1._from, this_1._to, loop, speedRatio, function () {
  46421. _this.onAnimationEndObservable.notifyObservers(targetedAnimation);
  46422. }));
  46423. };
  46424. var this_1 = this;
  46425. for (var index = 0; index < this._targetedAnimations.length; index++) {
  46426. _loop_1();
  46427. }
  46428. this._speedRatio = speedRatio;
  46429. this._isStarted = true;
  46430. return this;
  46431. };
  46432. /**
  46433. * Pause all animations
  46434. */
  46435. AnimationGroup.prototype.pause = function () {
  46436. if (!this._isStarted) {
  46437. return this;
  46438. }
  46439. for (var index = 0; index < this._animatables.length; index++) {
  46440. var animatable = this._animatables[index];
  46441. animatable.pause();
  46442. }
  46443. return this;
  46444. };
  46445. /**
  46446. * Play all animations to initial state
  46447. * This function will start() the animations if they were not started or will restart() them if they were paused
  46448. * @param loop defines if animations must loop
  46449. */
  46450. AnimationGroup.prototype.play = function (loop) {
  46451. if (this.isStarted) {
  46452. if (loop !== undefined) {
  46453. for (var index = 0; index < this._animatables.length; index++) {
  46454. var animatable = this._animatables[index];
  46455. animatable.loopAnimation = loop;
  46456. }
  46457. }
  46458. this.restart();
  46459. }
  46460. else {
  46461. this.start(loop, this._speedRatio);
  46462. }
  46463. return this;
  46464. };
  46465. /**
  46466. * Reset all animations to initial state
  46467. */
  46468. AnimationGroup.prototype.reset = function () {
  46469. if (!this._isStarted) {
  46470. return this;
  46471. }
  46472. for (var index = 0; index < this._animatables.length; index++) {
  46473. var animatable = this._animatables[index];
  46474. animatable.reset();
  46475. }
  46476. return this;
  46477. };
  46478. /**
  46479. * Restart animations from key 0
  46480. */
  46481. AnimationGroup.prototype.restart = function () {
  46482. if (!this._isStarted) {
  46483. return this;
  46484. }
  46485. for (var index = 0; index < this._animatables.length; index++) {
  46486. var animatable = this._animatables[index];
  46487. animatable.restart();
  46488. }
  46489. return this;
  46490. };
  46491. /**
  46492. * Stop all animations
  46493. */
  46494. AnimationGroup.prototype.stop = function () {
  46495. if (!this._isStarted) {
  46496. return this;
  46497. }
  46498. for (var index = 0; index < this._animatables.length; index++) {
  46499. var animatable = this._animatables[index];
  46500. animatable.stop();
  46501. }
  46502. this._isStarted = false;
  46503. return this;
  46504. };
  46505. /**
  46506. * Dispose all associated resources
  46507. */
  46508. AnimationGroup.prototype.dispose = function () {
  46509. this._targetedAnimations = [];
  46510. this._animatables = [];
  46511. var index = this._scene.animationGroups.indexOf(this);
  46512. if (index > -1) {
  46513. this._scene.animationGroups.splice(index, 1);
  46514. }
  46515. };
  46516. return AnimationGroup;
  46517. }());
  46518. BABYLON.AnimationGroup = AnimationGroup;
  46519. })(BABYLON || (BABYLON = {}));
  46520. //# sourceMappingURL=babylon.animationGroup.js.map
  46521. var BABYLON;
  46522. (function (BABYLON) {
  46523. var RuntimeAnimation = /** @class */ (function () {
  46524. function RuntimeAnimation(target, animation) {
  46525. this._offsetsCache = {};
  46526. this._highLimitsCache = {};
  46527. this._stopped = false;
  46528. this._blendingFactor = 0;
  46529. this._ratioOffset = 0;
  46530. this._animation = animation;
  46531. this._target = target;
  46532. animation._runtimeAnimations.push(this);
  46533. }
  46534. Object.defineProperty(RuntimeAnimation.prototype, "animation", {
  46535. get: function () {
  46536. return this._animation;
  46537. },
  46538. enumerable: true,
  46539. configurable: true
  46540. });
  46541. RuntimeAnimation.prototype.reset = function () {
  46542. this._offsetsCache = {};
  46543. this._highLimitsCache = {};
  46544. this.currentFrame = 0;
  46545. this._blendingFactor = 0;
  46546. this._originalBlendValue = null;
  46547. };
  46548. RuntimeAnimation.prototype.isStopped = function () {
  46549. return this._stopped;
  46550. };
  46551. RuntimeAnimation.prototype.dispose = function () {
  46552. var index = this._animation.runtimeAnimations.indexOf(this);
  46553. if (index > -1) {
  46554. this._animation.runtimeAnimations.splice(index, 1);
  46555. }
  46556. };
  46557. RuntimeAnimation.prototype._getKeyValue = function (value) {
  46558. if (typeof value === "function") {
  46559. return value();
  46560. }
  46561. return value;
  46562. };
  46563. RuntimeAnimation.prototype._interpolate = function (currentFrame, repeatCount, loopMode, offsetValue, highLimitValue) {
  46564. if (loopMode === BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT && repeatCount > 0) {
  46565. return highLimitValue.clone ? highLimitValue.clone() : highLimitValue;
  46566. }
  46567. this.currentFrame = currentFrame;
  46568. var keys = this._animation.getKeys();
  46569. // Try to get a hash to find the right key
  46570. 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));
  46571. if (keys[startKeyIndex].frame >= currentFrame) {
  46572. while (startKeyIndex - 1 >= 0 && keys[startKeyIndex].frame >= currentFrame) {
  46573. startKeyIndex--;
  46574. }
  46575. }
  46576. for (var key = startKeyIndex; key < keys.length; key++) {
  46577. var endKey = keys[key + 1];
  46578. if (endKey.frame >= currentFrame) {
  46579. var startKey = keys[key];
  46580. var startValue = this._getKeyValue(startKey.value);
  46581. if (startKey.interpolation === BABYLON.AnimationKeyInterpolation.STEP) {
  46582. return startValue;
  46583. }
  46584. var endValue = this._getKeyValue(endKey.value);
  46585. var useTangent = startKey.outTangent !== undefined && endKey.inTangent !== undefined;
  46586. var frameDelta = endKey.frame - startKey.frame;
  46587. // gradient : percent of currentFrame between the frame inf and the frame sup
  46588. var gradient = (currentFrame - startKey.frame) / frameDelta;
  46589. // check for easingFunction and correction of gradient
  46590. var easingFunction = this._animation.getEasingFunction();
  46591. if (easingFunction != null) {
  46592. gradient = easingFunction.ease(gradient);
  46593. }
  46594. switch (this._animation.dataType) {
  46595. // Float
  46596. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  46597. var floatValue = useTangent ? this._animation.floatInterpolateFunctionWithTangents(startValue, startKey.outTangent * frameDelta, endValue, endKey.inTangent * frameDelta, gradient) : this._animation.floatInterpolateFunction(startValue, endValue, gradient);
  46598. switch (loopMode) {
  46599. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  46600. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  46601. return floatValue;
  46602. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  46603. return offsetValue * repeatCount + floatValue;
  46604. }
  46605. break;
  46606. // Quaternion
  46607. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  46608. var quatValue = useTangent ? this._animation.quaternionInterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this._animation.quaternionInterpolateFunction(startValue, endValue, gradient);
  46609. switch (loopMode) {
  46610. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  46611. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  46612. return quatValue;
  46613. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  46614. return quatValue.add(offsetValue.scale(repeatCount));
  46615. }
  46616. return quatValue;
  46617. // Vector3
  46618. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  46619. var vec3Value = useTangent ? this._animation.vector3InterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this._animation.vector3InterpolateFunction(startValue, endValue, gradient);
  46620. switch (loopMode) {
  46621. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  46622. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  46623. return vec3Value;
  46624. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  46625. return vec3Value.add(offsetValue.scale(repeatCount));
  46626. }
  46627. // Vector2
  46628. case BABYLON.Animation.ANIMATIONTYPE_VECTOR2:
  46629. var vec2Value = useTangent ? this._animation.vector2InterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this._animation.vector2InterpolateFunction(startValue, endValue, gradient);
  46630. switch (loopMode) {
  46631. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  46632. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  46633. return vec2Value;
  46634. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  46635. return vec2Value.add(offsetValue.scale(repeatCount));
  46636. }
  46637. // Size
  46638. case BABYLON.Animation.ANIMATIONTYPE_SIZE:
  46639. switch (loopMode) {
  46640. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  46641. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  46642. return this._animation.sizeInterpolateFunction(startValue, endValue, gradient);
  46643. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  46644. return this._animation.sizeInterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  46645. }
  46646. // Color3
  46647. case BABYLON.Animation.ANIMATIONTYPE_COLOR3:
  46648. switch (loopMode) {
  46649. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  46650. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  46651. return this._animation.color3InterpolateFunction(startValue, endValue, gradient);
  46652. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  46653. return this._animation.color3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  46654. }
  46655. // Matrix
  46656. case BABYLON.Animation.ANIMATIONTYPE_MATRIX:
  46657. switch (loopMode) {
  46658. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  46659. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  46660. if (BABYLON.Animation.AllowMatricesInterpolation) {
  46661. return this._animation.matrixInterpolateFunction(startValue, endValue, gradient);
  46662. }
  46663. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  46664. return startValue;
  46665. }
  46666. default:
  46667. break;
  46668. }
  46669. break;
  46670. }
  46671. }
  46672. return this._getKeyValue(keys[keys.length - 1].value);
  46673. };
  46674. RuntimeAnimation.prototype.setValue = function (currentValue, blend) {
  46675. if (blend === void 0) { blend = false; }
  46676. // Set value
  46677. var path;
  46678. var destination;
  46679. var targetPropertyPath = this._animation.targetPropertyPath;
  46680. if (targetPropertyPath.length > 1) {
  46681. var property = this._target[targetPropertyPath[0]];
  46682. for (var index = 1; index < targetPropertyPath.length - 1; index++) {
  46683. property = property[targetPropertyPath[index]];
  46684. }
  46685. path = targetPropertyPath[targetPropertyPath.length - 1];
  46686. destination = property;
  46687. }
  46688. else {
  46689. path = targetPropertyPath[0];
  46690. destination = this._target;
  46691. }
  46692. // Blending
  46693. if (this._animation.enableBlending && this._blendingFactor <= 1.0) {
  46694. if (!this._originalBlendValue) {
  46695. if (destination[path].clone) {
  46696. this._originalBlendValue = destination[path].clone();
  46697. }
  46698. else {
  46699. this._originalBlendValue = destination[path];
  46700. }
  46701. }
  46702. if (this._originalBlendValue.prototype) {
  46703. if (this._originalBlendValue.prototype.Lerp) {
  46704. destination[path] = this._originalBlendValue.construtor.prototype.Lerp(currentValue, this._originalBlendValue, this._blendingFactor);
  46705. }
  46706. else {
  46707. destination[path] = currentValue;
  46708. }
  46709. }
  46710. else if (this._originalBlendValue.m) {
  46711. destination[path] = BABYLON.Matrix.Lerp(this._originalBlendValue, currentValue, this._blendingFactor);
  46712. }
  46713. else {
  46714. destination[path] = this._originalBlendValue * (1.0 - this._blendingFactor) + this._blendingFactor * currentValue;
  46715. }
  46716. this._blendingFactor += this._animation.blendingSpeed;
  46717. }
  46718. else {
  46719. destination[path] = currentValue;
  46720. }
  46721. if (this._target.markAsDirty) {
  46722. this._target.markAsDirty(this._animation.targetProperty);
  46723. }
  46724. };
  46725. RuntimeAnimation.prototype.goToFrame = function (frame) {
  46726. var keys = this._animation.getKeys();
  46727. if (frame < keys[0].frame) {
  46728. frame = keys[0].frame;
  46729. }
  46730. else if (frame > keys[keys.length - 1].frame) {
  46731. frame = keys[keys.length - 1].frame;
  46732. }
  46733. var currentValue = this._interpolate(frame, 0, this._animation.loopMode);
  46734. this.setValue(currentValue);
  46735. };
  46736. RuntimeAnimation.prototype._prepareForSpeedRatioChange = function (newSpeedRatio) {
  46737. var newRatio = this._previousDelay * (this._animation.framePerSecond * newSpeedRatio) / 1000.0;
  46738. this._ratioOffset = this._previousRatio - newRatio;
  46739. };
  46740. RuntimeAnimation.prototype.animate = function (delay, from, to, loop, speedRatio, blend) {
  46741. if (blend === void 0) { blend = false; }
  46742. var targetPropertyPath = this._animation.targetPropertyPath;
  46743. if (!targetPropertyPath || targetPropertyPath.length < 1) {
  46744. this._stopped = true;
  46745. return false;
  46746. }
  46747. var returnValue = true;
  46748. var keys = this._animation.getKeys();
  46749. // Adding a start key at frame 0 if missing
  46750. if (keys[0].frame !== 0) {
  46751. var newKey = { frame: 0, value: keys[0].value };
  46752. keys.splice(0, 0, newKey);
  46753. }
  46754. // Check limits
  46755. if (from < keys[0].frame || from > keys[keys.length - 1].frame) {
  46756. from = keys[0].frame;
  46757. }
  46758. if (to < keys[0].frame || to > keys[keys.length - 1].frame) {
  46759. to = keys[keys.length - 1].frame;
  46760. }
  46761. //to and from cannot be the same key
  46762. if (from === to) {
  46763. if (from > keys[0].frame) {
  46764. from--;
  46765. }
  46766. else if (to < keys[keys.length - 1].frame) {
  46767. to++;
  46768. }
  46769. }
  46770. // Compute ratio
  46771. var range = to - from;
  46772. var offsetValue;
  46773. // ratio represents the frame delta between from and to
  46774. var ratio = (delay * (this._animation.framePerSecond * speedRatio) / 1000.0) + this._ratioOffset;
  46775. var highLimitValue = 0;
  46776. this._previousDelay = delay;
  46777. this._previousRatio = ratio;
  46778. if (((to > from && ratio > range) || (from > to && ratio < range)) && !loop) {
  46779. returnValue = false;
  46780. highLimitValue = this._getKeyValue(keys[keys.length - 1].value);
  46781. }
  46782. else {
  46783. // Get max value if required
  46784. if (this._animation.loopMode !== BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE) {
  46785. var keyOffset = to.toString() + from.toString();
  46786. if (!this._offsetsCache[keyOffset]) {
  46787. var fromValue = this._interpolate(from, 0, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  46788. var toValue = this._interpolate(to, 0, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  46789. switch (this._animation.dataType) {
  46790. // Float
  46791. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  46792. this._offsetsCache[keyOffset] = toValue - fromValue;
  46793. break;
  46794. // Quaternion
  46795. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  46796. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  46797. break;
  46798. // Vector3
  46799. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  46800. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  46801. // Vector2
  46802. case BABYLON.Animation.ANIMATIONTYPE_VECTOR2:
  46803. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  46804. // Size
  46805. case BABYLON.Animation.ANIMATIONTYPE_SIZE:
  46806. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  46807. // Color3
  46808. case BABYLON.Animation.ANIMATIONTYPE_COLOR3:
  46809. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  46810. default:
  46811. break;
  46812. }
  46813. this._highLimitsCache[keyOffset] = toValue;
  46814. }
  46815. highLimitValue = this._highLimitsCache[keyOffset];
  46816. offsetValue = this._offsetsCache[keyOffset];
  46817. }
  46818. }
  46819. if (offsetValue === undefined) {
  46820. switch (this._animation.dataType) {
  46821. // Float
  46822. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  46823. offsetValue = 0;
  46824. break;
  46825. // Quaternion
  46826. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  46827. offsetValue = new BABYLON.Quaternion(0, 0, 0, 0);
  46828. break;
  46829. // Vector3
  46830. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  46831. offsetValue = BABYLON.Vector3.Zero();
  46832. break;
  46833. // Vector2
  46834. case BABYLON.Animation.ANIMATIONTYPE_VECTOR2:
  46835. offsetValue = BABYLON.Vector2.Zero();
  46836. break;
  46837. // Size
  46838. case BABYLON.Animation.ANIMATIONTYPE_SIZE:
  46839. offsetValue = BABYLON.Size.Zero();
  46840. break;
  46841. // Color3
  46842. case BABYLON.Animation.ANIMATIONTYPE_COLOR3:
  46843. offsetValue = BABYLON.Color3.Black();
  46844. }
  46845. }
  46846. // Compute value
  46847. var repeatCount = (ratio / range) >> 0;
  46848. var currentFrame = returnValue ? from + ratio % range : to;
  46849. var currentValue = this._interpolate(currentFrame, repeatCount, this._animation.loopMode, offsetValue, highLimitValue);
  46850. // Set value
  46851. this.setValue(currentValue);
  46852. // Check events
  46853. var events = this._animation.getEvents();
  46854. for (var index = 0; index < events.length; index++) {
  46855. // Make sure current frame has passed event frame and that event frame is within the current range
  46856. // Also, handle both forward and reverse animations
  46857. if ((range > 0 && currentFrame >= events[index].frame && events[index].frame >= from) ||
  46858. (range < 0 && currentFrame <= events[index].frame && events[index].frame <= from)) {
  46859. var event = events[index];
  46860. if (!event.isDone) {
  46861. // If event should be done only once, remove it.
  46862. if (event.onlyOnce) {
  46863. events.splice(index, 1);
  46864. index--;
  46865. }
  46866. event.isDone = true;
  46867. event.action();
  46868. } // Don't do anything if the event has already be done.
  46869. }
  46870. else if (events[index].isDone && !events[index].onlyOnce) {
  46871. // reset event, the animation is looping
  46872. events[index].isDone = false;
  46873. }
  46874. }
  46875. if (!returnValue) {
  46876. this._stopped = true;
  46877. }
  46878. return returnValue;
  46879. };
  46880. return RuntimeAnimation;
  46881. }());
  46882. BABYLON.RuntimeAnimation = RuntimeAnimation;
  46883. })(BABYLON || (BABYLON = {}));
  46884. //# sourceMappingURL=babylon.runtimeAnimation.js.map
  46885. var BABYLON;
  46886. (function (BABYLON) {
  46887. var Animatable = /** @class */ (function () {
  46888. function Animatable(scene, target, fromFrame, toFrame, loopAnimation, speedRatio, onAnimationEnd, animations) {
  46889. if (fromFrame === void 0) { fromFrame = 0; }
  46890. if (toFrame === void 0) { toFrame = 100; }
  46891. if (loopAnimation === void 0) { loopAnimation = false; }
  46892. if (speedRatio === void 0) { speedRatio = 1.0; }
  46893. this.target = target;
  46894. this.fromFrame = fromFrame;
  46895. this.toFrame = toFrame;
  46896. this.loopAnimation = loopAnimation;
  46897. this.onAnimationEnd = onAnimationEnd;
  46898. this._localDelayOffset = null;
  46899. this._pausedDelay = null;
  46900. this._runtimeAnimations = new Array();
  46901. this._paused = false;
  46902. this._speedRatio = 1;
  46903. this.animationStarted = false;
  46904. if (animations) {
  46905. this.appendAnimations(target, animations);
  46906. }
  46907. this._speedRatio = speedRatio;
  46908. this._scene = scene;
  46909. scene._activeAnimatables.push(this);
  46910. }
  46911. Object.defineProperty(Animatable.prototype, "speedRatio", {
  46912. get: function () {
  46913. return this._speedRatio;
  46914. },
  46915. set: function (value) {
  46916. for (var index = 0; index < this._runtimeAnimations.length; index++) {
  46917. var animation = this._runtimeAnimations[index];
  46918. animation._prepareForSpeedRatioChange(value);
  46919. }
  46920. this._speedRatio = value;
  46921. },
  46922. enumerable: true,
  46923. configurable: true
  46924. });
  46925. // Methods
  46926. Animatable.prototype.getAnimations = function () {
  46927. return this._runtimeAnimations;
  46928. };
  46929. Animatable.prototype.appendAnimations = function (target, animations) {
  46930. for (var index = 0; index < animations.length; index++) {
  46931. var animation = animations[index];
  46932. this._runtimeAnimations.push(new BABYLON.RuntimeAnimation(target, animation));
  46933. }
  46934. };
  46935. Animatable.prototype.getAnimationByTargetProperty = function (property) {
  46936. var runtimeAnimations = this._runtimeAnimations;
  46937. for (var index = 0; index < runtimeAnimations.length; index++) {
  46938. if (runtimeAnimations[index].animation.targetProperty === property) {
  46939. return runtimeAnimations[index].animation;
  46940. }
  46941. }
  46942. return null;
  46943. };
  46944. Animatable.prototype.getRuntimeAnimationByTargetProperty = function (property) {
  46945. var runtimeAnimations = this._runtimeAnimations;
  46946. for (var index = 0; index < runtimeAnimations.length; index++) {
  46947. if (runtimeAnimations[index].animation.targetProperty === property) {
  46948. return runtimeAnimations[index];
  46949. }
  46950. }
  46951. return null;
  46952. };
  46953. Animatable.prototype.reset = function () {
  46954. var runtimeAnimations = this._runtimeAnimations;
  46955. for (var index = 0; index < runtimeAnimations.length; index++) {
  46956. runtimeAnimations[index].reset();
  46957. }
  46958. // Reset to original value
  46959. for (index = 0; index < runtimeAnimations.length; index++) {
  46960. var animation = runtimeAnimations[index];
  46961. animation.animate(0, this.fromFrame, this.toFrame, false, this._speedRatio);
  46962. }
  46963. this._localDelayOffset = null;
  46964. this._pausedDelay = null;
  46965. };
  46966. Animatable.prototype.enableBlending = function (blendingSpeed) {
  46967. var runtimeAnimations = this._runtimeAnimations;
  46968. for (var index = 0; index < runtimeAnimations.length; index++) {
  46969. runtimeAnimations[index].animation.enableBlending = true;
  46970. runtimeAnimations[index].animation.blendingSpeed = blendingSpeed;
  46971. }
  46972. };
  46973. Animatable.prototype.disableBlending = function () {
  46974. var runtimeAnimations = this._runtimeAnimations;
  46975. for (var index = 0; index < runtimeAnimations.length; index++) {
  46976. runtimeAnimations[index].animation.enableBlending = false;
  46977. }
  46978. };
  46979. Animatable.prototype.goToFrame = function (frame) {
  46980. var runtimeAnimations = this._runtimeAnimations;
  46981. if (runtimeAnimations[0]) {
  46982. var fps = runtimeAnimations[0].animation.framePerSecond;
  46983. var currentFrame = runtimeAnimations[0].currentFrame;
  46984. var adjustTime = frame - currentFrame;
  46985. var delay = adjustTime * 1000 / (fps * this.speedRatio);
  46986. if (this._localDelayOffset === null) {
  46987. this._localDelayOffset = 0;
  46988. }
  46989. this._localDelayOffset -= delay;
  46990. }
  46991. for (var index = 0; index < runtimeAnimations.length; index++) {
  46992. runtimeAnimations[index].goToFrame(frame);
  46993. }
  46994. };
  46995. Animatable.prototype.pause = function () {
  46996. if (this._paused) {
  46997. return;
  46998. }
  46999. this._paused = true;
  47000. };
  47001. Animatable.prototype.restart = function () {
  47002. this._paused = false;
  47003. };
  47004. Animatable.prototype.stop = function (animationName) {
  47005. if (animationName) {
  47006. var idx = this._scene._activeAnimatables.indexOf(this);
  47007. if (idx > -1) {
  47008. var runtimeAnimations = this._runtimeAnimations;
  47009. for (var index = runtimeAnimations.length - 1; index >= 0; index--) {
  47010. if (typeof animationName === "string" && runtimeAnimations[index].animation.name != animationName) {
  47011. continue;
  47012. }
  47013. runtimeAnimations[index].dispose();
  47014. runtimeAnimations.splice(index, 1);
  47015. }
  47016. if (runtimeAnimations.length == 0) {
  47017. this._scene._activeAnimatables.splice(idx, 1);
  47018. if (this.onAnimationEnd) {
  47019. this.onAnimationEnd();
  47020. }
  47021. }
  47022. }
  47023. }
  47024. else {
  47025. var index = this._scene._activeAnimatables.indexOf(this);
  47026. if (index > -1) {
  47027. this._scene._activeAnimatables.splice(index, 1);
  47028. var runtimeAnimations = this._runtimeAnimations;
  47029. for (var index = 0; index < runtimeAnimations.length; index++) {
  47030. runtimeAnimations[index].dispose();
  47031. }
  47032. if (this.onAnimationEnd) {
  47033. this.onAnimationEnd();
  47034. }
  47035. }
  47036. }
  47037. };
  47038. Animatable.prototype._animate = function (delay) {
  47039. if (this._paused) {
  47040. this.animationStarted = false;
  47041. if (this._pausedDelay === null) {
  47042. this._pausedDelay = delay;
  47043. }
  47044. return true;
  47045. }
  47046. if (this._localDelayOffset === null) {
  47047. this._localDelayOffset = delay;
  47048. this._pausedDelay = null;
  47049. }
  47050. else if (this._pausedDelay !== null) {
  47051. this._localDelayOffset += delay - this._pausedDelay;
  47052. this._pausedDelay = null;
  47053. }
  47054. // Animating
  47055. var running = false;
  47056. var runtimeAnimations = this._runtimeAnimations;
  47057. var index;
  47058. for (index = 0; index < runtimeAnimations.length; index++) {
  47059. var animation = runtimeAnimations[index];
  47060. var isRunning = animation.animate(delay - this._localDelayOffset, this.fromFrame, this.toFrame, this.loopAnimation, this._speedRatio);
  47061. running = running || isRunning;
  47062. }
  47063. this.animationStarted = running;
  47064. if (!running) {
  47065. // Remove from active animatables
  47066. index = this._scene._activeAnimatables.indexOf(this);
  47067. this._scene._activeAnimatables.splice(index, 1);
  47068. // Dispose all runtime animations
  47069. for (index = 0; index < runtimeAnimations.length; index++) {
  47070. runtimeAnimations[index].dispose();
  47071. }
  47072. }
  47073. if (!running && this.onAnimationEnd) {
  47074. this.onAnimationEnd();
  47075. this.onAnimationEnd = null;
  47076. }
  47077. return running;
  47078. };
  47079. return Animatable;
  47080. }());
  47081. BABYLON.Animatable = Animatable;
  47082. })(BABYLON || (BABYLON = {}));
  47083. //# sourceMappingURL=babylon.animatable.js.map
  47084. var BABYLON;
  47085. (function (BABYLON) {
  47086. var EasingFunction = /** @class */ (function () {
  47087. function EasingFunction() {
  47088. // Properties
  47089. this._easingMode = EasingFunction.EASINGMODE_EASEIN;
  47090. }
  47091. Object.defineProperty(EasingFunction, "EASINGMODE_EASEIN", {
  47092. get: function () {
  47093. return EasingFunction._EASINGMODE_EASEIN;
  47094. },
  47095. enumerable: true,
  47096. configurable: true
  47097. });
  47098. Object.defineProperty(EasingFunction, "EASINGMODE_EASEOUT", {
  47099. get: function () {
  47100. return EasingFunction._EASINGMODE_EASEOUT;
  47101. },
  47102. enumerable: true,
  47103. configurable: true
  47104. });
  47105. Object.defineProperty(EasingFunction, "EASINGMODE_EASEINOUT", {
  47106. get: function () {
  47107. return EasingFunction._EASINGMODE_EASEINOUT;
  47108. },
  47109. enumerable: true,
  47110. configurable: true
  47111. });
  47112. EasingFunction.prototype.setEasingMode = function (easingMode) {
  47113. var n = Math.min(Math.max(easingMode, 0), 2);
  47114. this._easingMode = n;
  47115. };
  47116. EasingFunction.prototype.getEasingMode = function () {
  47117. return this._easingMode;
  47118. };
  47119. EasingFunction.prototype.easeInCore = function (gradient) {
  47120. throw new Error('You must implement this method');
  47121. };
  47122. EasingFunction.prototype.ease = function (gradient) {
  47123. switch (this._easingMode) {
  47124. case EasingFunction.EASINGMODE_EASEIN:
  47125. return this.easeInCore(gradient);
  47126. case EasingFunction.EASINGMODE_EASEOUT:
  47127. return (1 - this.easeInCore(1 - gradient));
  47128. }
  47129. if (gradient >= 0.5) {
  47130. return (((1 - this.easeInCore((1 - gradient) * 2)) * 0.5) + 0.5);
  47131. }
  47132. return (this.easeInCore(gradient * 2) * 0.5);
  47133. };
  47134. //Statics
  47135. EasingFunction._EASINGMODE_EASEIN = 0;
  47136. EasingFunction._EASINGMODE_EASEOUT = 1;
  47137. EasingFunction._EASINGMODE_EASEINOUT = 2;
  47138. return EasingFunction;
  47139. }());
  47140. BABYLON.EasingFunction = EasingFunction;
  47141. var CircleEase = /** @class */ (function (_super) {
  47142. __extends(CircleEase, _super);
  47143. function CircleEase() {
  47144. return _super !== null && _super.apply(this, arguments) || this;
  47145. }
  47146. CircleEase.prototype.easeInCore = function (gradient) {
  47147. gradient = Math.max(0, Math.min(1, gradient));
  47148. return (1.0 - Math.sqrt(1.0 - (gradient * gradient)));
  47149. };
  47150. return CircleEase;
  47151. }(EasingFunction));
  47152. BABYLON.CircleEase = CircleEase;
  47153. var BackEase = /** @class */ (function (_super) {
  47154. __extends(BackEase, _super);
  47155. function BackEase(amplitude) {
  47156. if (amplitude === void 0) { amplitude = 1; }
  47157. var _this = _super.call(this) || this;
  47158. _this.amplitude = amplitude;
  47159. return _this;
  47160. }
  47161. BackEase.prototype.easeInCore = function (gradient) {
  47162. var num = Math.max(0, this.amplitude);
  47163. return (Math.pow(gradient, 3.0) - ((gradient * num) * Math.sin(3.1415926535897931 * gradient)));
  47164. };
  47165. return BackEase;
  47166. }(EasingFunction));
  47167. BABYLON.BackEase = BackEase;
  47168. var BounceEase = /** @class */ (function (_super) {
  47169. __extends(BounceEase, _super);
  47170. function BounceEase(bounces, bounciness) {
  47171. if (bounces === void 0) { bounces = 3; }
  47172. if (bounciness === void 0) { bounciness = 2; }
  47173. var _this = _super.call(this) || this;
  47174. _this.bounces = bounces;
  47175. _this.bounciness = bounciness;
  47176. return _this;
  47177. }
  47178. BounceEase.prototype.easeInCore = function (gradient) {
  47179. var y = Math.max(0.0, this.bounces);
  47180. var bounciness = this.bounciness;
  47181. if (bounciness <= 1.0) {
  47182. bounciness = 1.001;
  47183. }
  47184. var num9 = Math.pow(bounciness, y);
  47185. var num5 = 1.0 - bounciness;
  47186. var num4 = ((1.0 - num9) / num5) + (num9 * 0.5);
  47187. var num15 = gradient * num4;
  47188. var num65 = Math.log((-num15 * (1.0 - bounciness)) + 1.0) / Math.log(bounciness);
  47189. var num3 = Math.floor(num65);
  47190. var num13 = num3 + 1.0;
  47191. var num8 = (1.0 - Math.pow(bounciness, num3)) / (num5 * num4);
  47192. var num12 = (1.0 - Math.pow(bounciness, num13)) / (num5 * num4);
  47193. var num7 = (num8 + num12) * 0.5;
  47194. var num6 = gradient - num7;
  47195. var num2 = num7 - num8;
  47196. return (((-Math.pow(1.0 / bounciness, y - num3) / (num2 * num2)) * (num6 - num2)) * (num6 + num2));
  47197. };
  47198. return BounceEase;
  47199. }(EasingFunction));
  47200. BABYLON.BounceEase = BounceEase;
  47201. var CubicEase = /** @class */ (function (_super) {
  47202. __extends(CubicEase, _super);
  47203. function CubicEase() {
  47204. return _super !== null && _super.apply(this, arguments) || this;
  47205. }
  47206. CubicEase.prototype.easeInCore = function (gradient) {
  47207. return (gradient * gradient * gradient);
  47208. };
  47209. return CubicEase;
  47210. }(EasingFunction));
  47211. BABYLON.CubicEase = CubicEase;
  47212. var ElasticEase = /** @class */ (function (_super) {
  47213. __extends(ElasticEase, _super);
  47214. function ElasticEase(oscillations, springiness) {
  47215. if (oscillations === void 0) { oscillations = 3; }
  47216. if (springiness === void 0) { springiness = 3; }
  47217. var _this = _super.call(this) || this;
  47218. _this.oscillations = oscillations;
  47219. _this.springiness = springiness;
  47220. return _this;
  47221. }
  47222. ElasticEase.prototype.easeInCore = function (gradient) {
  47223. var num2;
  47224. var num3 = Math.max(0.0, this.oscillations);
  47225. var num = Math.max(0.0, this.springiness);
  47226. if (num == 0) {
  47227. num2 = gradient;
  47228. }
  47229. else {
  47230. num2 = (Math.exp(num * gradient) - 1.0) / (Math.exp(num) - 1.0);
  47231. }
  47232. return (num2 * Math.sin(((6.2831853071795862 * num3) + 1.5707963267948966) * gradient));
  47233. };
  47234. return ElasticEase;
  47235. }(EasingFunction));
  47236. BABYLON.ElasticEase = ElasticEase;
  47237. var ExponentialEase = /** @class */ (function (_super) {
  47238. __extends(ExponentialEase, _super);
  47239. function ExponentialEase(exponent) {
  47240. if (exponent === void 0) { exponent = 2; }
  47241. var _this = _super.call(this) || this;
  47242. _this.exponent = exponent;
  47243. return _this;
  47244. }
  47245. ExponentialEase.prototype.easeInCore = function (gradient) {
  47246. if (this.exponent <= 0) {
  47247. return gradient;
  47248. }
  47249. return ((Math.exp(this.exponent * gradient) - 1.0) / (Math.exp(this.exponent) - 1.0));
  47250. };
  47251. return ExponentialEase;
  47252. }(EasingFunction));
  47253. BABYLON.ExponentialEase = ExponentialEase;
  47254. var PowerEase = /** @class */ (function (_super) {
  47255. __extends(PowerEase, _super);
  47256. function PowerEase(power) {
  47257. if (power === void 0) { power = 2; }
  47258. var _this = _super.call(this) || this;
  47259. _this.power = power;
  47260. return _this;
  47261. }
  47262. PowerEase.prototype.easeInCore = function (gradient) {
  47263. var y = Math.max(0.0, this.power);
  47264. return Math.pow(gradient, y);
  47265. };
  47266. return PowerEase;
  47267. }(EasingFunction));
  47268. BABYLON.PowerEase = PowerEase;
  47269. var QuadraticEase = /** @class */ (function (_super) {
  47270. __extends(QuadraticEase, _super);
  47271. function QuadraticEase() {
  47272. return _super !== null && _super.apply(this, arguments) || this;
  47273. }
  47274. QuadraticEase.prototype.easeInCore = function (gradient) {
  47275. return (gradient * gradient);
  47276. };
  47277. return QuadraticEase;
  47278. }(EasingFunction));
  47279. BABYLON.QuadraticEase = QuadraticEase;
  47280. var QuarticEase = /** @class */ (function (_super) {
  47281. __extends(QuarticEase, _super);
  47282. function QuarticEase() {
  47283. return _super !== null && _super.apply(this, arguments) || this;
  47284. }
  47285. QuarticEase.prototype.easeInCore = function (gradient) {
  47286. return (gradient * gradient * gradient * gradient);
  47287. };
  47288. return QuarticEase;
  47289. }(EasingFunction));
  47290. BABYLON.QuarticEase = QuarticEase;
  47291. var QuinticEase = /** @class */ (function (_super) {
  47292. __extends(QuinticEase, _super);
  47293. function QuinticEase() {
  47294. return _super !== null && _super.apply(this, arguments) || this;
  47295. }
  47296. QuinticEase.prototype.easeInCore = function (gradient) {
  47297. return (gradient * gradient * gradient * gradient * gradient);
  47298. };
  47299. return QuinticEase;
  47300. }(EasingFunction));
  47301. BABYLON.QuinticEase = QuinticEase;
  47302. var SineEase = /** @class */ (function (_super) {
  47303. __extends(SineEase, _super);
  47304. function SineEase() {
  47305. return _super !== null && _super.apply(this, arguments) || this;
  47306. }
  47307. SineEase.prototype.easeInCore = function (gradient) {
  47308. return (1.0 - Math.sin(1.5707963267948966 * (1.0 - gradient)));
  47309. };
  47310. return SineEase;
  47311. }(EasingFunction));
  47312. BABYLON.SineEase = SineEase;
  47313. var BezierCurveEase = /** @class */ (function (_super) {
  47314. __extends(BezierCurveEase, _super);
  47315. function BezierCurveEase(x1, y1, x2, y2) {
  47316. if (x1 === void 0) { x1 = 0; }
  47317. if (y1 === void 0) { y1 = 0; }
  47318. if (x2 === void 0) { x2 = 1; }
  47319. if (y2 === void 0) { y2 = 1; }
  47320. var _this = _super.call(this) || this;
  47321. _this.x1 = x1;
  47322. _this.y1 = y1;
  47323. _this.x2 = x2;
  47324. _this.y2 = y2;
  47325. return _this;
  47326. }
  47327. BezierCurveEase.prototype.easeInCore = function (gradient) {
  47328. return BABYLON.BezierCurve.interpolate(gradient, this.x1, this.y1, this.x2, this.y2);
  47329. };
  47330. return BezierCurveEase;
  47331. }(EasingFunction));
  47332. BABYLON.BezierCurveEase = BezierCurveEase;
  47333. })(BABYLON || (BABYLON = {}));
  47334. //# sourceMappingURL=babylon.easing.js.map
  47335. var BABYLON;
  47336. (function (BABYLON) {
  47337. var Condition = /** @class */ (function () {
  47338. function Condition(actionManager) {
  47339. this._actionManager = actionManager;
  47340. }
  47341. Condition.prototype.isValid = function () {
  47342. return true;
  47343. };
  47344. Condition.prototype._getProperty = function (propertyPath) {
  47345. return this._actionManager._getProperty(propertyPath);
  47346. };
  47347. Condition.prototype._getEffectiveTarget = function (target, propertyPath) {
  47348. return this._actionManager._getEffectiveTarget(target, propertyPath);
  47349. };
  47350. Condition.prototype.serialize = function () {
  47351. };
  47352. Condition.prototype._serialize = function (serializedCondition) {
  47353. return {
  47354. type: 2,
  47355. children: [],
  47356. name: serializedCondition.name,
  47357. properties: serializedCondition.properties
  47358. };
  47359. };
  47360. return Condition;
  47361. }());
  47362. BABYLON.Condition = Condition;
  47363. var ValueCondition = /** @class */ (function (_super) {
  47364. __extends(ValueCondition, _super);
  47365. function ValueCondition(actionManager, target, propertyPath, value, operator) {
  47366. if (operator === void 0) { operator = ValueCondition.IsEqual; }
  47367. var _this = _super.call(this, actionManager) || this;
  47368. _this.propertyPath = propertyPath;
  47369. _this.value = value;
  47370. _this.operator = operator;
  47371. _this._target = target;
  47372. _this._effectiveTarget = _this._getEffectiveTarget(target, _this.propertyPath);
  47373. _this._property = _this._getProperty(_this.propertyPath);
  47374. return _this;
  47375. }
  47376. Object.defineProperty(ValueCondition, "IsEqual", {
  47377. get: function () {
  47378. return ValueCondition._IsEqual;
  47379. },
  47380. enumerable: true,
  47381. configurable: true
  47382. });
  47383. Object.defineProperty(ValueCondition, "IsDifferent", {
  47384. get: function () {
  47385. return ValueCondition._IsDifferent;
  47386. },
  47387. enumerable: true,
  47388. configurable: true
  47389. });
  47390. Object.defineProperty(ValueCondition, "IsGreater", {
  47391. get: function () {
  47392. return ValueCondition._IsGreater;
  47393. },
  47394. enumerable: true,
  47395. configurable: true
  47396. });
  47397. Object.defineProperty(ValueCondition, "IsLesser", {
  47398. get: function () {
  47399. return ValueCondition._IsLesser;
  47400. },
  47401. enumerable: true,
  47402. configurable: true
  47403. });
  47404. // Methods
  47405. ValueCondition.prototype.isValid = function () {
  47406. switch (this.operator) {
  47407. case ValueCondition.IsGreater:
  47408. return this._effectiveTarget[this._property] > this.value;
  47409. case ValueCondition.IsLesser:
  47410. return this._effectiveTarget[this._property] < this.value;
  47411. case ValueCondition.IsEqual:
  47412. case ValueCondition.IsDifferent:
  47413. var check;
  47414. if (this.value.equals) {
  47415. check = this.value.equals(this._effectiveTarget[this._property]);
  47416. }
  47417. else {
  47418. check = this.value === this._effectiveTarget[this._property];
  47419. }
  47420. return this.operator === ValueCondition.IsEqual ? check : !check;
  47421. }
  47422. return false;
  47423. };
  47424. ValueCondition.prototype.serialize = function () {
  47425. return this._serialize({
  47426. name: "ValueCondition",
  47427. properties: [
  47428. BABYLON.Action._GetTargetProperty(this._target),
  47429. { name: "propertyPath", value: this.propertyPath },
  47430. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  47431. { name: "operator", value: ValueCondition.GetOperatorName(this.operator) }
  47432. ]
  47433. });
  47434. };
  47435. ValueCondition.GetOperatorName = function (operator) {
  47436. switch (operator) {
  47437. case ValueCondition._IsEqual: return "IsEqual";
  47438. case ValueCondition._IsDifferent: return "IsDifferent";
  47439. case ValueCondition._IsGreater: return "IsGreater";
  47440. case ValueCondition._IsLesser: return "IsLesser";
  47441. default: return "";
  47442. }
  47443. };
  47444. // Statics
  47445. ValueCondition._IsEqual = 0;
  47446. ValueCondition._IsDifferent = 1;
  47447. ValueCondition._IsGreater = 2;
  47448. ValueCondition._IsLesser = 3;
  47449. return ValueCondition;
  47450. }(Condition));
  47451. BABYLON.ValueCondition = ValueCondition;
  47452. var PredicateCondition = /** @class */ (function (_super) {
  47453. __extends(PredicateCondition, _super);
  47454. function PredicateCondition(actionManager, predicate) {
  47455. var _this = _super.call(this, actionManager) || this;
  47456. _this.predicate = predicate;
  47457. return _this;
  47458. }
  47459. PredicateCondition.prototype.isValid = function () {
  47460. return this.predicate();
  47461. };
  47462. return PredicateCondition;
  47463. }(Condition));
  47464. BABYLON.PredicateCondition = PredicateCondition;
  47465. var StateCondition = /** @class */ (function (_super) {
  47466. __extends(StateCondition, _super);
  47467. function StateCondition(actionManager, target, value) {
  47468. var _this = _super.call(this, actionManager) || this;
  47469. _this.value = value;
  47470. _this._target = target;
  47471. return _this;
  47472. }
  47473. // Methods
  47474. StateCondition.prototype.isValid = function () {
  47475. return this._target.state === this.value;
  47476. };
  47477. StateCondition.prototype.serialize = function () {
  47478. return this._serialize({
  47479. name: "StateCondition",
  47480. properties: [
  47481. BABYLON.Action._GetTargetProperty(this._target),
  47482. { name: "value", value: this.value }
  47483. ]
  47484. });
  47485. };
  47486. return StateCondition;
  47487. }(Condition));
  47488. BABYLON.StateCondition = StateCondition;
  47489. })(BABYLON || (BABYLON = {}));
  47490. //# sourceMappingURL=babylon.condition.js.map
  47491. var BABYLON;
  47492. (function (BABYLON) {
  47493. var Action = /** @class */ (function () {
  47494. function Action(triggerOptions, condition) {
  47495. this.triggerOptions = triggerOptions;
  47496. this.onBeforeExecuteObservable = new BABYLON.Observable();
  47497. if (triggerOptions.parameter) {
  47498. this.trigger = triggerOptions.trigger;
  47499. this._triggerParameter = triggerOptions.parameter;
  47500. }
  47501. else {
  47502. this.trigger = triggerOptions;
  47503. }
  47504. this._nextActiveAction = this;
  47505. this._condition = condition;
  47506. }
  47507. // Methods
  47508. Action.prototype._prepare = function () {
  47509. };
  47510. Action.prototype.getTriggerParameter = function () {
  47511. return this._triggerParameter;
  47512. };
  47513. Action.prototype._executeCurrent = function (evt) {
  47514. if (this._nextActiveAction._condition) {
  47515. var condition = this._nextActiveAction._condition;
  47516. var currentRenderId = this._actionManager.getScene().getRenderId();
  47517. // We cache the current evaluation for the current frame
  47518. if (condition._evaluationId === currentRenderId) {
  47519. if (!condition._currentResult) {
  47520. return;
  47521. }
  47522. }
  47523. else {
  47524. condition._evaluationId = currentRenderId;
  47525. if (!condition.isValid()) {
  47526. condition._currentResult = false;
  47527. return;
  47528. }
  47529. condition._currentResult = true;
  47530. }
  47531. }
  47532. this.onBeforeExecuteObservable.notifyObservers(this);
  47533. this._nextActiveAction.execute(evt);
  47534. this.skipToNextActiveAction();
  47535. };
  47536. Action.prototype.execute = function (evt) {
  47537. };
  47538. Action.prototype.skipToNextActiveAction = function () {
  47539. if (this._nextActiveAction._child) {
  47540. if (!this._nextActiveAction._child._actionManager) {
  47541. this._nextActiveAction._child._actionManager = this._actionManager;
  47542. }
  47543. this._nextActiveAction = this._nextActiveAction._child;
  47544. }
  47545. else {
  47546. this._nextActiveAction = this;
  47547. }
  47548. };
  47549. Action.prototype.then = function (action) {
  47550. this._child = action;
  47551. action._actionManager = this._actionManager;
  47552. action._prepare();
  47553. return action;
  47554. };
  47555. Action.prototype._getProperty = function (propertyPath) {
  47556. return this._actionManager._getProperty(propertyPath);
  47557. };
  47558. Action.prototype._getEffectiveTarget = function (target, propertyPath) {
  47559. return this._actionManager._getEffectiveTarget(target, propertyPath);
  47560. };
  47561. Action.prototype.serialize = function (parent) {
  47562. };
  47563. // Called by BABYLON.Action objects in serialize(...). Internal use
  47564. Action.prototype._serialize = function (serializedAction, parent) {
  47565. var serializationObject = {
  47566. type: 1,
  47567. children: [],
  47568. name: serializedAction.name,
  47569. properties: serializedAction.properties || []
  47570. };
  47571. // Serialize child
  47572. if (this._child) {
  47573. this._child.serialize(serializationObject);
  47574. }
  47575. // Check if "this" has a condition
  47576. if (this._condition) {
  47577. var serializedCondition = this._condition.serialize();
  47578. serializedCondition.children.push(serializationObject);
  47579. if (parent) {
  47580. parent.children.push(serializedCondition);
  47581. }
  47582. return serializedCondition;
  47583. }
  47584. if (parent) {
  47585. parent.children.push(serializationObject);
  47586. }
  47587. return serializationObject;
  47588. };
  47589. Action._SerializeValueAsString = function (value) {
  47590. if (typeof value === "number") {
  47591. return value.toString();
  47592. }
  47593. if (typeof value === "boolean") {
  47594. return value ? "true" : "false";
  47595. }
  47596. if (value instanceof BABYLON.Vector2) {
  47597. return value.x + ", " + value.y;
  47598. }
  47599. if (value instanceof BABYLON.Vector3) {
  47600. return value.x + ", " + value.y + ", " + value.z;
  47601. }
  47602. if (value instanceof BABYLON.Color3) {
  47603. return value.r + ", " + value.g + ", " + value.b;
  47604. }
  47605. if (value instanceof BABYLON.Color4) {
  47606. return value.r + ", " + value.g + ", " + value.b + ", " + value.a;
  47607. }
  47608. return value; // string
  47609. };
  47610. Action._GetTargetProperty = function (target) {
  47611. return {
  47612. name: "target",
  47613. targetType: target instanceof BABYLON.Mesh ? "MeshProperties"
  47614. : target instanceof BABYLON.Light ? "LightProperties"
  47615. : target instanceof BABYLON.Camera ? "CameraProperties"
  47616. : "SceneProperties",
  47617. value: target instanceof BABYLON.Scene ? "Scene" : target.name
  47618. };
  47619. };
  47620. return Action;
  47621. }());
  47622. BABYLON.Action = Action;
  47623. })(BABYLON || (BABYLON = {}));
  47624. //# sourceMappingURL=babylon.action.js.map
  47625. var BABYLON;
  47626. (function (BABYLON) {
  47627. /**
  47628. * ActionEvent is the event beint sent when an action is triggered.
  47629. */
  47630. var ActionEvent = /** @class */ (function () {
  47631. /**
  47632. * @param source The mesh or sprite that triggered the action.
  47633. * @param pointerX The X mouse cursor position at the time of the event
  47634. * @param pointerY The Y mouse cursor position at the time of the event
  47635. * @param meshUnderPointer The mesh that is currently pointed at (can be null)
  47636. * @param sourceEvent the original (browser) event that triggered the ActionEvent
  47637. */
  47638. function ActionEvent(source, pointerX, pointerY, meshUnderPointer, sourceEvent, additionalData) {
  47639. this.source = source;
  47640. this.pointerX = pointerX;
  47641. this.pointerY = pointerY;
  47642. this.meshUnderPointer = meshUnderPointer;
  47643. this.sourceEvent = sourceEvent;
  47644. this.additionalData = additionalData;
  47645. }
  47646. /**
  47647. * Helper function to auto-create an ActionEvent from a source mesh.
  47648. * @param source The source mesh that triggered the event
  47649. * @param evt {Event} The original (browser) event
  47650. */
  47651. ActionEvent.CreateNew = function (source, evt, additionalData) {
  47652. var scene = source.getScene();
  47653. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  47654. };
  47655. /**
  47656. * Helper function to auto-create an ActionEvent from a source mesh.
  47657. * @param source The source sprite that triggered the event
  47658. * @param scene Scene associated with the sprite
  47659. * @param evt {Event} The original (browser) event
  47660. */
  47661. ActionEvent.CreateNewFromSprite = function (source, scene, evt, additionalData) {
  47662. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  47663. };
  47664. /**
  47665. * Helper function to auto-create an ActionEvent from a scene. If triggered by a mesh use ActionEvent.CreateNew
  47666. * @param scene the scene where the event occurred
  47667. * @param evt {Event} The original (browser) event
  47668. */
  47669. ActionEvent.CreateNewFromScene = function (scene, evt) {
  47670. return new ActionEvent(null, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt);
  47671. };
  47672. ActionEvent.CreateNewFromPrimitive = function (prim, pointerPos, evt, additionalData) {
  47673. return new ActionEvent(prim, pointerPos.x, pointerPos.y, null, evt, additionalData);
  47674. };
  47675. return ActionEvent;
  47676. }());
  47677. BABYLON.ActionEvent = ActionEvent;
  47678. /**
  47679. * Action Manager manages all events to be triggered on a given mesh or the global scene.
  47680. * A single scene can have many Action Managers to handle predefined actions on specific meshes.
  47681. */
  47682. var ActionManager = /** @class */ (function () {
  47683. function ActionManager(scene) {
  47684. // Members
  47685. this.actions = new Array();
  47686. this.hoverCursor = '';
  47687. this._scene = scene;
  47688. scene._actionManagers.push(this);
  47689. }
  47690. Object.defineProperty(ActionManager, "NothingTrigger", {
  47691. get: function () {
  47692. return ActionManager._NothingTrigger;
  47693. },
  47694. enumerable: true,
  47695. configurable: true
  47696. });
  47697. Object.defineProperty(ActionManager, "OnPickTrigger", {
  47698. get: function () {
  47699. return ActionManager._OnPickTrigger;
  47700. },
  47701. enumerable: true,
  47702. configurable: true
  47703. });
  47704. Object.defineProperty(ActionManager, "OnLeftPickTrigger", {
  47705. get: function () {
  47706. return ActionManager._OnLeftPickTrigger;
  47707. },
  47708. enumerable: true,
  47709. configurable: true
  47710. });
  47711. Object.defineProperty(ActionManager, "OnRightPickTrigger", {
  47712. get: function () {
  47713. return ActionManager._OnRightPickTrigger;
  47714. },
  47715. enumerable: true,
  47716. configurable: true
  47717. });
  47718. Object.defineProperty(ActionManager, "OnCenterPickTrigger", {
  47719. get: function () {
  47720. return ActionManager._OnCenterPickTrigger;
  47721. },
  47722. enumerable: true,
  47723. configurable: true
  47724. });
  47725. Object.defineProperty(ActionManager, "OnPickDownTrigger", {
  47726. get: function () {
  47727. return ActionManager._OnPickDownTrigger;
  47728. },
  47729. enumerable: true,
  47730. configurable: true
  47731. });
  47732. Object.defineProperty(ActionManager, "OnDoublePickTrigger", {
  47733. get: function () {
  47734. return ActionManager._OnDoublePickTrigger;
  47735. },
  47736. enumerable: true,
  47737. configurable: true
  47738. });
  47739. Object.defineProperty(ActionManager, "OnPickUpTrigger", {
  47740. get: function () {
  47741. return ActionManager._OnPickUpTrigger;
  47742. },
  47743. enumerable: true,
  47744. configurable: true
  47745. });
  47746. Object.defineProperty(ActionManager, "OnPickOutTrigger", {
  47747. /// This trigger will only be raised if you also declared a OnPickDown
  47748. get: function () {
  47749. return ActionManager._OnPickOutTrigger;
  47750. },
  47751. enumerable: true,
  47752. configurable: true
  47753. });
  47754. Object.defineProperty(ActionManager, "OnLongPressTrigger", {
  47755. get: function () {
  47756. return ActionManager._OnLongPressTrigger;
  47757. },
  47758. enumerable: true,
  47759. configurable: true
  47760. });
  47761. Object.defineProperty(ActionManager, "OnPointerOverTrigger", {
  47762. get: function () {
  47763. return ActionManager._OnPointerOverTrigger;
  47764. },
  47765. enumerable: true,
  47766. configurable: true
  47767. });
  47768. Object.defineProperty(ActionManager, "OnPointerOutTrigger", {
  47769. get: function () {
  47770. return ActionManager._OnPointerOutTrigger;
  47771. },
  47772. enumerable: true,
  47773. configurable: true
  47774. });
  47775. Object.defineProperty(ActionManager, "OnEveryFrameTrigger", {
  47776. get: function () {
  47777. return ActionManager._OnEveryFrameTrigger;
  47778. },
  47779. enumerable: true,
  47780. configurable: true
  47781. });
  47782. Object.defineProperty(ActionManager, "OnIntersectionEnterTrigger", {
  47783. get: function () {
  47784. return ActionManager._OnIntersectionEnterTrigger;
  47785. },
  47786. enumerable: true,
  47787. configurable: true
  47788. });
  47789. Object.defineProperty(ActionManager, "OnIntersectionExitTrigger", {
  47790. get: function () {
  47791. return ActionManager._OnIntersectionExitTrigger;
  47792. },
  47793. enumerable: true,
  47794. configurable: true
  47795. });
  47796. Object.defineProperty(ActionManager, "OnKeyDownTrigger", {
  47797. get: function () {
  47798. return ActionManager._OnKeyDownTrigger;
  47799. },
  47800. enumerable: true,
  47801. configurable: true
  47802. });
  47803. Object.defineProperty(ActionManager, "OnKeyUpTrigger", {
  47804. get: function () {
  47805. return ActionManager._OnKeyUpTrigger;
  47806. },
  47807. enumerable: true,
  47808. configurable: true
  47809. });
  47810. // Methods
  47811. ActionManager.prototype.dispose = function () {
  47812. var index = this._scene._actionManagers.indexOf(this);
  47813. for (var i = 0; i < this.actions.length; i++) {
  47814. var action = this.actions[i];
  47815. ActionManager.Triggers[action.trigger]--;
  47816. if (ActionManager.Triggers[action.trigger] === 0) {
  47817. delete ActionManager.Triggers[action.trigger];
  47818. }
  47819. }
  47820. if (index > -1) {
  47821. this._scene._actionManagers.splice(index, 1);
  47822. }
  47823. };
  47824. ActionManager.prototype.getScene = function () {
  47825. return this._scene;
  47826. };
  47827. /**
  47828. * Does this action manager handles actions of any of the given triggers
  47829. * @param {number[]} triggers - the triggers to be tested
  47830. * @return {boolean} whether one (or more) of the triggers is handeled
  47831. */
  47832. ActionManager.prototype.hasSpecificTriggers = function (triggers) {
  47833. for (var index = 0; index < this.actions.length; index++) {
  47834. var action = this.actions[index];
  47835. if (triggers.indexOf(action.trigger) > -1) {
  47836. return true;
  47837. }
  47838. }
  47839. return false;
  47840. };
  47841. /**
  47842. * Does this action manager handles actions of a given trigger
  47843. * @param {number} trigger - the trigger to be tested
  47844. * @return {boolean} whether the trigger is handeled
  47845. */
  47846. ActionManager.prototype.hasSpecificTrigger = function (trigger) {
  47847. for (var index = 0; index < this.actions.length; index++) {
  47848. var action = this.actions[index];
  47849. if (action.trigger === trigger) {
  47850. return true;
  47851. }
  47852. }
  47853. return false;
  47854. };
  47855. Object.defineProperty(ActionManager.prototype, "hasPointerTriggers", {
  47856. /**
  47857. * Does this action manager has pointer triggers
  47858. * @return {boolean} whether or not it has pointer triggers
  47859. */
  47860. get: function () {
  47861. for (var index = 0; index < this.actions.length; index++) {
  47862. var action = this.actions[index];
  47863. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPointerOutTrigger) {
  47864. return true;
  47865. }
  47866. }
  47867. return false;
  47868. },
  47869. enumerable: true,
  47870. configurable: true
  47871. });
  47872. Object.defineProperty(ActionManager.prototype, "hasPickTriggers", {
  47873. /**
  47874. * Does this action manager has pick triggers
  47875. * @return {boolean} whether or not it has pick triggers
  47876. */
  47877. get: function () {
  47878. for (var index = 0; index < this.actions.length; index++) {
  47879. var action = this.actions[index];
  47880. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPickUpTrigger) {
  47881. return true;
  47882. }
  47883. }
  47884. return false;
  47885. },
  47886. enumerable: true,
  47887. configurable: true
  47888. });
  47889. Object.defineProperty(ActionManager, "HasTriggers", {
  47890. /**
  47891. * Does exist one action manager with at least one trigger
  47892. * @return {boolean} whether or not it exists one action manager with one trigger
  47893. **/
  47894. get: function () {
  47895. for (var t in ActionManager.Triggers) {
  47896. if (ActionManager.Triggers.hasOwnProperty(t)) {
  47897. return true;
  47898. }
  47899. }
  47900. return false;
  47901. },
  47902. enumerable: true,
  47903. configurable: true
  47904. });
  47905. Object.defineProperty(ActionManager, "HasPickTriggers", {
  47906. /**
  47907. * Does exist one action manager with at least one pick trigger
  47908. * @return {boolean} whether or not it exists one action manager with one pick trigger
  47909. **/
  47910. get: function () {
  47911. for (var t in ActionManager.Triggers) {
  47912. if (ActionManager.Triggers.hasOwnProperty(t)) {
  47913. var t_int = parseInt(t);
  47914. if (t_int >= ActionManager._OnPickTrigger && t_int <= ActionManager._OnPickUpTrigger) {
  47915. return true;
  47916. }
  47917. }
  47918. }
  47919. return false;
  47920. },
  47921. enumerable: true,
  47922. configurable: true
  47923. });
  47924. /**
  47925. * Does exist one action manager that handles actions of a given trigger
  47926. * @param {number} trigger - the trigger to be tested
  47927. * @return {boolean} whether the trigger is handeled by at least one action manager
  47928. **/
  47929. ActionManager.HasSpecificTrigger = function (trigger) {
  47930. for (var t in ActionManager.Triggers) {
  47931. if (ActionManager.Triggers.hasOwnProperty(t)) {
  47932. var t_int = parseInt(t);
  47933. if (t_int === trigger) {
  47934. return true;
  47935. }
  47936. }
  47937. }
  47938. return false;
  47939. };
  47940. /**
  47941. * Registers an action to this action manager
  47942. * @param {BABYLON.Action} action - the action to be registered
  47943. * @return {BABYLON.Action} the action amended (prepared) after registration
  47944. */
  47945. ActionManager.prototype.registerAction = function (action) {
  47946. if (action.trigger === ActionManager.OnEveryFrameTrigger) {
  47947. if (this.getScene().actionManager !== this) {
  47948. BABYLON.Tools.Warn("OnEveryFrameTrigger can only be used with scene.actionManager");
  47949. return null;
  47950. }
  47951. }
  47952. this.actions.push(action);
  47953. if (ActionManager.Triggers[action.trigger]) {
  47954. ActionManager.Triggers[action.trigger]++;
  47955. }
  47956. else {
  47957. ActionManager.Triggers[action.trigger] = 1;
  47958. }
  47959. action._actionManager = this;
  47960. action._prepare();
  47961. return action;
  47962. };
  47963. /**
  47964. * Unregisters an action to this action manager
  47965. * @param action The action to be unregistered
  47966. * @return whether the action has been unregistered
  47967. */
  47968. ActionManager.prototype.unregisterAction = function (action) {
  47969. var index = this.actions.indexOf(action);
  47970. if (index !== -1) {
  47971. this.actions.splice(index, 1);
  47972. ActionManager.Triggers[action.trigger] -= 1;
  47973. if (ActionManager.Triggers[action.trigger] === 0) {
  47974. delete ActionManager.Triggers[action.trigger];
  47975. }
  47976. delete action._actionManager;
  47977. return true;
  47978. }
  47979. return false;
  47980. };
  47981. /**
  47982. * Process a specific trigger
  47983. * @param {number} trigger - the trigger to process
  47984. * @param evt {BABYLON.ActionEvent} the event details to be processed
  47985. */
  47986. ActionManager.prototype.processTrigger = function (trigger, evt) {
  47987. for (var index = 0; index < this.actions.length; index++) {
  47988. var action = this.actions[index];
  47989. if (action.trigger === trigger) {
  47990. if (evt) {
  47991. if (trigger === ActionManager.OnKeyUpTrigger
  47992. || trigger === ActionManager.OnKeyDownTrigger) {
  47993. var parameter = action.getTriggerParameter();
  47994. if (parameter && parameter !== evt.sourceEvent.keyCode) {
  47995. if (!parameter.toLowerCase) {
  47996. continue;
  47997. }
  47998. var lowerCase = parameter.toLowerCase();
  47999. if (lowerCase !== evt.sourceEvent.key) {
  48000. var unicode = evt.sourceEvent.charCode ? evt.sourceEvent.charCode : evt.sourceEvent.keyCode;
  48001. var actualkey = String.fromCharCode(unicode).toLowerCase();
  48002. if (actualkey !== lowerCase) {
  48003. continue;
  48004. }
  48005. }
  48006. }
  48007. }
  48008. }
  48009. action._executeCurrent(evt);
  48010. }
  48011. }
  48012. };
  48013. ActionManager.prototype._getEffectiveTarget = function (target, propertyPath) {
  48014. var properties = propertyPath.split(".");
  48015. for (var index = 0; index < properties.length - 1; index++) {
  48016. target = target[properties[index]];
  48017. }
  48018. return target;
  48019. };
  48020. ActionManager.prototype._getProperty = function (propertyPath) {
  48021. var properties = propertyPath.split(".");
  48022. return properties[properties.length - 1];
  48023. };
  48024. ActionManager.prototype.serialize = function (name) {
  48025. var root = {
  48026. children: new Array(),
  48027. name: name,
  48028. type: 3,
  48029. properties: new Array() // Empty for root but required
  48030. };
  48031. for (var i = 0; i < this.actions.length; i++) {
  48032. var triggerObject = {
  48033. type: 0,
  48034. children: new Array(),
  48035. name: ActionManager.GetTriggerName(this.actions[i].trigger),
  48036. properties: new Array()
  48037. };
  48038. var triggerOptions = this.actions[i].triggerOptions;
  48039. if (triggerOptions && typeof triggerOptions !== "number") {
  48040. if (triggerOptions.parameter instanceof BABYLON.Node) {
  48041. triggerObject.properties.push(BABYLON.Action._GetTargetProperty(triggerOptions.parameter));
  48042. }
  48043. else {
  48044. var parameter = {};
  48045. BABYLON.Tools.DeepCopy(triggerOptions.parameter, parameter, ["mesh"]);
  48046. if (triggerOptions.parameter.mesh) {
  48047. parameter._meshId = triggerOptions.parameter.mesh.id;
  48048. }
  48049. triggerObject.properties.push({ name: "parameter", targetType: null, value: parameter });
  48050. }
  48051. }
  48052. // Serialize child action, recursively
  48053. this.actions[i].serialize(triggerObject);
  48054. // Add serialized trigger
  48055. root.children.push(triggerObject);
  48056. }
  48057. return root;
  48058. };
  48059. ActionManager.Parse = function (parsedActions, object, scene) {
  48060. var actionManager = new ActionManager(scene);
  48061. if (object === null)
  48062. scene.actionManager = actionManager;
  48063. else
  48064. object.actionManager = actionManager;
  48065. // instanciate a new object
  48066. var instanciate = function (name, params) {
  48067. // TODO: We will need to find a solution for the next line when using commonjs / es6 .
  48068. var newInstance = Object.create(BABYLON.Tools.Instantiate("BABYLON." + name).prototype);
  48069. newInstance.constructor.apply(newInstance, params);
  48070. return newInstance;
  48071. };
  48072. var parseParameter = function (name, value, target, propertyPath) {
  48073. if (propertyPath === null) {
  48074. // String, boolean or float
  48075. var floatValue = parseFloat(value);
  48076. if (value === "true" || value === "false")
  48077. return value === "true";
  48078. else
  48079. return isNaN(floatValue) ? value : floatValue;
  48080. }
  48081. var effectiveTarget = propertyPath.split(".");
  48082. var values = value.split(",");
  48083. // Get effective Target
  48084. for (var i = 0; i < effectiveTarget.length; i++) {
  48085. target = target[effectiveTarget[i]];
  48086. }
  48087. // Return appropriate value with its type
  48088. if (typeof (target) === "boolean")
  48089. return values[0] === "true";
  48090. if (typeof (target) === "string")
  48091. return values[0];
  48092. // Parameters with multiple values such as Vector3 etc.
  48093. var split = new Array();
  48094. for (var i = 0; i < values.length; i++)
  48095. split.push(parseFloat(values[i]));
  48096. if (target instanceof BABYLON.Vector3)
  48097. return BABYLON.Vector3.FromArray(split);
  48098. if (target instanceof BABYLON.Vector4)
  48099. return BABYLON.Vector4.FromArray(split);
  48100. if (target instanceof BABYLON.Color3)
  48101. return BABYLON.Color3.FromArray(split);
  48102. if (target instanceof BABYLON.Color4)
  48103. return BABYLON.Color4.FromArray(split);
  48104. return parseFloat(values[0]);
  48105. };
  48106. // traverse graph per trigger
  48107. var traverse = function (parsedAction, trigger, condition, action, combineArray) {
  48108. if (combineArray === void 0) { combineArray = null; }
  48109. if (parsedAction.detached)
  48110. return;
  48111. var parameters = new Array();
  48112. var target = null;
  48113. var propertyPath = null;
  48114. var combine = parsedAction.combine && parsedAction.combine.length > 0;
  48115. // Parameters
  48116. if (parsedAction.type === 2)
  48117. parameters.push(actionManager);
  48118. else
  48119. parameters.push(trigger);
  48120. if (combine) {
  48121. var actions = new Array();
  48122. for (var j = 0; j < parsedAction.combine.length; j++) {
  48123. traverse(parsedAction.combine[j], ActionManager.NothingTrigger, condition, action, actions);
  48124. }
  48125. parameters.push(actions);
  48126. }
  48127. else {
  48128. for (var i = 0; i < parsedAction.properties.length; i++) {
  48129. var value = parsedAction.properties[i].value;
  48130. var name = parsedAction.properties[i].name;
  48131. var targetType = parsedAction.properties[i].targetType;
  48132. if (name === "target")
  48133. if (targetType !== null && targetType === "SceneProperties")
  48134. value = target = scene;
  48135. else
  48136. value = target = scene.getNodeByName(value);
  48137. else if (name === "parent")
  48138. value = scene.getNodeByName(value);
  48139. else if (name === "sound")
  48140. value = scene.getSoundByName(value);
  48141. else if (name !== "propertyPath") {
  48142. if (parsedAction.type === 2 && name === "operator")
  48143. value = BABYLON.ValueCondition[value];
  48144. else
  48145. value = parseParameter(name, value, target, name === "value" ? propertyPath : null);
  48146. }
  48147. else {
  48148. propertyPath = value;
  48149. }
  48150. parameters.push(value);
  48151. }
  48152. }
  48153. if (combineArray === null) {
  48154. parameters.push(condition);
  48155. }
  48156. else {
  48157. parameters.push(null);
  48158. }
  48159. // If interpolate value action
  48160. if (parsedAction.name === "InterpolateValueAction") {
  48161. var param = parameters[parameters.length - 2];
  48162. parameters[parameters.length - 1] = param;
  48163. parameters[parameters.length - 2] = condition;
  48164. }
  48165. // Action or condition(s) and not CombineAction
  48166. var newAction = instanciate(parsedAction.name, parameters);
  48167. if (newAction instanceof BABYLON.Condition && condition !== null) {
  48168. var nothing = new BABYLON.DoNothingAction(trigger, condition);
  48169. if (action)
  48170. action.then(nothing);
  48171. else
  48172. actionManager.registerAction(nothing);
  48173. action = nothing;
  48174. }
  48175. if (combineArray === null) {
  48176. if (newAction instanceof BABYLON.Condition) {
  48177. condition = newAction;
  48178. newAction = action;
  48179. }
  48180. else {
  48181. condition = null;
  48182. if (action)
  48183. action.then(newAction);
  48184. else
  48185. actionManager.registerAction(newAction);
  48186. }
  48187. }
  48188. else {
  48189. combineArray.push(newAction);
  48190. }
  48191. for (var i = 0; i < parsedAction.children.length; i++)
  48192. traverse(parsedAction.children[i], trigger, condition, newAction, null);
  48193. };
  48194. // triggers
  48195. for (var i = 0; i < parsedActions.children.length; i++) {
  48196. var triggerParams;
  48197. var trigger = parsedActions.children[i];
  48198. if (trigger.properties.length > 0) {
  48199. var param = trigger.properties[0].value;
  48200. var value = trigger.properties[0].targetType === null ? param : scene.getMeshByName(param);
  48201. if (value._meshId) {
  48202. value.mesh = scene.getMeshByID(value._meshId);
  48203. }
  48204. triggerParams = { trigger: ActionManager[trigger.name], parameter: value };
  48205. }
  48206. else
  48207. triggerParams = ActionManager[trigger.name];
  48208. for (var j = 0; j < trigger.children.length; j++) {
  48209. if (!trigger.detached)
  48210. traverse(trigger.children[j], triggerParams, null, null);
  48211. }
  48212. }
  48213. };
  48214. ActionManager.GetTriggerName = function (trigger) {
  48215. switch (trigger) {
  48216. case 0: return "NothingTrigger";
  48217. case 1: return "OnPickTrigger";
  48218. case 2: return "OnLeftPickTrigger";
  48219. case 3: return "OnRightPickTrigger";
  48220. case 4: return "OnCenterPickTrigger";
  48221. case 5: return "OnPickDownTrigger";
  48222. case 6: return "OnPickUpTrigger";
  48223. case 7: return "OnLongPressTrigger";
  48224. case 8: return "OnPointerOverTrigger";
  48225. case 9: return "OnPointerOutTrigger";
  48226. case 10: return "OnEveryFrameTrigger";
  48227. case 11: return "OnIntersectionEnterTrigger";
  48228. case 12: return "OnIntersectionExitTrigger";
  48229. case 13: return "OnKeyDownTrigger";
  48230. case 14: return "OnKeyUpTrigger";
  48231. case 15: return "OnPickOutTrigger";
  48232. default: return "";
  48233. }
  48234. };
  48235. // Statics
  48236. ActionManager._NothingTrigger = 0;
  48237. ActionManager._OnPickTrigger = 1;
  48238. ActionManager._OnLeftPickTrigger = 2;
  48239. ActionManager._OnRightPickTrigger = 3;
  48240. ActionManager._OnCenterPickTrigger = 4;
  48241. ActionManager._OnPickDownTrigger = 5;
  48242. ActionManager._OnDoublePickTrigger = 6;
  48243. ActionManager._OnPickUpTrigger = 7;
  48244. ActionManager._OnLongPressTrigger = 8;
  48245. ActionManager._OnPointerOverTrigger = 9;
  48246. ActionManager._OnPointerOutTrigger = 10;
  48247. ActionManager._OnEveryFrameTrigger = 11;
  48248. ActionManager._OnIntersectionEnterTrigger = 12;
  48249. ActionManager._OnIntersectionExitTrigger = 13;
  48250. ActionManager._OnKeyDownTrigger = 14;
  48251. ActionManager._OnKeyUpTrigger = 15;
  48252. ActionManager._OnPickOutTrigger = 16;
  48253. ActionManager.Triggers = {};
  48254. return ActionManager;
  48255. }());
  48256. BABYLON.ActionManager = ActionManager;
  48257. })(BABYLON || (BABYLON = {}));
  48258. //# sourceMappingURL=babylon.actionManager.js.map
  48259. var BABYLON;
  48260. (function (BABYLON) {
  48261. var InterpolateValueAction = /** @class */ (function (_super) {
  48262. __extends(InterpolateValueAction, _super);
  48263. function InterpolateValueAction(triggerOptions, target, propertyPath, value, duration, condition, stopOtherAnimations, onInterpolationDone) {
  48264. if (duration === void 0) { duration = 1000; }
  48265. var _this = _super.call(this, triggerOptions, condition) || this;
  48266. _this.propertyPath = propertyPath;
  48267. _this.value = value;
  48268. _this.duration = duration;
  48269. _this.stopOtherAnimations = stopOtherAnimations;
  48270. _this.onInterpolationDone = onInterpolationDone;
  48271. _this.onInterpolationDoneObservable = new BABYLON.Observable();
  48272. _this._target = _this._effectiveTarget = target;
  48273. return _this;
  48274. }
  48275. InterpolateValueAction.prototype._prepare = function () {
  48276. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  48277. this._property = this._getProperty(this.propertyPath);
  48278. };
  48279. InterpolateValueAction.prototype.execute = function () {
  48280. var _this = this;
  48281. var scene = this._actionManager.getScene();
  48282. var keys = [
  48283. {
  48284. frame: 0,
  48285. value: this._effectiveTarget[this._property]
  48286. }, {
  48287. frame: 100,
  48288. value: this.value
  48289. }
  48290. ];
  48291. var dataType;
  48292. if (typeof this.value === "number") {
  48293. dataType = BABYLON.Animation.ANIMATIONTYPE_FLOAT;
  48294. }
  48295. else if (this.value instanceof BABYLON.Color3) {
  48296. dataType = BABYLON.Animation.ANIMATIONTYPE_COLOR3;
  48297. }
  48298. else if (this.value instanceof BABYLON.Vector3) {
  48299. dataType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  48300. }
  48301. else if (this.value instanceof BABYLON.Matrix) {
  48302. dataType = BABYLON.Animation.ANIMATIONTYPE_MATRIX;
  48303. }
  48304. else if (this.value instanceof BABYLON.Quaternion) {
  48305. dataType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  48306. }
  48307. else {
  48308. BABYLON.Tools.Warn("InterpolateValueAction: Unsupported type (" + typeof this.value + ")");
  48309. return;
  48310. }
  48311. var animation = new BABYLON.Animation("InterpolateValueAction", this._property, 100 * (1000.0 / this.duration), dataType, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  48312. animation.setKeys(keys);
  48313. if (this.stopOtherAnimations) {
  48314. scene.stopAnimation(this._effectiveTarget);
  48315. }
  48316. var wrapper = function () {
  48317. _this.onInterpolationDoneObservable.notifyObservers(_this);
  48318. if (_this.onInterpolationDone) {
  48319. _this.onInterpolationDone();
  48320. }
  48321. };
  48322. scene.beginDirectAnimation(this._effectiveTarget, [animation], 0, 100, false, 1, wrapper);
  48323. };
  48324. InterpolateValueAction.prototype.serialize = function (parent) {
  48325. return _super.prototype._serialize.call(this, {
  48326. name: "InterpolateValueAction",
  48327. properties: [
  48328. BABYLON.Action._GetTargetProperty(this._target),
  48329. { name: "propertyPath", value: this.propertyPath },
  48330. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  48331. { name: "duration", value: BABYLON.Action._SerializeValueAsString(this.duration) },
  48332. { name: "stopOtherAnimations", value: BABYLON.Action._SerializeValueAsString(this.stopOtherAnimations) || false }
  48333. ]
  48334. }, parent);
  48335. };
  48336. return InterpolateValueAction;
  48337. }(BABYLON.Action));
  48338. BABYLON.InterpolateValueAction = InterpolateValueAction;
  48339. })(BABYLON || (BABYLON = {}));
  48340. //# sourceMappingURL=babylon.interpolateValueAction.js.map
  48341. var BABYLON;
  48342. (function (BABYLON) {
  48343. var SwitchBooleanAction = /** @class */ (function (_super) {
  48344. __extends(SwitchBooleanAction, _super);
  48345. function SwitchBooleanAction(triggerOptions, target, propertyPath, condition) {
  48346. var _this = _super.call(this, triggerOptions, condition) || this;
  48347. _this.propertyPath = propertyPath;
  48348. _this._target = _this._effectiveTarget = target;
  48349. return _this;
  48350. }
  48351. SwitchBooleanAction.prototype._prepare = function () {
  48352. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  48353. this._property = this._getProperty(this.propertyPath);
  48354. };
  48355. SwitchBooleanAction.prototype.execute = function () {
  48356. this._effectiveTarget[this._property] = !this._effectiveTarget[this._property];
  48357. };
  48358. SwitchBooleanAction.prototype.serialize = function (parent) {
  48359. return _super.prototype._serialize.call(this, {
  48360. name: "SwitchBooleanAction",
  48361. properties: [
  48362. BABYLON.Action._GetTargetProperty(this._target),
  48363. { name: "propertyPath", value: this.propertyPath }
  48364. ]
  48365. }, parent);
  48366. };
  48367. return SwitchBooleanAction;
  48368. }(BABYLON.Action));
  48369. BABYLON.SwitchBooleanAction = SwitchBooleanAction;
  48370. var SetStateAction = /** @class */ (function (_super) {
  48371. __extends(SetStateAction, _super);
  48372. function SetStateAction(triggerOptions, target, value, condition) {
  48373. var _this = _super.call(this, triggerOptions, condition) || this;
  48374. _this.value = value;
  48375. _this._target = target;
  48376. return _this;
  48377. }
  48378. SetStateAction.prototype.execute = function () {
  48379. this._target.state = this.value;
  48380. };
  48381. SetStateAction.prototype.serialize = function (parent) {
  48382. return _super.prototype._serialize.call(this, {
  48383. name: "SetStateAction",
  48384. properties: [
  48385. BABYLON.Action._GetTargetProperty(this._target),
  48386. { name: "value", value: this.value }
  48387. ]
  48388. }, parent);
  48389. };
  48390. return SetStateAction;
  48391. }(BABYLON.Action));
  48392. BABYLON.SetStateAction = SetStateAction;
  48393. var SetValueAction = /** @class */ (function (_super) {
  48394. __extends(SetValueAction, _super);
  48395. function SetValueAction(triggerOptions, target, propertyPath, value, condition) {
  48396. var _this = _super.call(this, triggerOptions, condition) || this;
  48397. _this.propertyPath = propertyPath;
  48398. _this.value = value;
  48399. _this._target = _this._effectiveTarget = target;
  48400. return _this;
  48401. }
  48402. SetValueAction.prototype._prepare = function () {
  48403. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  48404. this._property = this._getProperty(this.propertyPath);
  48405. };
  48406. SetValueAction.prototype.execute = function () {
  48407. this._effectiveTarget[this._property] = this.value;
  48408. if (this._target.markAsDirty) {
  48409. this._target.markAsDirty(this._property);
  48410. }
  48411. };
  48412. SetValueAction.prototype.serialize = function (parent) {
  48413. return _super.prototype._serialize.call(this, {
  48414. name: "SetValueAction",
  48415. properties: [
  48416. BABYLON.Action._GetTargetProperty(this._target),
  48417. { name: "propertyPath", value: this.propertyPath },
  48418. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  48419. ]
  48420. }, parent);
  48421. };
  48422. return SetValueAction;
  48423. }(BABYLON.Action));
  48424. BABYLON.SetValueAction = SetValueAction;
  48425. var IncrementValueAction = /** @class */ (function (_super) {
  48426. __extends(IncrementValueAction, _super);
  48427. function IncrementValueAction(triggerOptions, target, propertyPath, value, condition) {
  48428. var _this = _super.call(this, triggerOptions, condition) || this;
  48429. _this.propertyPath = propertyPath;
  48430. _this.value = value;
  48431. _this._target = _this._effectiveTarget = target;
  48432. return _this;
  48433. }
  48434. IncrementValueAction.prototype._prepare = function () {
  48435. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  48436. this._property = this._getProperty(this.propertyPath);
  48437. if (typeof this._effectiveTarget[this._property] !== "number") {
  48438. BABYLON.Tools.Warn("Warning: IncrementValueAction can only be used with number values");
  48439. }
  48440. };
  48441. IncrementValueAction.prototype.execute = function () {
  48442. this._effectiveTarget[this._property] += this.value;
  48443. if (this._target.markAsDirty) {
  48444. this._target.markAsDirty(this._property);
  48445. }
  48446. };
  48447. IncrementValueAction.prototype.serialize = function (parent) {
  48448. return _super.prototype._serialize.call(this, {
  48449. name: "IncrementValueAction",
  48450. properties: [
  48451. BABYLON.Action._GetTargetProperty(this._target),
  48452. { name: "propertyPath", value: this.propertyPath },
  48453. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  48454. ]
  48455. }, parent);
  48456. };
  48457. return IncrementValueAction;
  48458. }(BABYLON.Action));
  48459. BABYLON.IncrementValueAction = IncrementValueAction;
  48460. var PlayAnimationAction = /** @class */ (function (_super) {
  48461. __extends(PlayAnimationAction, _super);
  48462. function PlayAnimationAction(triggerOptions, target, from, to, loop, condition) {
  48463. var _this = _super.call(this, triggerOptions, condition) || this;
  48464. _this.from = from;
  48465. _this.to = to;
  48466. _this.loop = loop;
  48467. _this._target = target;
  48468. return _this;
  48469. }
  48470. PlayAnimationAction.prototype._prepare = function () {
  48471. };
  48472. PlayAnimationAction.prototype.execute = function () {
  48473. var scene = this._actionManager.getScene();
  48474. scene.beginAnimation(this._target, this.from, this.to, this.loop);
  48475. };
  48476. PlayAnimationAction.prototype.serialize = function (parent) {
  48477. return _super.prototype._serialize.call(this, {
  48478. name: "PlayAnimationAction",
  48479. properties: [
  48480. BABYLON.Action._GetTargetProperty(this._target),
  48481. { name: "from", value: String(this.from) },
  48482. { name: "to", value: String(this.to) },
  48483. { name: "loop", value: BABYLON.Action._SerializeValueAsString(this.loop) || false }
  48484. ]
  48485. }, parent);
  48486. };
  48487. return PlayAnimationAction;
  48488. }(BABYLON.Action));
  48489. BABYLON.PlayAnimationAction = PlayAnimationAction;
  48490. var StopAnimationAction = /** @class */ (function (_super) {
  48491. __extends(StopAnimationAction, _super);
  48492. function StopAnimationAction(triggerOptions, target, condition) {
  48493. var _this = _super.call(this, triggerOptions, condition) || this;
  48494. _this._target = target;
  48495. return _this;
  48496. }
  48497. StopAnimationAction.prototype._prepare = function () {
  48498. };
  48499. StopAnimationAction.prototype.execute = function () {
  48500. var scene = this._actionManager.getScene();
  48501. scene.stopAnimation(this._target);
  48502. };
  48503. StopAnimationAction.prototype.serialize = function (parent) {
  48504. return _super.prototype._serialize.call(this, {
  48505. name: "StopAnimationAction",
  48506. properties: [BABYLON.Action._GetTargetProperty(this._target)]
  48507. }, parent);
  48508. };
  48509. return StopAnimationAction;
  48510. }(BABYLON.Action));
  48511. BABYLON.StopAnimationAction = StopAnimationAction;
  48512. var DoNothingAction = /** @class */ (function (_super) {
  48513. __extends(DoNothingAction, _super);
  48514. function DoNothingAction(triggerOptions, condition) {
  48515. if (triggerOptions === void 0) { triggerOptions = BABYLON.ActionManager.NothingTrigger; }
  48516. return _super.call(this, triggerOptions, condition) || this;
  48517. }
  48518. DoNothingAction.prototype.execute = function () {
  48519. };
  48520. DoNothingAction.prototype.serialize = function (parent) {
  48521. return _super.prototype._serialize.call(this, {
  48522. name: "DoNothingAction",
  48523. properties: []
  48524. }, parent);
  48525. };
  48526. return DoNothingAction;
  48527. }(BABYLON.Action));
  48528. BABYLON.DoNothingAction = DoNothingAction;
  48529. var CombineAction = /** @class */ (function (_super) {
  48530. __extends(CombineAction, _super);
  48531. function CombineAction(triggerOptions, children, condition) {
  48532. var _this = _super.call(this, triggerOptions, condition) || this;
  48533. _this.children = children;
  48534. return _this;
  48535. }
  48536. CombineAction.prototype._prepare = function () {
  48537. for (var index = 0; index < this.children.length; index++) {
  48538. this.children[index]._actionManager = this._actionManager;
  48539. this.children[index]._prepare();
  48540. }
  48541. };
  48542. CombineAction.prototype.execute = function (evt) {
  48543. for (var index = 0; index < this.children.length; index++) {
  48544. this.children[index].execute(evt);
  48545. }
  48546. };
  48547. CombineAction.prototype.serialize = function (parent) {
  48548. var serializationObject = _super.prototype._serialize.call(this, {
  48549. name: "CombineAction",
  48550. properties: [],
  48551. combine: []
  48552. }, parent);
  48553. for (var i = 0; i < this.children.length; i++) {
  48554. serializationObject.combine.push(this.children[i].serialize(null));
  48555. }
  48556. return serializationObject;
  48557. };
  48558. return CombineAction;
  48559. }(BABYLON.Action));
  48560. BABYLON.CombineAction = CombineAction;
  48561. var ExecuteCodeAction = /** @class */ (function (_super) {
  48562. __extends(ExecuteCodeAction, _super);
  48563. function ExecuteCodeAction(triggerOptions, func, condition) {
  48564. var _this = _super.call(this, triggerOptions, condition) || this;
  48565. _this.func = func;
  48566. return _this;
  48567. }
  48568. ExecuteCodeAction.prototype.execute = function (evt) {
  48569. this.func(evt);
  48570. };
  48571. return ExecuteCodeAction;
  48572. }(BABYLON.Action));
  48573. BABYLON.ExecuteCodeAction = ExecuteCodeAction;
  48574. var SetParentAction = /** @class */ (function (_super) {
  48575. __extends(SetParentAction, _super);
  48576. function SetParentAction(triggerOptions, target, parent, condition) {
  48577. var _this = _super.call(this, triggerOptions, condition) || this;
  48578. _this._target = target;
  48579. _this._parent = parent;
  48580. return _this;
  48581. }
  48582. SetParentAction.prototype._prepare = function () {
  48583. };
  48584. SetParentAction.prototype.execute = function () {
  48585. if (this._target.parent === this._parent) {
  48586. return;
  48587. }
  48588. var invertParentWorldMatrix = this._parent.getWorldMatrix().clone();
  48589. invertParentWorldMatrix.invert();
  48590. this._target.position = BABYLON.Vector3.TransformCoordinates(this._target.position, invertParentWorldMatrix);
  48591. this._target.parent = this._parent;
  48592. };
  48593. SetParentAction.prototype.serialize = function (parent) {
  48594. return _super.prototype._serialize.call(this, {
  48595. name: "SetParentAction",
  48596. properties: [
  48597. BABYLON.Action._GetTargetProperty(this._target),
  48598. BABYLON.Action._GetTargetProperty(this._parent),
  48599. ]
  48600. }, parent);
  48601. };
  48602. return SetParentAction;
  48603. }(BABYLON.Action));
  48604. BABYLON.SetParentAction = SetParentAction;
  48605. var PlaySoundAction = /** @class */ (function (_super) {
  48606. __extends(PlaySoundAction, _super);
  48607. function PlaySoundAction(triggerOptions, sound, condition) {
  48608. var _this = _super.call(this, triggerOptions, condition) || this;
  48609. _this._sound = sound;
  48610. return _this;
  48611. }
  48612. PlaySoundAction.prototype._prepare = function () {
  48613. };
  48614. PlaySoundAction.prototype.execute = function () {
  48615. if (this._sound !== undefined)
  48616. this._sound.play();
  48617. };
  48618. PlaySoundAction.prototype.serialize = function (parent) {
  48619. return _super.prototype._serialize.call(this, {
  48620. name: "PlaySoundAction",
  48621. properties: [{ name: "sound", value: this._sound.name }]
  48622. }, parent);
  48623. };
  48624. return PlaySoundAction;
  48625. }(BABYLON.Action));
  48626. BABYLON.PlaySoundAction = PlaySoundAction;
  48627. var StopSoundAction = /** @class */ (function (_super) {
  48628. __extends(StopSoundAction, _super);
  48629. function StopSoundAction(triggerOptions, sound, condition) {
  48630. var _this = _super.call(this, triggerOptions, condition) || this;
  48631. _this._sound = sound;
  48632. return _this;
  48633. }
  48634. StopSoundAction.prototype._prepare = function () {
  48635. };
  48636. StopSoundAction.prototype.execute = function () {
  48637. if (this._sound !== undefined)
  48638. this._sound.stop();
  48639. };
  48640. StopSoundAction.prototype.serialize = function (parent) {
  48641. return _super.prototype._serialize.call(this, {
  48642. name: "StopSoundAction",
  48643. properties: [{ name: "sound", value: this._sound.name }]
  48644. }, parent);
  48645. };
  48646. return StopSoundAction;
  48647. }(BABYLON.Action));
  48648. BABYLON.StopSoundAction = StopSoundAction;
  48649. })(BABYLON || (BABYLON = {}));
  48650. //# sourceMappingURL=babylon.directActions.js.map
  48651. var BABYLON;
  48652. (function (BABYLON) {
  48653. var SpriteManager = /** @class */ (function () {
  48654. function SpriteManager(name, imgUrl, capacity, cellSize, scene, epsilon, samplingMode) {
  48655. if (epsilon === void 0) { epsilon = 0.01; }
  48656. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  48657. this.name = name;
  48658. this.sprites = new Array();
  48659. this.renderingGroupId = 0;
  48660. this.layerMask = 0x0FFFFFFF;
  48661. this.fogEnabled = true;
  48662. this.isPickable = false;
  48663. /**
  48664. * An event triggered when the manager is disposed.
  48665. * @type {BABYLON.Observable}
  48666. */
  48667. this.onDisposeObservable = new BABYLON.Observable();
  48668. this._vertexBuffers = {};
  48669. this._capacity = capacity;
  48670. this._spriteTexture = new BABYLON.Texture(imgUrl, scene, true, false, samplingMode);
  48671. this._spriteTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  48672. this._spriteTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  48673. if (cellSize.width && cellSize.height) {
  48674. this.cellWidth = cellSize.width;
  48675. this.cellHeight = cellSize.height;
  48676. }
  48677. else if (cellSize !== undefined) {
  48678. this.cellWidth = cellSize;
  48679. this.cellHeight = cellSize;
  48680. }
  48681. else {
  48682. return;
  48683. }
  48684. this._epsilon = epsilon;
  48685. this._scene = scene;
  48686. this._scene.spriteManagers.push(this);
  48687. var indices = [];
  48688. var index = 0;
  48689. for (var count = 0; count < capacity; count++) {
  48690. indices.push(index);
  48691. indices.push(index + 1);
  48692. indices.push(index + 2);
  48693. indices.push(index);
  48694. indices.push(index + 2);
  48695. indices.push(index + 3);
  48696. index += 4;
  48697. }
  48698. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  48699. // VBO
  48700. // 16 floats per sprite (x, y, z, angle, sizeX, sizeY, offsetX, offsetY, invertU, invertV, cellIndexX, cellIndexY, color r, color g, color b, color a)
  48701. this._vertexData = new Float32Array(capacity * 16 * 4);
  48702. this._buffer = new BABYLON.Buffer(scene.getEngine(), this._vertexData, true, 16);
  48703. var positions = this._buffer.createVertexBuffer(BABYLON.VertexBuffer.PositionKind, 0, 4);
  48704. var options = this._buffer.createVertexBuffer("options", 4, 4);
  48705. var cellInfo = this._buffer.createVertexBuffer("cellInfo", 8, 4);
  48706. var colors = this._buffer.createVertexBuffer(BABYLON.VertexBuffer.ColorKind, 12, 4);
  48707. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = positions;
  48708. this._vertexBuffers["options"] = options;
  48709. this._vertexBuffers["cellInfo"] = cellInfo;
  48710. this._vertexBuffers[BABYLON.VertexBuffer.ColorKind] = colors;
  48711. // Effects
  48712. this._effectBase = this._scene.getEngine().createEffect("sprites", [BABYLON.VertexBuffer.PositionKind, "options", "cellInfo", BABYLON.VertexBuffer.ColorKind], ["view", "projection", "textureInfos", "alphaTest"], ["diffuseSampler"], "");
  48713. this._effectFog = this._scene.getEngine().createEffect("sprites", [BABYLON.VertexBuffer.PositionKind, "options", "cellInfo", BABYLON.VertexBuffer.ColorKind], ["view", "projection", "textureInfos", "alphaTest", "vFogInfos", "vFogColor"], ["diffuseSampler"], "#define FOG");
  48714. }
  48715. Object.defineProperty(SpriteManager.prototype, "onDispose", {
  48716. set: function (callback) {
  48717. if (this._onDisposeObserver) {
  48718. this.onDisposeObservable.remove(this._onDisposeObserver);
  48719. }
  48720. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  48721. },
  48722. enumerable: true,
  48723. configurable: true
  48724. });
  48725. Object.defineProperty(SpriteManager.prototype, "texture", {
  48726. get: function () {
  48727. return this._spriteTexture;
  48728. },
  48729. set: function (value) {
  48730. this._spriteTexture = value;
  48731. },
  48732. enumerable: true,
  48733. configurable: true
  48734. });
  48735. SpriteManager.prototype._appendSpriteVertex = function (index, sprite, offsetX, offsetY, rowSize) {
  48736. var arrayOffset = index * 16;
  48737. if (offsetX === 0)
  48738. offsetX = this._epsilon;
  48739. else if (offsetX === 1)
  48740. offsetX = 1 - this._epsilon;
  48741. if (offsetY === 0)
  48742. offsetY = this._epsilon;
  48743. else if (offsetY === 1)
  48744. offsetY = 1 - this._epsilon;
  48745. this._vertexData[arrayOffset] = sprite.position.x;
  48746. this._vertexData[arrayOffset + 1] = sprite.position.y;
  48747. this._vertexData[arrayOffset + 2] = sprite.position.z;
  48748. this._vertexData[arrayOffset + 3] = sprite.angle;
  48749. this._vertexData[arrayOffset + 4] = sprite.width;
  48750. this._vertexData[arrayOffset + 5] = sprite.height;
  48751. this._vertexData[arrayOffset + 6] = offsetX;
  48752. this._vertexData[arrayOffset + 7] = offsetY;
  48753. this._vertexData[arrayOffset + 8] = sprite.invertU ? 1 : 0;
  48754. this._vertexData[arrayOffset + 9] = sprite.invertV ? 1 : 0;
  48755. var offset = (sprite.cellIndex / rowSize) >> 0;
  48756. this._vertexData[arrayOffset + 10] = sprite.cellIndex - offset * rowSize;
  48757. this._vertexData[arrayOffset + 11] = offset;
  48758. // Color
  48759. this._vertexData[arrayOffset + 12] = sprite.color.r;
  48760. this._vertexData[arrayOffset + 13] = sprite.color.g;
  48761. this._vertexData[arrayOffset + 14] = sprite.color.b;
  48762. this._vertexData[arrayOffset + 15] = sprite.color.a;
  48763. };
  48764. SpriteManager.prototype.intersects = function (ray, camera, predicate, fastCheck) {
  48765. var count = Math.min(this._capacity, this.sprites.length);
  48766. var min = BABYLON.Vector3.Zero();
  48767. var max = BABYLON.Vector3.Zero();
  48768. var distance = Number.MAX_VALUE;
  48769. var currentSprite = null;
  48770. var cameraSpacePosition = BABYLON.Vector3.Zero();
  48771. var cameraView = camera.getViewMatrix();
  48772. for (var index = 0; index < count; index++) {
  48773. var sprite = this.sprites[index];
  48774. if (!sprite) {
  48775. continue;
  48776. }
  48777. if (predicate) {
  48778. if (!predicate(sprite)) {
  48779. continue;
  48780. }
  48781. }
  48782. else if (!sprite.isPickable) {
  48783. continue;
  48784. }
  48785. BABYLON.Vector3.TransformCoordinatesToRef(sprite.position, cameraView, cameraSpacePosition);
  48786. min.copyFromFloats(cameraSpacePosition.x - sprite.width / 2, cameraSpacePosition.y - sprite.height / 2, cameraSpacePosition.z);
  48787. max.copyFromFloats(cameraSpacePosition.x + sprite.width / 2, cameraSpacePosition.y + sprite.height / 2, cameraSpacePosition.z);
  48788. if (ray.intersectsBoxMinMax(min, max)) {
  48789. var currentDistance = BABYLON.Vector3.Distance(cameraSpacePosition, ray.origin);
  48790. if (distance > currentDistance) {
  48791. distance = currentDistance;
  48792. currentSprite = sprite;
  48793. if (fastCheck) {
  48794. break;
  48795. }
  48796. }
  48797. }
  48798. }
  48799. if (currentSprite) {
  48800. var result = new BABYLON.PickingInfo();
  48801. result.hit = true;
  48802. result.pickedSprite = currentSprite;
  48803. result.distance = distance;
  48804. return result;
  48805. }
  48806. return null;
  48807. };
  48808. SpriteManager.prototype.render = function () {
  48809. // Check
  48810. if (!this._effectBase.isReady() || !this._effectFog.isReady() || !this._spriteTexture || !this._spriteTexture.isReady())
  48811. return;
  48812. var engine = this._scene.getEngine();
  48813. var baseSize = this._spriteTexture.getBaseSize();
  48814. // Sprites
  48815. var deltaTime = engine.getDeltaTime();
  48816. var max = Math.min(this._capacity, this.sprites.length);
  48817. var rowSize = baseSize.width / this.cellWidth;
  48818. var offset = 0;
  48819. for (var index = 0; index < max; index++) {
  48820. var sprite = this.sprites[index];
  48821. if (!sprite) {
  48822. continue;
  48823. }
  48824. sprite._animate(deltaTime);
  48825. this._appendSpriteVertex(offset++, sprite, 0, 0, rowSize);
  48826. this._appendSpriteVertex(offset++, sprite, 1, 0, rowSize);
  48827. this._appendSpriteVertex(offset++, sprite, 1, 1, rowSize);
  48828. this._appendSpriteVertex(offset++, sprite, 0, 1, rowSize);
  48829. }
  48830. this._buffer.update(this._vertexData);
  48831. // Render
  48832. var effect = this._effectBase;
  48833. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  48834. effect = this._effectFog;
  48835. }
  48836. engine.enableEffect(effect);
  48837. var viewMatrix = this._scene.getViewMatrix();
  48838. effect.setTexture("diffuseSampler", this._spriteTexture);
  48839. effect.setMatrix("view", viewMatrix);
  48840. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  48841. effect.setFloat2("textureInfos", this.cellWidth / baseSize.width, this.cellHeight / baseSize.height);
  48842. // Fog
  48843. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  48844. effect.setFloat4("vFogInfos", this._scene.fogMode, this._scene.fogStart, this._scene.fogEnd, this._scene.fogDensity);
  48845. effect.setColor3("vFogColor", this._scene.fogColor);
  48846. }
  48847. // VBOs
  48848. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  48849. // Draw order
  48850. engine.setDepthFunctionToLessOrEqual();
  48851. effect.setBool("alphaTest", true);
  48852. engine.setColorWrite(false);
  48853. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, max * 6);
  48854. engine.setColorWrite(true);
  48855. effect.setBool("alphaTest", false);
  48856. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  48857. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, max * 6);
  48858. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  48859. };
  48860. SpriteManager.prototype.dispose = function () {
  48861. if (this._buffer) {
  48862. this._buffer.dispose();
  48863. this._buffer = null;
  48864. }
  48865. if (this._indexBuffer) {
  48866. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  48867. this._indexBuffer = null;
  48868. }
  48869. if (this._spriteTexture) {
  48870. this._spriteTexture.dispose();
  48871. this._spriteTexture = null;
  48872. }
  48873. // Remove from scene
  48874. var index = this._scene.spriteManagers.indexOf(this);
  48875. this._scene.spriteManagers.splice(index, 1);
  48876. // Callback
  48877. this.onDisposeObservable.notifyObservers(this);
  48878. this.onDisposeObservable.clear();
  48879. };
  48880. return SpriteManager;
  48881. }());
  48882. BABYLON.SpriteManager = SpriteManager;
  48883. })(BABYLON || (BABYLON = {}));
  48884. //# sourceMappingURL=babylon.spriteManager.js.map
  48885. var BABYLON;
  48886. (function (BABYLON) {
  48887. var Sprite = /** @class */ (function () {
  48888. function Sprite(name, manager) {
  48889. this.name = name;
  48890. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  48891. this.width = 1.0;
  48892. this.height = 1.0;
  48893. this.angle = 0;
  48894. this.cellIndex = 0;
  48895. this.invertU = 0;
  48896. this.invertV = 0;
  48897. this.animations = new Array();
  48898. this.isPickable = false;
  48899. this._animationStarted = false;
  48900. this._loopAnimation = false;
  48901. this._fromIndex = 0;
  48902. this._toIndex = 0;
  48903. this._delay = 0;
  48904. this._direction = 1;
  48905. this._time = 0;
  48906. this._manager = manager;
  48907. this._manager.sprites.push(this);
  48908. this.position = BABYLON.Vector3.Zero();
  48909. }
  48910. Object.defineProperty(Sprite.prototype, "size", {
  48911. get: function () {
  48912. return this.width;
  48913. },
  48914. set: function (value) {
  48915. this.width = value;
  48916. this.height = value;
  48917. },
  48918. enumerable: true,
  48919. configurable: true
  48920. });
  48921. Sprite.prototype.playAnimation = function (from, to, loop, delay, onAnimationEnd) {
  48922. this._fromIndex = from;
  48923. this._toIndex = to;
  48924. this._loopAnimation = loop;
  48925. this._delay = delay;
  48926. this._animationStarted = true;
  48927. this._direction = from < to ? 1 : -1;
  48928. this.cellIndex = from;
  48929. this._time = 0;
  48930. this._onAnimationEnd = onAnimationEnd;
  48931. };
  48932. Sprite.prototype.stopAnimation = function () {
  48933. this._animationStarted = false;
  48934. };
  48935. Sprite.prototype._animate = function (deltaTime) {
  48936. if (!this._animationStarted)
  48937. return;
  48938. this._time += deltaTime;
  48939. if (this._time > this._delay) {
  48940. this._time = this._time % this._delay;
  48941. this.cellIndex += this._direction;
  48942. if (this.cellIndex > this._toIndex) {
  48943. if (this._loopAnimation) {
  48944. this.cellIndex = this._fromIndex;
  48945. }
  48946. else {
  48947. this.cellIndex = this._toIndex;
  48948. this._animationStarted = false;
  48949. if (this._onAnimationEnd) {
  48950. this._onAnimationEnd();
  48951. }
  48952. if (this.disposeWhenFinishedAnimating) {
  48953. this.dispose();
  48954. }
  48955. }
  48956. }
  48957. }
  48958. };
  48959. Sprite.prototype.dispose = function () {
  48960. for (var i = 0; i < this._manager.sprites.length; i++) {
  48961. if (this._manager.sprites[i] == this) {
  48962. this._manager.sprites.splice(i, 1);
  48963. }
  48964. }
  48965. };
  48966. return Sprite;
  48967. }());
  48968. BABYLON.Sprite = Sprite;
  48969. })(BABYLON || (BABYLON = {}));
  48970. //# sourceMappingURL=babylon.sprite.js.map
  48971. var BABYLON;
  48972. (function (BABYLON) {
  48973. var IntersectionInfo = /** @class */ (function () {
  48974. function IntersectionInfo(bu, bv, distance) {
  48975. this.bu = bu;
  48976. this.bv = bv;
  48977. this.distance = distance;
  48978. this.faceId = 0;
  48979. this.subMeshId = 0;
  48980. }
  48981. return IntersectionInfo;
  48982. }());
  48983. BABYLON.IntersectionInfo = IntersectionInfo;
  48984. var PickingInfo = /** @class */ (function () {
  48985. function PickingInfo() {
  48986. this.hit = false;
  48987. this.distance = 0;
  48988. this.pickedPoint = null;
  48989. this.pickedMesh = null;
  48990. this.bu = 0;
  48991. this.bv = 0;
  48992. this.faceId = -1;
  48993. this.subMeshId = 0;
  48994. this.pickedSprite = null;
  48995. }
  48996. // Methods
  48997. PickingInfo.prototype.getNormal = function (useWorldCoordinates, useVerticesNormals) {
  48998. if (useWorldCoordinates === void 0) { useWorldCoordinates = false; }
  48999. if (useVerticesNormals === void 0) { useVerticesNormals = true; }
  49000. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  49001. return null;
  49002. }
  49003. var indices = this.pickedMesh.getIndices();
  49004. if (!indices) {
  49005. return null;
  49006. }
  49007. var result;
  49008. if (useVerticesNormals) {
  49009. var normals = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  49010. var normal0 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3] * 3);
  49011. var normal1 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 1] * 3);
  49012. var normal2 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 2] * 3);
  49013. normal0 = normal0.scale(this.bu);
  49014. normal1 = normal1.scale(this.bv);
  49015. normal2 = normal2.scale(1.0 - this.bu - this.bv);
  49016. result = new BABYLON.Vector3(normal0.x + normal1.x + normal2.x, normal0.y + normal1.y + normal2.y, normal0.z + normal1.z + normal2.z);
  49017. }
  49018. else {
  49019. var positions = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  49020. var vertex1 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3] * 3);
  49021. var vertex2 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 1] * 3);
  49022. var vertex3 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 2] * 3);
  49023. var p1p2 = vertex1.subtract(vertex2);
  49024. var p3p2 = vertex3.subtract(vertex2);
  49025. result = BABYLON.Vector3.Cross(p1p2, p3p2);
  49026. }
  49027. if (useWorldCoordinates) {
  49028. result = BABYLON.Vector3.TransformNormal(result, this.pickedMesh.getWorldMatrix());
  49029. }
  49030. return BABYLON.Vector3.Normalize(result);
  49031. };
  49032. PickingInfo.prototype.getTextureCoordinates = function () {
  49033. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  49034. return null;
  49035. }
  49036. var indices = this.pickedMesh.getIndices();
  49037. if (!indices) {
  49038. return null;
  49039. }
  49040. var uvs = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  49041. if (!uvs) {
  49042. return null;
  49043. }
  49044. var uv0 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3] * 2);
  49045. var uv1 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 1] * 2);
  49046. var uv2 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 2] * 2);
  49047. uv0 = uv0.scale(1.0 - this.bu - this.bv);
  49048. uv1 = uv1.scale(this.bu);
  49049. uv2 = uv2.scale(this.bv);
  49050. return new BABYLON.Vector2(uv0.x + uv1.x + uv2.x, uv0.y + uv1.y + uv2.y);
  49051. };
  49052. return PickingInfo;
  49053. }());
  49054. BABYLON.PickingInfo = PickingInfo;
  49055. })(BABYLON || (BABYLON = {}));
  49056. //# sourceMappingURL=babylon.pickingInfo.js.map
  49057. var BABYLON;
  49058. (function (BABYLON) {
  49059. var Ray = /** @class */ (function () {
  49060. function Ray(origin, direction, length) {
  49061. if (length === void 0) { length = Number.MAX_VALUE; }
  49062. this.origin = origin;
  49063. this.direction = direction;
  49064. this.length = length;
  49065. }
  49066. // Methods
  49067. Ray.prototype.intersectsBoxMinMax = function (minimum, maximum) {
  49068. var d = 0.0;
  49069. var maxValue = Number.MAX_VALUE;
  49070. var inv;
  49071. var min;
  49072. var max;
  49073. var temp;
  49074. if (Math.abs(this.direction.x) < 0.0000001) {
  49075. if (this.origin.x < minimum.x || this.origin.x > maximum.x) {
  49076. return false;
  49077. }
  49078. }
  49079. else {
  49080. inv = 1.0 / this.direction.x;
  49081. min = (minimum.x - this.origin.x) * inv;
  49082. max = (maximum.x - this.origin.x) * inv;
  49083. if (max === -Infinity) {
  49084. max = Infinity;
  49085. }
  49086. if (min > max) {
  49087. temp = min;
  49088. min = max;
  49089. max = temp;
  49090. }
  49091. d = Math.max(min, d);
  49092. maxValue = Math.min(max, maxValue);
  49093. if (d > maxValue) {
  49094. return false;
  49095. }
  49096. }
  49097. if (Math.abs(this.direction.y) < 0.0000001) {
  49098. if (this.origin.y < minimum.y || this.origin.y > maximum.y) {
  49099. return false;
  49100. }
  49101. }
  49102. else {
  49103. inv = 1.0 / this.direction.y;
  49104. min = (minimum.y - this.origin.y) * inv;
  49105. max = (maximum.y - this.origin.y) * inv;
  49106. if (max === -Infinity) {
  49107. max = Infinity;
  49108. }
  49109. if (min > max) {
  49110. temp = min;
  49111. min = max;
  49112. max = temp;
  49113. }
  49114. d = Math.max(min, d);
  49115. maxValue = Math.min(max, maxValue);
  49116. if (d > maxValue) {
  49117. return false;
  49118. }
  49119. }
  49120. if (Math.abs(this.direction.z) < 0.0000001) {
  49121. if (this.origin.z < minimum.z || this.origin.z > maximum.z) {
  49122. return false;
  49123. }
  49124. }
  49125. else {
  49126. inv = 1.0 / this.direction.z;
  49127. min = (minimum.z - this.origin.z) * inv;
  49128. max = (maximum.z - this.origin.z) * inv;
  49129. if (max === -Infinity) {
  49130. max = Infinity;
  49131. }
  49132. if (min > max) {
  49133. temp = min;
  49134. min = max;
  49135. max = temp;
  49136. }
  49137. d = Math.max(min, d);
  49138. maxValue = Math.min(max, maxValue);
  49139. if (d > maxValue) {
  49140. return false;
  49141. }
  49142. }
  49143. return true;
  49144. };
  49145. Ray.prototype.intersectsBox = function (box) {
  49146. return this.intersectsBoxMinMax(box.minimum, box.maximum);
  49147. };
  49148. Ray.prototype.intersectsSphere = function (sphere) {
  49149. var x = sphere.center.x - this.origin.x;
  49150. var y = sphere.center.y - this.origin.y;
  49151. var z = sphere.center.z - this.origin.z;
  49152. var pyth = (x * x) + (y * y) + (z * z);
  49153. var rr = sphere.radius * sphere.radius;
  49154. if (pyth <= rr) {
  49155. return true;
  49156. }
  49157. var dot = (x * this.direction.x) + (y * this.direction.y) + (z * this.direction.z);
  49158. if (dot < 0.0) {
  49159. return false;
  49160. }
  49161. var temp = pyth - (dot * dot);
  49162. return temp <= rr;
  49163. };
  49164. Ray.prototype.intersectsTriangle = function (vertex0, vertex1, vertex2) {
  49165. if (!this._edge1) {
  49166. this._edge1 = BABYLON.Vector3.Zero();
  49167. this._edge2 = BABYLON.Vector3.Zero();
  49168. this._pvec = BABYLON.Vector3.Zero();
  49169. this._tvec = BABYLON.Vector3.Zero();
  49170. this._qvec = BABYLON.Vector3.Zero();
  49171. }
  49172. vertex1.subtractToRef(vertex0, this._edge1);
  49173. vertex2.subtractToRef(vertex0, this._edge2);
  49174. BABYLON.Vector3.CrossToRef(this.direction, this._edge2, this._pvec);
  49175. var det = BABYLON.Vector3.Dot(this._edge1, this._pvec);
  49176. if (det === 0) {
  49177. return null;
  49178. }
  49179. var invdet = 1 / det;
  49180. this.origin.subtractToRef(vertex0, this._tvec);
  49181. var bu = BABYLON.Vector3.Dot(this._tvec, this._pvec) * invdet;
  49182. if (bu < 0 || bu > 1.0) {
  49183. return null;
  49184. }
  49185. BABYLON.Vector3.CrossToRef(this._tvec, this._edge1, this._qvec);
  49186. var bv = BABYLON.Vector3.Dot(this.direction, this._qvec) * invdet;
  49187. if (bv < 0 || bu + bv > 1.0) {
  49188. return null;
  49189. }
  49190. //check if the distance is longer than the predefined length.
  49191. var distance = BABYLON.Vector3.Dot(this._edge2, this._qvec) * invdet;
  49192. if (distance > this.length) {
  49193. return null;
  49194. }
  49195. return new BABYLON.IntersectionInfo(bu, bv, distance);
  49196. };
  49197. Ray.prototype.intersectsPlane = function (plane) {
  49198. var distance;
  49199. var result1 = BABYLON.Vector3.Dot(plane.normal, this.direction);
  49200. if (Math.abs(result1) < 9.99999997475243E-07) {
  49201. return null;
  49202. }
  49203. else {
  49204. var result2 = BABYLON.Vector3.Dot(plane.normal, this.origin);
  49205. distance = (-plane.d - result2) / result1;
  49206. if (distance < 0.0) {
  49207. if (distance < -9.99999997475243E-07) {
  49208. return null;
  49209. }
  49210. else {
  49211. return 0;
  49212. }
  49213. }
  49214. return distance;
  49215. }
  49216. };
  49217. Ray.prototype.intersectsMesh = function (mesh, fastCheck) {
  49218. var tm = BABYLON.Tmp.Matrix[0];
  49219. mesh.getWorldMatrix().invertToRef(tm);
  49220. if (this._tmpRay) {
  49221. Ray.TransformToRef(this, tm, this._tmpRay);
  49222. }
  49223. else {
  49224. this._tmpRay = Ray.Transform(this, tm);
  49225. }
  49226. return mesh.intersects(this._tmpRay, fastCheck);
  49227. };
  49228. Ray.prototype.intersectsMeshes = function (meshes, fastCheck, results) {
  49229. if (results) {
  49230. results.length = 0;
  49231. }
  49232. else {
  49233. results = [];
  49234. }
  49235. for (var i = 0; i < meshes.length; i++) {
  49236. var pickInfo = this.intersectsMesh(meshes[i], fastCheck);
  49237. if (pickInfo.hit) {
  49238. results.push(pickInfo);
  49239. }
  49240. }
  49241. results.sort(this._comparePickingInfo);
  49242. return results;
  49243. };
  49244. Ray.prototype._comparePickingInfo = function (pickingInfoA, pickingInfoB) {
  49245. if (pickingInfoA.distance < pickingInfoB.distance) {
  49246. return -1;
  49247. }
  49248. else if (pickingInfoA.distance > pickingInfoB.distance) {
  49249. return 1;
  49250. }
  49251. else {
  49252. return 0;
  49253. }
  49254. };
  49255. /**
  49256. * Intersection test between the ray and a given segment whithin a given tolerance (threshold)
  49257. * @param sega the first point of the segment to test the intersection against
  49258. * @param segb the second point of the segment to test the intersection against
  49259. * @param threshold the tolerance margin, if the ray doesn't intersect the segment but is close to the given threshold, the intersection is successful
  49260. * @return the distance from the ray origin to the intersection point if there's intersection, or -1 if there's no intersection
  49261. */
  49262. Ray.prototype.intersectionSegment = function (sega, segb, threshold) {
  49263. var rsegb = this.origin.add(this.direction.multiplyByFloats(Ray.rayl, Ray.rayl, Ray.rayl));
  49264. var u = segb.subtract(sega);
  49265. var v = rsegb.subtract(this.origin);
  49266. var w = sega.subtract(this.origin);
  49267. var a = BABYLON.Vector3.Dot(u, u); // always >= 0
  49268. var b = BABYLON.Vector3.Dot(u, v);
  49269. var c = BABYLON.Vector3.Dot(v, v); // always >= 0
  49270. var d = BABYLON.Vector3.Dot(u, w);
  49271. var e = BABYLON.Vector3.Dot(v, w);
  49272. var D = a * c - b * b; // always >= 0
  49273. var sc, sN, sD = D; // sc = sN / sD, default sD = D >= 0
  49274. var tc, tN, tD = D; // tc = tN / tD, default tD = D >= 0
  49275. // compute the line parameters of the two closest points
  49276. if (D < Ray.smallnum) {
  49277. sN = 0.0; // force using point P0 on segment S1
  49278. sD = 1.0; // to prevent possible division by 0.0 later
  49279. tN = e;
  49280. tD = c;
  49281. }
  49282. else {
  49283. sN = (b * e - c * d);
  49284. tN = (a * e - b * d);
  49285. if (sN < 0.0) {
  49286. sN = 0.0;
  49287. tN = e;
  49288. tD = c;
  49289. }
  49290. else if (sN > sD) {
  49291. sN = sD;
  49292. tN = e + b;
  49293. tD = c;
  49294. }
  49295. }
  49296. if (tN < 0.0) {
  49297. tN = 0.0;
  49298. // recompute sc for this edge
  49299. if (-d < 0.0) {
  49300. sN = 0.0;
  49301. }
  49302. else if (-d > a)
  49303. sN = sD;
  49304. else {
  49305. sN = -d;
  49306. sD = a;
  49307. }
  49308. }
  49309. else if (tN > tD) {
  49310. tN = tD;
  49311. // recompute sc for this edge
  49312. if ((-d + b) < 0.0) {
  49313. sN = 0;
  49314. }
  49315. else if ((-d + b) > a) {
  49316. sN = sD;
  49317. }
  49318. else {
  49319. sN = (-d + b);
  49320. sD = a;
  49321. }
  49322. }
  49323. // finally do the division to get sc and tc
  49324. sc = (Math.abs(sN) < Ray.smallnum ? 0.0 : sN / sD);
  49325. tc = (Math.abs(tN) < Ray.smallnum ? 0.0 : tN / tD);
  49326. // get the difference of the two closest points
  49327. var qtc = v.multiplyByFloats(tc, tc, tc);
  49328. var dP = w.add(u.multiplyByFloats(sc, sc, sc)).subtract(qtc); // = S1(sc) - S2(tc)
  49329. var isIntersected = (tc > 0) && (tc <= this.length) && (dP.lengthSquared() < (threshold * threshold)); // return intersection result
  49330. if (isIntersected) {
  49331. return qtc.length();
  49332. }
  49333. return -1;
  49334. };
  49335. Ray.prototype.update = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  49336. BABYLON.Vector3.UnprojectFloatsToRef(x, y, 0, viewportWidth, viewportHeight, world, view, projection, this.origin);
  49337. BABYLON.Vector3.UnprojectFloatsToRef(x, y, 1, viewportWidth, viewportHeight, world, view, projection, BABYLON.Tmp.Vector3[0]);
  49338. BABYLON.Tmp.Vector3[0].subtractToRef(this.origin, this.direction);
  49339. this.direction.normalize();
  49340. return this;
  49341. };
  49342. // Statics
  49343. Ray.Zero = function () {
  49344. return new Ray(BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero());
  49345. };
  49346. Ray.CreateNew = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  49347. var result = Ray.Zero();
  49348. return result.update(x, y, viewportWidth, viewportHeight, world, view, projection);
  49349. };
  49350. /**
  49351. * 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
  49352. * transformed to the given world matrix.
  49353. * @param origin The origin point
  49354. * @param end The end point
  49355. * @param world a matrix to transform the ray to. Default is the identity matrix.
  49356. */
  49357. Ray.CreateNewFromTo = function (origin, end, world) {
  49358. if (world === void 0) { world = BABYLON.Matrix.Identity(); }
  49359. var direction = end.subtract(origin);
  49360. var length = Math.sqrt((direction.x * direction.x) + (direction.y * direction.y) + (direction.z * direction.z));
  49361. direction.normalize();
  49362. return Ray.Transform(new Ray(origin, direction, length), world);
  49363. };
  49364. Ray.Transform = function (ray, matrix) {
  49365. var result = new Ray(new BABYLON.Vector3(0, 0, 0), new BABYLON.Vector3(0, 0, 0));
  49366. Ray.TransformToRef(ray, matrix, result);
  49367. return result;
  49368. };
  49369. Ray.TransformToRef = function (ray, matrix, result) {
  49370. BABYLON.Vector3.TransformCoordinatesToRef(ray.origin, matrix, result.origin);
  49371. BABYLON.Vector3.TransformNormalToRef(ray.direction, matrix, result.direction);
  49372. result.length = ray.length;
  49373. var dir = result.direction;
  49374. var len = dir.length();
  49375. if (!(len === 0 || len === 1)) {
  49376. var num = 1.0 / len;
  49377. dir.x *= num;
  49378. dir.y *= num;
  49379. dir.z *= num;
  49380. result.length *= len;
  49381. }
  49382. };
  49383. Ray.smallnum = 0.00000001;
  49384. Ray.rayl = 10e8;
  49385. return Ray;
  49386. }());
  49387. BABYLON.Ray = Ray;
  49388. })(BABYLON || (BABYLON = {}));
  49389. //# sourceMappingURL=babylon.ray.js.map
  49390. var BABYLON;
  49391. (function (BABYLON) {
  49392. var intersectBoxAASphere = function (boxMin, boxMax, sphereCenter, sphereRadius) {
  49393. if (boxMin.x > sphereCenter.x + sphereRadius)
  49394. return false;
  49395. if (sphereCenter.x - sphereRadius > boxMax.x)
  49396. return false;
  49397. if (boxMin.y > sphereCenter.y + sphereRadius)
  49398. return false;
  49399. if (sphereCenter.y - sphereRadius > boxMax.y)
  49400. return false;
  49401. if (boxMin.z > sphereCenter.z + sphereRadius)
  49402. return false;
  49403. if (sphereCenter.z - sphereRadius > boxMax.z)
  49404. return false;
  49405. return true;
  49406. };
  49407. var getLowestRoot = (function () {
  49408. var result = { root: 0, found: false };
  49409. return function (a, b, c, maxR) {
  49410. result.root = 0;
  49411. result.found = false;
  49412. var determinant = b * b - 4.0 * a * c;
  49413. if (determinant < 0)
  49414. return result;
  49415. var sqrtD = Math.sqrt(determinant);
  49416. var r1 = (-b - sqrtD) / (2.0 * a);
  49417. var r2 = (-b + sqrtD) / (2.0 * a);
  49418. if (r1 > r2) {
  49419. var temp = r2;
  49420. r2 = r1;
  49421. r1 = temp;
  49422. }
  49423. if (r1 > 0 && r1 < maxR) {
  49424. result.root = r1;
  49425. result.found = true;
  49426. return result;
  49427. }
  49428. if (r2 > 0 && r2 < maxR) {
  49429. result.root = r2;
  49430. result.found = true;
  49431. return result;
  49432. }
  49433. return result;
  49434. };
  49435. })();
  49436. var Collider = /** @class */ (function () {
  49437. function Collider() {
  49438. this._collisionPoint = BABYLON.Vector3.Zero();
  49439. this._planeIntersectionPoint = BABYLON.Vector3.Zero();
  49440. this._tempVector = BABYLON.Vector3.Zero();
  49441. this._tempVector2 = BABYLON.Vector3.Zero();
  49442. this._tempVector3 = BABYLON.Vector3.Zero();
  49443. this._tempVector4 = BABYLON.Vector3.Zero();
  49444. this._edge = BABYLON.Vector3.Zero();
  49445. this._baseToVertex = BABYLON.Vector3.Zero();
  49446. this._destinationPoint = BABYLON.Vector3.Zero();
  49447. this._slidePlaneNormal = BABYLON.Vector3.Zero();
  49448. this._displacementVector = BABYLON.Vector3.Zero();
  49449. this._radius = BABYLON.Vector3.One();
  49450. this._retry = 0;
  49451. this._basePointWorld = BABYLON.Vector3.Zero();
  49452. this._velocityWorld = BABYLON.Vector3.Zero();
  49453. this._normalizedVelocity = BABYLON.Vector3.Zero();
  49454. this._collisionMask = -1;
  49455. }
  49456. Object.defineProperty(Collider.prototype, "collisionMask", {
  49457. get: function () {
  49458. return this._collisionMask;
  49459. },
  49460. set: function (mask) {
  49461. this._collisionMask = !isNaN(mask) ? mask : -1;
  49462. },
  49463. enumerable: true,
  49464. configurable: true
  49465. });
  49466. Object.defineProperty(Collider.prototype, "slidePlaneNormal", {
  49467. /**
  49468. * Gets the plane normal used to compute the sliding response (in local space)
  49469. */
  49470. get: function () {
  49471. return this._slidePlaneNormal;
  49472. },
  49473. enumerable: true,
  49474. configurable: true
  49475. });
  49476. // Methods
  49477. Collider.prototype._initialize = function (source, dir, e) {
  49478. this._velocity = dir;
  49479. BABYLON.Vector3.NormalizeToRef(dir, this._normalizedVelocity);
  49480. this._basePoint = source;
  49481. source.multiplyToRef(this._radius, this._basePointWorld);
  49482. dir.multiplyToRef(this._radius, this._velocityWorld);
  49483. this._velocityWorldLength = this._velocityWorld.length();
  49484. this._epsilon = e;
  49485. this.collisionFound = false;
  49486. };
  49487. Collider.prototype._checkPointInTriangle = function (point, pa, pb, pc, n) {
  49488. pa.subtractToRef(point, this._tempVector);
  49489. pb.subtractToRef(point, this._tempVector2);
  49490. BABYLON.Vector3.CrossToRef(this._tempVector, this._tempVector2, this._tempVector4);
  49491. var d = BABYLON.Vector3.Dot(this._tempVector4, n);
  49492. if (d < 0)
  49493. return false;
  49494. pc.subtractToRef(point, this._tempVector3);
  49495. BABYLON.Vector3.CrossToRef(this._tempVector2, this._tempVector3, this._tempVector4);
  49496. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  49497. if (d < 0)
  49498. return false;
  49499. BABYLON.Vector3.CrossToRef(this._tempVector3, this._tempVector, this._tempVector4);
  49500. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  49501. return d >= 0;
  49502. };
  49503. Collider.prototype._canDoCollision = function (sphereCenter, sphereRadius, vecMin, vecMax) {
  49504. var distance = BABYLON.Vector3.Distance(this._basePointWorld, sphereCenter);
  49505. var max = Math.max(this._radius.x, this._radius.y, this._radius.z);
  49506. if (distance > this._velocityWorldLength + max + sphereRadius) {
  49507. return false;
  49508. }
  49509. if (!intersectBoxAASphere(vecMin, vecMax, this._basePointWorld, this._velocityWorldLength + max))
  49510. return false;
  49511. return true;
  49512. };
  49513. Collider.prototype._testTriangle = function (faceIndex, trianglePlaneArray, p1, p2, p3, hasMaterial) {
  49514. var t0;
  49515. var embeddedInPlane = false;
  49516. //defensive programming, actually not needed.
  49517. if (!trianglePlaneArray) {
  49518. trianglePlaneArray = [];
  49519. }
  49520. if (!trianglePlaneArray[faceIndex]) {
  49521. trianglePlaneArray[faceIndex] = new BABYLON.Plane(0, 0, 0, 0);
  49522. trianglePlaneArray[faceIndex].copyFromPoints(p1, p2, p3);
  49523. }
  49524. var trianglePlane = trianglePlaneArray[faceIndex];
  49525. if ((!hasMaterial) && !trianglePlane.isFrontFacingTo(this._normalizedVelocity, 0))
  49526. return;
  49527. var signedDistToTrianglePlane = trianglePlane.signedDistanceTo(this._basePoint);
  49528. var normalDotVelocity = BABYLON.Vector3.Dot(trianglePlane.normal, this._velocity);
  49529. if (normalDotVelocity == 0) {
  49530. if (Math.abs(signedDistToTrianglePlane) >= 1.0)
  49531. return;
  49532. embeddedInPlane = true;
  49533. t0 = 0;
  49534. }
  49535. else {
  49536. t0 = (-1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  49537. var t1 = (1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  49538. if (t0 > t1) {
  49539. var temp = t1;
  49540. t1 = t0;
  49541. t0 = temp;
  49542. }
  49543. if (t0 > 1.0 || t1 < 0.0)
  49544. return;
  49545. if (t0 < 0)
  49546. t0 = 0;
  49547. if (t0 > 1.0)
  49548. t0 = 1.0;
  49549. }
  49550. this._collisionPoint.copyFromFloats(0, 0, 0);
  49551. var found = false;
  49552. var t = 1.0;
  49553. if (!embeddedInPlane) {
  49554. this._basePoint.subtractToRef(trianglePlane.normal, this._planeIntersectionPoint);
  49555. this._velocity.scaleToRef(t0, this._tempVector);
  49556. this._planeIntersectionPoint.addInPlace(this._tempVector);
  49557. if (this._checkPointInTriangle(this._planeIntersectionPoint, p1, p2, p3, trianglePlane.normal)) {
  49558. found = true;
  49559. t = t0;
  49560. this._collisionPoint.copyFrom(this._planeIntersectionPoint);
  49561. }
  49562. }
  49563. if (!found) {
  49564. var velocitySquaredLength = this._velocity.lengthSquared();
  49565. var a = velocitySquaredLength;
  49566. this._basePoint.subtractToRef(p1, this._tempVector);
  49567. var b = 2.0 * (BABYLON.Vector3.Dot(this._velocity, this._tempVector));
  49568. var c = this._tempVector.lengthSquared() - 1.0;
  49569. var lowestRoot = getLowestRoot(a, b, c, t);
  49570. if (lowestRoot.found) {
  49571. t = lowestRoot.root;
  49572. found = true;
  49573. this._collisionPoint.copyFrom(p1);
  49574. }
  49575. this._basePoint.subtractToRef(p2, this._tempVector);
  49576. b = 2.0 * (BABYLON.Vector3.Dot(this._velocity, this._tempVector));
  49577. c = this._tempVector.lengthSquared() - 1.0;
  49578. lowestRoot = getLowestRoot(a, b, c, t);
  49579. if (lowestRoot.found) {
  49580. t = lowestRoot.root;
  49581. found = true;
  49582. this._collisionPoint.copyFrom(p2);
  49583. }
  49584. this._basePoint.subtractToRef(p3, this._tempVector);
  49585. b = 2.0 * (BABYLON.Vector3.Dot(this._velocity, this._tempVector));
  49586. c = this._tempVector.lengthSquared() - 1.0;
  49587. lowestRoot = getLowestRoot(a, b, c, t);
  49588. if (lowestRoot.found) {
  49589. t = lowestRoot.root;
  49590. found = true;
  49591. this._collisionPoint.copyFrom(p3);
  49592. }
  49593. p2.subtractToRef(p1, this._edge);
  49594. p1.subtractToRef(this._basePoint, this._baseToVertex);
  49595. var edgeSquaredLength = this._edge.lengthSquared();
  49596. var edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this._velocity);
  49597. var edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  49598. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  49599. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  49600. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  49601. lowestRoot = getLowestRoot(a, b, c, t);
  49602. if (lowestRoot.found) {
  49603. var f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  49604. if (f >= 0.0 && f <= 1.0) {
  49605. t = lowestRoot.root;
  49606. found = true;
  49607. this._edge.scaleInPlace(f);
  49608. p1.addToRef(this._edge, this._collisionPoint);
  49609. }
  49610. }
  49611. p3.subtractToRef(p2, this._edge);
  49612. p2.subtractToRef(this._basePoint, this._baseToVertex);
  49613. edgeSquaredLength = this._edge.lengthSquared();
  49614. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this._velocity);
  49615. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  49616. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  49617. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  49618. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  49619. lowestRoot = getLowestRoot(a, b, c, t);
  49620. if (lowestRoot.found) {
  49621. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  49622. if (f >= 0.0 && f <= 1.0) {
  49623. t = lowestRoot.root;
  49624. found = true;
  49625. this._edge.scaleInPlace(f);
  49626. p2.addToRef(this._edge, this._collisionPoint);
  49627. }
  49628. }
  49629. p1.subtractToRef(p3, this._edge);
  49630. p3.subtractToRef(this._basePoint, this._baseToVertex);
  49631. edgeSquaredLength = this._edge.lengthSquared();
  49632. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this._velocity);
  49633. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  49634. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  49635. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  49636. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  49637. lowestRoot = getLowestRoot(a, b, c, t);
  49638. if (lowestRoot.found) {
  49639. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  49640. if (f >= 0.0 && f <= 1.0) {
  49641. t = lowestRoot.root;
  49642. found = true;
  49643. this._edge.scaleInPlace(f);
  49644. p3.addToRef(this._edge, this._collisionPoint);
  49645. }
  49646. }
  49647. }
  49648. if (found) {
  49649. var distToCollision = t * this._velocity.length();
  49650. if (!this.collisionFound || distToCollision < this._nearestDistance) {
  49651. if (!this.intersectionPoint) {
  49652. this.intersectionPoint = this._collisionPoint.clone();
  49653. }
  49654. else {
  49655. this.intersectionPoint.copyFrom(this._collisionPoint);
  49656. }
  49657. this._nearestDistance = distToCollision;
  49658. this.collisionFound = true;
  49659. }
  49660. }
  49661. };
  49662. Collider.prototype._collide = function (trianglePlaneArray, pts, indices, indexStart, indexEnd, decal, hasMaterial) {
  49663. for (var i = indexStart; i < indexEnd; i += 3) {
  49664. var p1 = pts[indices[i] - decal];
  49665. var p2 = pts[indices[i + 1] - decal];
  49666. var p3 = pts[indices[i + 2] - decal];
  49667. this._testTriangle(i, trianglePlaneArray, p3, p2, p1, hasMaterial);
  49668. }
  49669. };
  49670. Collider.prototype._getResponse = function (pos, vel) {
  49671. pos.addToRef(vel, this._destinationPoint);
  49672. vel.scaleInPlace((this._nearestDistance / vel.length()));
  49673. this._basePoint.addToRef(vel, pos);
  49674. pos.subtractToRef(this.intersectionPoint, this._slidePlaneNormal);
  49675. this._slidePlaneNormal.normalize();
  49676. this._slidePlaneNormal.scaleToRef(this._epsilon, this._displacementVector);
  49677. pos.addInPlace(this._displacementVector);
  49678. this.intersectionPoint.addInPlace(this._displacementVector);
  49679. this._slidePlaneNormal.scaleInPlace(BABYLON.Plane.SignedDistanceToPlaneFromPositionAndNormal(this.intersectionPoint, this._slidePlaneNormal, this._destinationPoint));
  49680. this._destinationPoint.subtractInPlace(this._slidePlaneNormal);
  49681. this._destinationPoint.subtractToRef(this.intersectionPoint, vel);
  49682. };
  49683. return Collider;
  49684. }());
  49685. BABYLON.Collider = Collider;
  49686. })(BABYLON || (BABYLON = {}));
  49687. //# sourceMappingURL=babylon.collider.js.map
  49688. var BABYLON;
  49689. (function (BABYLON) {
  49690. //WebWorker code will be inserted to this variable.
  49691. BABYLON.CollisionWorker = "";
  49692. var WorkerTaskType;
  49693. (function (WorkerTaskType) {
  49694. WorkerTaskType[WorkerTaskType["INIT"] = 0] = "INIT";
  49695. WorkerTaskType[WorkerTaskType["UPDATE"] = 1] = "UPDATE";
  49696. WorkerTaskType[WorkerTaskType["COLLIDE"] = 2] = "COLLIDE";
  49697. })(WorkerTaskType = BABYLON.WorkerTaskType || (BABYLON.WorkerTaskType = {}));
  49698. var WorkerReplyType;
  49699. (function (WorkerReplyType) {
  49700. WorkerReplyType[WorkerReplyType["SUCCESS"] = 0] = "SUCCESS";
  49701. WorkerReplyType[WorkerReplyType["UNKNOWN_ERROR"] = 1] = "UNKNOWN_ERROR";
  49702. })(WorkerReplyType = BABYLON.WorkerReplyType || (BABYLON.WorkerReplyType = {}));
  49703. var CollisionCoordinatorWorker = /** @class */ (function () {
  49704. function CollisionCoordinatorWorker() {
  49705. var _this = this;
  49706. this._scaledPosition = BABYLON.Vector3.Zero();
  49707. this._scaledVelocity = BABYLON.Vector3.Zero();
  49708. this.onMeshUpdated = function (transformNode) {
  49709. _this._addUpdateMeshesList[transformNode.uniqueId] = CollisionCoordinatorWorker.SerializeMesh(transformNode);
  49710. };
  49711. this.onGeometryUpdated = function (geometry) {
  49712. _this._addUpdateGeometriesList[geometry.id] = CollisionCoordinatorWorker.SerializeGeometry(geometry);
  49713. };
  49714. this._afterRender = function () {
  49715. if (!_this._init)
  49716. return;
  49717. if (_this._toRemoveGeometryArray.length == 0 && _this._toRemoveMeshesArray.length == 0 && Object.keys(_this._addUpdateGeometriesList).length == 0 && Object.keys(_this._addUpdateMeshesList).length == 0) {
  49718. return;
  49719. }
  49720. //5 concurrent updates were sent to the web worker and were not yet processed. Abort next update.
  49721. //TODO make sure update runs as fast as possible to be able to update 60 FPS.
  49722. if (_this._runningUpdated > 4) {
  49723. return;
  49724. }
  49725. ++_this._runningUpdated;
  49726. var payload = {
  49727. updatedMeshes: _this._addUpdateMeshesList,
  49728. updatedGeometries: _this._addUpdateGeometriesList,
  49729. removedGeometries: _this._toRemoveGeometryArray,
  49730. removedMeshes: _this._toRemoveMeshesArray
  49731. };
  49732. var message = {
  49733. payload: payload,
  49734. taskType: WorkerTaskType.UPDATE
  49735. };
  49736. var serializable = [];
  49737. for (var id in payload.updatedGeometries) {
  49738. if (payload.updatedGeometries.hasOwnProperty(id)) {
  49739. //prepare transferables
  49740. serializable.push(message.payload.updatedGeometries[id].indices.buffer);
  49741. serializable.push(message.payload.updatedGeometries[id].normals.buffer);
  49742. serializable.push(message.payload.updatedGeometries[id].positions.buffer);
  49743. }
  49744. }
  49745. _this._worker.postMessage(message, serializable);
  49746. _this._addUpdateMeshesList = {};
  49747. _this._addUpdateGeometriesList = {};
  49748. _this._toRemoveGeometryArray = [];
  49749. _this._toRemoveMeshesArray = [];
  49750. };
  49751. this._onMessageFromWorker = function (e) {
  49752. var returnData = e.data;
  49753. if (returnData.error != WorkerReplyType.SUCCESS) {
  49754. //TODO what errors can be returned from the worker?
  49755. BABYLON.Tools.Warn("error returned from worker!");
  49756. return;
  49757. }
  49758. switch (returnData.taskType) {
  49759. case WorkerTaskType.INIT:
  49760. _this._init = true;
  49761. //Update the worked with ALL of the scene's current state
  49762. _this._scene.meshes.forEach(function (mesh) {
  49763. _this.onMeshAdded(mesh);
  49764. });
  49765. _this._scene.getGeometries().forEach(function (geometry) {
  49766. _this.onGeometryAdded(geometry);
  49767. });
  49768. break;
  49769. case WorkerTaskType.UPDATE:
  49770. _this._runningUpdated--;
  49771. break;
  49772. case WorkerTaskType.COLLIDE:
  49773. var returnPayload = returnData.payload;
  49774. if (!_this._collisionsCallbackArray[returnPayload.collisionId])
  49775. return;
  49776. var callback = _this._collisionsCallbackArray[returnPayload.collisionId];
  49777. if (callback) {
  49778. var mesh = _this._scene.getMeshByUniqueID(returnPayload.collidedMeshUniqueId);
  49779. if (mesh) {
  49780. callback(returnPayload.collisionId, BABYLON.Vector3.FromArray(returnPayload.newPosition), mesh);
  49781. }
  49782. }
  49783. //cleanup
  49784. _this._collisionsCallbackArray[returnPayload.collisionId] = null;
  49785. break;
  49786. }
  49787. };
  49788. this._collisionsCallbackArray = [];
  49789. this._init = false;
  49790. this._runningUpdated = 0;
  49791. this._addUpdateMeshesList = {};
  49792. this._addUpdateGeometriesList = {};
  49793. this._toRemoveGeometryArray = [];
  49794. this._toRemoveMeshesArray = [];
  49795. }
  49796. CollisionCoordinatorWorker.prototype.getNewPosition = function (position, displacement, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  49797. if (!this._init)
  49798. return;
  49799. if (this._collisionsCallbackArray[collisionIndex] || this._collisionsCallbackArray[collisionIndex + 100000])
  49800. return;
  49801. position.divideToRef(collider._radius, this._scaledPosition);
  49802. displacement.divideToRef(collider._radius, this._scaledVelocity);
  49803. this._collisionsCallbackArray[collisionIndex] = onNewPosition;
  49804. var payload = {
  49805. collider: {
  49806. position: this._scaledPosition.asArray(),
  49807. velocity: this._scaledVelocity.asArray(),
  49808. radius: collider._radius.asArray()
  49809. },
  49810. collisionId: collisionIndex,
  49811. excludedMeshUniqueId: excludedMesh ? excludedMesh.uniqueId : null,
  49812. maximumRetry: maximumRetry
  49813. };
  49814. var message = {
  49815. payload: payload,
  49816. taskType: WorkerTaskType.COLLIDE
  49817. };
  49818. this._worker.postMessage(message);
  49819. };
  49820. CollisionCoordinatorWorker.prototype.init = function (scene) {
  49821. this._scene = scene;
  49822. this._scene.registerAfterRender(this._afterRender);
  49823. var workerUrl = BABYLON.WorkerIncluded ? BABYLON.Engine.CodeRepository + "Collisions/babylon.collisionWorker.js" : URL.createObjectURL(new Blob([BABYLON.CollisionWorker], { type: 'application/javascript' }));
  49824. this._worker = new Worker(workerUrl);
  49825. this._worker.onmessage = this._onMessageFromWorker;
  49826. var message = {
  49827. payload: {},
  49828. taskType: WorkerTaskType.INIT
  49829. };
  49830. this._worker.postMessage(message);
  49831. };
  49832. CollisionCoordinatorWorker.prototype.destroy = function () {
  49833. this._scene.unregisterAfterRender(this._afterRender);
  49834. this._worker.terminate();
  49835. };
  49836. CollisionCoordinatorWorker.prototype.onMeshAdded = function (mesh) {
  49837. mesh.registerAfterWorldMatrixUpdate(this.onMeshUpdated);
  49838. this.onMeshUpdated(mesh);
  49839. };
  49840. CollisionCoordinatorWorker.prototype.onMeshRemoved = function (mesh) {
  49841. this._toRemoveMeshesArray.push(mesh.uniqueId);
  49842. };
  49843. CollisionCoordinatorWorker.prototype.onGeometryAdded = function (geometry) {
  49844. //TODO this will break if the user uses his own function. This should be an array of callbacks!
  49845. geometry.onGeometryUpdated = this.onGeometryUpdated;
  49846. this.onGeometryUpdated(geometry);
  49847. };
  49848. CollisionCoordinatorWorker.prototype.onGeometryDeleted = function (geometry) {
  49849. this._toRemoveGeometryArray.push(geometry.id);
  49850. };
  49851. CollisionCoordinatorWorker.SerializeMesh = function (mesh) {
  49852. var submeshes = [];
  49853. if (mesh.subMeshes) {
  49854. submeshes = mesh.subMeshes.map(function (sm, idx) {
  49855. var boundingInfo = sm.getBoundingInfo();
  49856. return {
  49857. position: idx,
  49858. verticesStart: sm.verticesStart,
  49859. verticesCount: sm.verticesCount,
  49860. indexStart: sm.indexStart,
  49861. indexCount: sm.indexCount,
  49862. hasMaterial: !!sm.getMaterial(),
  49863. sphereCenter: boundingInfo.boundingSphere.centerWorld.asArray(),
  49864. sphereRadius: boundingInfo.boundingSphere.radiusWorld,
  49865. boxMinimum: boundingInfo.boundingBox.minimumWorld.asArray(),
  49866. boxMaximum: boundingInfo.boundingBox.maximumWorld.asArray()
  49867. };
  49868. });
  49869. }
  49870. var geometryId = null;
  49871. if (mesh instanceof BABYLON.Mesh) {
  49872. var geometry = mesh.geometry;
  49873. geometryId = geometry ? geometry.id : null;
  49874. }
  49875. else if (mesh instanceof BABYLON.InstancedMesh) {
  49876. var geometry = mesh.sourceMesh.geometry;
  49877. geometryId = geometry ? geometry.id : null;
  49878. }
  49879. var boundingInfo = mesh.getBoundingInfo();
  49880. return {
  49881. uniqueId: mesh.uniqueId,
  49882. id: mesh.id,
  49883. name: mesh.name,
  49884. geometryId: geometryId,
  49885. sphereCenter: boundingInfo.boundingSphere.centerWorld.asArray(),
  49886. sphereRadius: boundingInfo.boundingSphere.radiusWorld,
  49887. boxMinimum: boundingInfo.boundingBox.minimumWorld.asArray(),
  49888. boxMaximum: boundingInfo.boundingBox.maximumWorld.asArray(),
  49889. worldMatrixFromCache: mesh.worldMatrixFromCache.asArray(),
  49890. subMeshes: submeshes,
  49891. checkCollisions: mesh.checkCollisions
  49892. };
  49893. };
  49894. CollisionCoordinatorWorker.SerializeGeometry = function (geometry) {
  49895. return {
  49896. id: geometry.id,
  49897. positions: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []),
  49898. normals: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []),
  49899. indices: new Uint32Array(geometry.getIndices() || []),
  49900. };
  49901. };
  49902. return CollisionCoordinatorWorker;
  49903. }());
  49904. BABYLON.CollisionCoordinatorWorker = CollisionCoordinatorWorker;
  49905. var CollisionCoordinatorLegacy = /** @class */ (function () {
  49906. function CollisionCoordinatorLegacy() {
  49907. this._scaledPosition = BABYLON.Vector3.Zero();
  49908. this._scaledVelocity = BABYLON.Vector3.Zero();
  49909. this._finalPosition = BABYLON.Vector3.Zero();
  49910. }
  49911. CollisionCoordinatorLegacy.prototype.getNewPosition = function (position, displacement, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  49912. position.divideToRef(collider._radius, this._scaledPosition);
  49913. displacement.divideToRef(collider._radius, this._scaledVelocity);
  49914. collider.collidedMesh = null;
  49915. collider._retry = 0;
  49916. collider._initialVelocity = this._scaledVelocity;
  49917. collider._initialPosition = this._scaledPosition;
  49918. this._collideWithWorld(this._scaledPosition, this._scaledVelocity, collider, maximumRetry, this._finalPosition, excludedMesh);
  49919. this._finalPosition.multiplyInPlace(collider._radius);
  49920. //run the callback
  49921. onNewPosition(collisionIndex, this._finalPosition, collider.collidedMesh);
  49922. };
  49923. CollisionCoordinatorLegacy.prototype.init = function (scene) {
  49924. this._scene = scene;
  49925. };
  49926. CollisionCoordinatorLegacy.prototype.destroy = function () {
  49927. //Legacy need no destruction method.
  49928. };
  49929. //No update in legacy mode
  49930. CollisionCoordinatorLegacy.prototype.onMeshAdded = function (mesh) { };
  49931. CollisionCoordinatorLegacy.prototype.onMeshUpdated = function (mesh) { };
  49932. CollisionCoordinatorLegacy.prototype.onMeshRemoved = function (mesh) { };
  49933. CollisionCoordinatorLegacy.prototype.onGeometryAdded = function (geometry) { };
  49934. CollisionCoordinatorLegacy.prototype.onGeometryUpdated = function (geometry) { };
  49935. CollisionCoordinatorLegacy.prototype.onGeometryDeleted = function (geometry) { };
  49936. CollisionCoordinatorLegacy.prototype._collideWithWorld = function (position, velocity, collider, maximumRetry, finalPosition, excludedMesh) {
  49937. if (excludedMesh === void 0) { excludedMesh = null; }
  49938. var closeDistance = BABYLON.Engine.CollisionsEpsilon * 10.0;
  49939. if (collider._retry >= maximumRetry) {
  49940. finalPosition.copyFrom(position);
  49941. return;
  49942. }
  49943. // Check if this is a mesh else camera or -1
  49944. var collisionMask = (excludedMesh ? excludedMesh.collisionMask : collider.collisionMask);
  49945. collider._initialize(position, velocity, closeDistance);
  49946. // Check all meshes
  49947. for (var index = 0; index < this._scene.meshes.length; index++) {
  49948. var mesh = this._scene.meshes[index];
  49949. if (mesh.isEnabled() && mesh.checkCollisions && mesh.subMeshes && mesh !== excludedMesh && ((collisionMask & mesh.collisionGroup) !== 0)) {
  49950. mesh._checkCollision(collider);
  49951. }
  49952. }
  49953. if (!collider.collisionFound) {
  49954. position.addToRef(velocity, finalPosition);
  49955. return;
  49956. }
  49957. if (velocity.x !== 0 || velocity.y !== 0 || velocity.z !== 0) {
  49958. collider._getResponse(position, velocity);
  49959. }
  49960. if (velocity.length() <= closeDistance) {
  49961. finalPosition.copyFrom(position);
  49962. return;
  49963. }
  49964. collider._retry++;
  49965. this._collideWithWorld(position, velocity, collider, maximumRetry, finalPosition, excludedMesh);
  49966. };
  49967. return CollisionCoordinatorLegacy;
  49968. }());
  49969. BABYLON.CollisionCoordinatorLegacy = CollisionCoordinatorLegacy;
  49970. })(BABYLON || (BABYLON = {}));
  49971. //# sourceMappingURL=babylon.collisionCoordinator.js.map
  49972. var BABYLON;
  49973. (function (BABYLON) {
  49974. /**
  49975. * A particle represents one of the element emitted by a particle system.
  49976. * This is mainly define by its coordinates, direction, velocity and age.
  49977. */
  49978. var Particle = /** @class */ (function () {
  49979. /**
  49980. * Creates a new instance of @see Particle
  49981. * @param particleSystem the particle system the particle belongs to
  49982. */
  49983. function Particle(particleSystem) {
  49984. this.particleSystem = particleSystem;
  49985. /**
  49986. * The world position of the particle in the scene.
  49987. */
  49988. this.position = BABYLON.Vector3.Zero();
  49989. /**
  49990. * The world direction of the particle in the scene.
  49991. */
  49992. this.direction = BABYLON.Vector3.Zero();
  49993. /**
  49994. * The color of the particle.
  49995. */
  49996. this.color = new BABYLON.Color4(0, 0, 0, 0);
  49997. /**
  49998. * The color change of the particle per step.
  49999. */
  50000. this.colorStep = new BABYLON.Color4(0, 0, 0, 0);
  50001. /**
  50002. * Defines how long will the life of the particle be.
  50003. */
  50004. this.lifeTime = 1.0;
  50005. /**
  50006. * The current age of the particle.
  50007. */
  50008. this.age = 0;
  50009. /**
  50010. * The current size of the particle.
  50011. */
  50012. this.size = 0;
  50013. /**
  50014. * The current angle of the particle.
  50015. */
  50016. this.angle = 0;
  50017. /**
  50018. * Defines how fast is the angle changing.
  50019. */
  50020. this.angularSpeed = 0;
  50021. /**
  50022. * Defines the cell index used by the particle to be rendered from a sprite.
  50023. */
  50024. this.cellIndex = 0;
  50025. this._currentFrameCounter = 0;
  50026. if (!this.particleSystem.isAnimationSheetEnabled) {
  50027. return;
  50028. }
  50029. this.cellIndex = this.particleSystem.startSpriteCellID;
  50030. if (this.particleSystem.spriteCellChangeSpeed == 0) {
  50031. this.updateCellIndex = this.updateCellIndexWithSpeedCalculated;
  50032. }
  50033. else {
  50034. this.updateCellIndex = this.updateCellIndexWithCustomSpeed;
  50035. }
  50036. }
  50037. Particle.prototype.updateCellIndexWithSpeedCalculated = function (scaledUpdateSpeed) {
  50038. // (ageOffset / scaledUpdateSpeed) / available cells
  50039. var numberOfScaledUpdatesPerCell = ((this.lifeTime - this.age) / scaledUpdateSpeed) / (this.particleSystem.endSpriteCellID + 1 - this.cellIndex);
  50040. this._currentFrameCounter += scaledUpdateSpeed;
  50041. if (this._currentFrameCounter >= numberOfScaledUpdatesPerCell * scaledUpdateSpeed) {
  50042. this._currentFrameCounter = 0;
  50043. this.cellIndex++;
  50044. if (this.cellIndex > this.particleSystem.endSpriteCellID) {
  50045. this.cellIndex = this.particleSystem.endSpriteCellID;
  50046. }
  50047. }
  50048. };
  50049. Particle.prototype.updateCellIndexWithCustomSpeed = function () {
  50050. if (this._currentFrameCounter >= this.particleSystem.spriteCellChangeSpeed) {
  50051. this.cellIndex++;
  50052. this._currentFrameCounter = 0;
  50053. if (this.cellIndex > this.particleSystem.endSpriteCellID) {
  50054. if (this.particleSystem.spriteCellLoop) {
  50055. this.cellIndex = this.particleSystem.startSpriteCellID;
  50056. }
  50057. else {
  50058. this.cellIndex = this.particleSystem.endSpriteCellID;
  50059. }
  50060. }
  50061. }
  50062. else {
  50063. this._currentFrameCounter++;
  50064. }
  50065. };
  50066. /**
  50067. * Copy the properties of particle to another one.
  50068. * @param other the particle to copy the information to.
  50069. */
  50070. Particle.prototype.copyTo = function (other) {
  50071. other.position.copyFrom(this.position);
  50072. other.direction.copyFrom(this.direction);
  50073. other.color.copyFrom(this.color);
  50074. other.colorStep.copyFrom(this.colorStep);
  50075. other.lifeTime = this.lifeTime;
  50076. other.age = this.age;
  50077. other.size = this.size;
  50078. other.angle = this.angle;
  50079. other.angularSpeed = this.angularSpeed;
  50080. other.particleSystem = this.particleSystem;
  50081. other.cellIndex = this.cellIndex;
  50082. };
  50083. return Particle;
  50084. }());
  50085. BABYLON.Particle = Particle;
  50086. })(BABYLON || (BABYLON = {}));
  50087. //# sourceMappingURL=babylon.particle.js.map
  50088. var BABYLON;
  50089. (function (BABYLON) {
  50090. /**
  50091. * This represents a particle system in Babylon.
  50092. * 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.
  50093. * Particles can take different shapes while emitted like box, sphere, cone or you can write your custom function.
  50094. * @example https://doc.babylonjs.com/babylon101/particles
  50095. */
  50096. var ParticleSystem = /** @class */ (function () {
  50097. /**
  50098. * Instantiates a particle system.
  50099. * 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.
  50100. * @param name The name of the particle system
  50101. * @param capacity The max number of particles alive at the same time
  50102. * @param scene The scene the particle system belongs to
  50103. * @param customEffect a custom effect used to change the way particles are rendered by default
  50104. * @param isAnimationSheetEnabled Must be true if using a spritesheet to animate the particles texture
  50105. * @param epsilon Offset used to render the particles
  50106. */
  50107. function ParticleSystem(name, capacity, scene, customEffect, isAnimationSheetEnabled, epsilon) {
  50108. if (customEffect === void 0) { customEffect = null; }
  50109. if (isAnimationSheetEnabled === void 0) { isAnimationSheetEnabled = false; }
  50110. if (epsilon === void 0) { epsilon = 0.01; }
  50111. var _this = this;
  50112. /**
  50113. * List of animations used by the particle system.
  50114. */
  50115. this.animations = [];
  50116. /**
  50117. * The rendering group used by the Particle system to chose when to render.
  50118. */
  50119. this.renderingGroupId = 0;
  50120. /**
  50121. * The emitter represents the Mesh or position we are attaching the particle system to.
  50122. */
  50123. this.emitter = null;
  50124. /**
  50125. * The maximum number of particles to emit per frame
  50126. */
  50127. this.emitRate = 10;
  50128. /**
  50129. * If you want to launch only a few particles at once, that can be done, as well.
  50130. */
  50131. this.manualEmitCount = -1;
  50132. /**
  50133. * The overall motion speed (0.01 is default update speed, faster updates = faster animation)
  50134. */
  50135. this.updateSpeed = 0.01;
  50136. /**
  50137. * The amount of time the particle system is running (depends of the overall speed above).
  50138. */
  50139. this.targetStopDuration = 0;
  50140. /**
  50141. * Specifies whether the particle system will be disposed once it reaches the end of the animation.
  50142. */
  50143. this.disposeOnStop = false;
  50144. /**
  50145. * Minimum power of emitting particles.
  50146. */
  50147. this.minEmitPower = 1;
  50148. /**
  50149. * Maximum power of emitting particles.
  50150. */
  50151. this.maxEmitPower = 1;
  50152. /**
  50153. * Minimum life time of emitting particles.
  50154. */
  50155. this.minLifeTime = 1;
  50156. /**
  50157. * Maximum life time of emitting particles.
  50158. */
  50159. this.maxLifeTime = 1;
  50160. /**
  50161. * Minimum Size of emitting particles.
  50162. */
  50163. this.minSize = 1;
  50164. /**
  50165. * Maximum Size of emitting particles.
  50166. */
  50167. this.maxSize = 1;
  50168. /**
  50169. * Minimum angular speed of emitting particles (Z-axis rotation for each particle).
  50170. */
  50171. this.minAngularSpeed = 0;
  50172. /**
  50173. * Maximum angular speed of emitting particles (Z-axis rotation for each particle).
  50174. */
  50175. this.maxAngularSpeed = 0;
  50176. /**
  50177. * The layer mask we are rendering the particles through.
  50178. */
  50179. this.layerMask = 0x0FFFFFFF;
  50180. /**
  50181. * This can help using your own shader to render the particle system.
  50182. * The according effect will be created
  50183. */
  50184. this.customShader = null;
  50185. /**
  50186. * By default particle system starts as soon as they are created. This prevents the
  50187. * automatic start to happen and let you decide when to start emitting particles.
  50188. */
  50189. this.preventAutoStart = false;
  50190. /**
  50191. * Callback triggered when the particle animation is ending.
  50192. */
  50193. this.onAnimationEnd = null;
  50194. /**
  50195. * Blend mode use to render the particle, it can be either ParticleSystem.BLENDMODE_ONEONE or ParticleSystem.BLENDMODE_STANDARD.
  50196. */
  50197. this.blendMode = ParticleSystem.BLENDMODE_ONEONE;
  50198. /**
  50199. * Forces the particle to write their depth information to the depth buffer. This can help preventing other draw calls
  50200. * to override the particles.
  50201. */
  50202. this.forceDepthWrite = false;
  50203. /**
  50204. * You can use gravity if you want to give an orientation to your particles.
  50205. */
  50206. this.gravity = BABYLON.Vector3.Zero();
  50207. /**
  50208. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  50209. */
  50210. this.direction1 = new BABYLON.Vector3(0, 1.0, 0);
  50211. /**
  50212. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  50213. */
  50214. this.direction2 = new BABYLON.Vector3(0, 1.0, 0);
  50215. /**
  50216. * 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.
  50217. */
  50218. this.minEmitBox = new BABYLON.Vector3(-0.5, -0.5, -0.5);
  50219. /**
  50220. * 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.
  50221. */
  50222. this.maxEmitBox = new BABYLON.Vector3(0.5, 0.5, 0.5);
  50223. /**
  50224. * Random color of each particle after it has been emitted, between color1 and color2 vectors.
  50225. */
  50226. this.color1 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  50227. /**
  50228. * Random color of each particle after it has been emitted, between color1 and color2 vectors.
  50229. */
  50230. this.color2 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  50231. /**
  50232. * Color the particle will have at the end of its lifetime.
  50233. */
  50234. this.colorDead = new BABYLON.Color4(0, 0, 0, 1.0);
  50235. /**
  50236. * An optional mask to filter some colors out of the texture, or filter a part of the alpha channel.
  50237. */
  50238. this.textureMask = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  50239. /**
  50240. * If using a spritesheet (isAnimationSheetEnabled), defines if the sprite animation should loop between startSpriteCellID and endSpriteCellID or not.
  50241. */
  50242. this.spriteCellLoop = true;
  50243. /**
  50244. * If using a spritesheet (isAnimationSheetEnabled) and spriteCellLoop defines the speed of the sprite loop.
  50245. */
  50246. this.spriteCellChangeSpeed = 0;
  50247. /**
  50248. * If using a spritesheet (isAnimationSheetEnabled) and spriteCellLoop defines the first sprite cell to display.
  50249. */
  50250. this.startSpriteCellID = 0;
  50251. /**
  50252. * If using a spritesheet (isAnimationSheetEnabled) and spriteCellLoop defines the last sprite cell to display.
  50253. */
  50254. this.endSpriteCellID = 0;
  50255. /**
  50256. * If using a spritesheet (isAnimationSheetEnabled), defines the sprite cell width to use.
  50257. */
  50258. this.spriteCellWidth = 0;
  50259. /**
  50260. * If using a spritesheet (isAnimationSheetEnabled), defines the sprite cell height to use.
  50261. */
  50262. this.spriteCellHeight = 0;
  50263. /**
  50264. * An event triggered when the system is disposed.
  50265. */
  50266. this.onDisposeObservable = new BABYLON.Observable();
  50267. this._particles = new Array();
  50268. this._stockParticles = new Array();
  50269. this._newPartsExcess = 0;
  50270. this._vertexBuffers = {};
  50271. this._scaledColorStep = new BABYLON.Color4(0, 0, 0, 0);
  50272. this._colorDiff = new BABYLON.Color4(0, 0, 0, 0);
  50273. this._scaledDirection = BABYLON.Vector3.Zero();
  50274. this._scaledGravity = BABYLON.Vector3.Zero();
  50275. this._currentRenderId = -1;
  50276. this._started = false;
  50277. this._stopped = false;
  50278. this._actualFrame = 0;
  50279. this._vertexBufferSize = 11;
  50280. this._appendParticleVertexes = null;
  50281. this.id = name;
  50282. this.name = name;
  50283. this._capacity = capacity;
  50284. this._epsilon = epsilon;
  50285. this._isAnimationSheetEnabled = isAnimationSheetEnabled;
  50286. if (isAnimationSheetEnabled) {
  50287. this._vertexBufferSize = 12;
  50288. }
  50289. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  50290. this._customEffect = customEffect;
  50291. scene.particleSystems.push(this);
  50292. this._createIndexBuffer();
  50293. // 11 floats per particle (x, y, z, r, g, b, a, angle, size, offsetX, offsetY) + 1 filler
  50294. this._vertexData = new Float32Array(capacity * this._vertexBufferSize * 4);
  50295. this._vertexBuffer = new BABYLON.Buffer(scene.getEngine(), this._vertexData, true, this._vertexBufferSize);
  50296. var positions = this._vertexBuffer.createVertexBuffer(BABYLON.VertexBuffer.PositionKind, 0, 3);
  50297. var colors = this._vertexBuffer.createVertexBuffer(BABYLON.VertexBuffer.ColorKind, 3, 4);
  50298. var options = this._vertexBuffer.createVertexBuffer("options", 7, 4);
  50299. if (this._isAnimationSheetEnabled) {
  50300. var cellIndexBuffer = this._vertexBuffer.createVertexBuffer("cellIndex", 11, 1);
  50301. this._vertexBuffers["cellIndex"] = cellIndexBuffer;
  50302. }
  50303. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = positions;
  50304. this._vertexBuffers[BABYLON.VertexBuffer.ColorKind] = colors;
  50305. this._vertexBuffers["options"] = options;
  50306. // Default behaviors
  50307. this.particleEmitterType = new BABYLON.BoxParticleEmitter(this);
  50308. this.updateFunction = function (particles) {
  50309. for (var index = 0; index < particles.length; index++) {
  50310. var particle = particles[index];
  50311. particle.age += _this._scaledUpdateSpeed;
  50312. if (particle.age >= particle.lifeTime) {
  50313. _this.recycleParticle(particle);
  50314. index--;
  50315. continue;
  50316. }
  50317. else {
  50318. particle.colorStep.scaleToRef(_this._scaledUpdateSpeed, _this._scaledColorStep);
  50319. particle.color.addInPlace(_this._scaledColorStep);
  50320. if (particle.color.a < 0)
  50321. particle.color.a = 0;
  50322. particle.angle += particle.angularSpeed * _this._scaledUpdateSpeed;
  50323. particle.direction.scaleToRef(_this._scaledUpdateSpeed, _this._scaledDirection);
  50324. particle.position.addInPlace(_this._scaledDirection);
  50325. _this.gravity.scaleToRef(_this._scaledUpdateSpeed, _this._scaledGravity);
  50326. particle.direction.addInPlace(_this._scaledGravity);
  50327. if (_this._isAnimationSheetEnabled) {
  50328. particle.updateCellIndex(_this._scaledUpdateSpeed);
  50329. }
  50330. }
  50331. }
  50332. };
  50333. }
  50334. Object.defineProperty(ParticleSystem.prototype, "onDispose", {
  50335. /**
  50336. * Sets a callback that will be triggered when the system is disposed.
  50337. */
  50338. set: function (callback) {
  50339. if (this._onDisposeObserver) {
  50340. this.onDisposeObservable.remove(this._onDisposeObserver);
  50341. }
  50342. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  50343. },
  50344. enumerable: true,
  50345. configurable: true
  50346. });
  50347. Object.defineProperty(ParticleSystem.prototype, "isAnimationSheetEnabled", {
  50348. /**
  50349. * Gets wether an animation sprite sheet is enabled or not on the particle system.
  50350. */
  50351. get: function () {
  50352. return this._isAnimationSheetEnabled;
  50353. },
  50354. enumerable: true,
  50355. configurable: true
  50356. });
  50357. ParticleSystem.prototype._createIndexBuffer = function () {
  50358. var indices = [];
  50359. var index = 0;
  50360. for (var count = 0; count < this._capacity; count++) {
  50361. indices.push(index);
  50362. indices.push(index + 1);
  50363. indices.push(index + 2);
  50364. indices.push(index);
  50365. indices.push(index + 2);
  50366. indices.push(index + 3);
  50367. index += 4;
  50368. }
  50369. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  50370. };
  50371. /**
  50372. * "Recycles" one of the particle by copying it back to the "stock" of particles and removing it from the active list.
  50373. * Its lifetime will start back at 0.
  50374. * @param particle The particle to recycle
  50375. */
  50376. ParticleSystem.prototype.recycleParticle = function (particle) {
  50377. var lastParticle = this._particles.pop();
  50378. if (lastParticle !== particle) {
  50379. lastParticle.copyTo(particle);
  50380. this._stockParticles.push(lastParticle);
  50381. }
  50382. };
  50383. /**
  50384. * Gets the maximum number of particles active at the same time.
  50385. * @returns The max number of active particles.
  50386. */
  50387. ParticleSystem.prototype.getCapacity = function () {
  50388. return this._capacity;
  50389. };
  50390. /**
  50391. * Gets Wether there are still active particles in the system.
  50392. * @returns True if it is alive, otherwise false.
  50393. */
  50394. ParticleSystem.prototype.isAlive = function () {
  50395. return this._alive;
  50396. };
  50397. /**
  50398. * Gets Wether the system has been started.
  50399. * @returns True if it has been started, otherwise false.
  50400. */
  50401. ParticleSystem.prototype.isStarted = function () {
  50402. return this._started;
  50403. };
  50404. /**
  50405. * Starts the particle system and begins to emit.
  50406. */
  50407. ParticleSystem.prototype.start = function () {
  50408. this._started = true;
  50409. this._stopped = false;
  50410. this._actualFrame = 0;
  50411. };
  50412. /**
  50413. * Stops the particle system.
  50414. */
  50415. ParticleSystem.prototype.stop = function () {
  50416. this._stopped = true;
  50417. };
  50418. /**
  50419. * Remove all active particles
  50420. */
  50421. ParticleSystem.prototype.reset = function () {
  50422. this._stockParticles = [];
  50423. this._particles = [];
  50424. };
  50425. /**
  50426. * @ignore (for internal use only)
  50427. */
  50428. ParticleSystem.prototype._appendParticleVertex = function (index, particle, offsetX, offsetY) {
  50429. var offset = index * this._vertexBufferSize;
  50430. this._vertexData[offset] = particle.position.x;
  50431. this._vertexData[offset + 1] = particle.position.y;
  50432. this._vertexData[offset + 2] = particle.position.z;
  50433. this._vertexData[offset + 3] = particle.color.r;
  50434. this._vertexData[offset + 4] = particle.color.g;
  50435. this._vertexData[offset + 5] = particle.color.b;
  50436. this._vertexData[offset + 6] = particle.color.a;
  50437. this._vertexData[offset + 7] = particle.angle;
  50438. this._vertexData[offset + 8] = particle.size;
  50439. this._vertexData[offset + 9] = offsetX;
  50440. this._vertexData[offset + 10] = offsetY;
  50441. };
  50442. /**
  50443. * @ignore (for internal use only)
  50444. */
  50445. ParticleSystem.prototype._appendParticleVertexWithAnimation = function (index, particle, offsetX, offsetY) {
  50446. if (offsetX === 0)
  50447. offsetX = this._epsilon;
  50448. else if (offsetX === 1)
  50449. offsetX = 1 - this._epsilon;
  50450. if (offsetY === 0)
  50451. offsetY = this._epsilon;
  50452. else if (offsetY === 1)
  50453. offsetY = 1 - this._epsilon;
  50454. var offset = index * this._vertexBufferSize;
  50455. this._vertexData[offset] = particle.position.x;
  50456. this._vertexData[offset + 1] = particle.position.y;
  50457. this._vertexData[offset + 2] = particle.position.z;
  50458. this._vertexData[offset + 3] = particle.color.r;
  50459. this._vertexData[offset + 4] = particle.color.g;
  50460. this._vertexData[offset + 5] = particle.color.b;
  50461. this._vertexData[offset + 6] = particle.color.a;
  50462. this._vertexData[offset + 7] = particle.angle;
  50463. this._vertexData[offset + 8] = particle.size;
  50464. this._vertexData[offset + 9] = offsetX;
  50465. this._vertexData[offset + 10] = offsetY;
  50466. this._vertexData[offset + 11] = particle.cellIndex;
  50467. };
  50468. ParticleSystem.prototype._update = function (newParticles) {
  50469. // Update current
  50470. this._alive = this._particles.length > 0;
  50471. this.updateFunction(this._particles);
  50472. // Add new ones
  50473. var worldMatrix;
  50474. if (this.emitter.position) {
  50475. var emitterMesh = this.emitter;
  50476. worldMatrix = emitterMesh.getWorldMatrix();
  50477. }
  50478. else {
  50479. var emitterPosition = this.emitter;
  50480. worldMatrix = BABYLON.Matrix.Translation(emitterPosition.x, emitterPosition.y, emitterPosition.z);
  50481. }
  50482. var particle;
  50483. for (var index = 0; index < newParticles; index++) {
  50484. if (this._particles.length === this._capacity) {
  50485. break;
  50486. }
  50487. if (this._stockParticles.length !== 0) {
  50488. particle = this._stockParticles.pop();
  50489. particle.age = 0;
  50490. particle.cellIndex = this.startSpriteCellID;
  50491. }
  50492. else {
  50493. particle = new BABYLON.Particle(this);
  50494. }
  50495. this._particles.push(particle);
  50496. var emitPower = BABYLON.Scalar.RandomRange(this.minEmitPower, this.maxEmitPower);
  50497. if (this.startPositionFunction) {
  50498. this.startPositionFunction(worldMatrix, particle.position, particle);
  50499. }
  50500. else {
  50501. this.particleEmitterType.startPositionFunction(worldMatrix, particle.position, particle);
  50502. }
  50503. if (this.startDirectionFunction) {
  50504. this.startDirectionFunction(emitPower, worldMatrix, particle.direction, particle);
  50505. }
  50506. else {
  50507. this.particleEmitterType.startDirectionFunction(emitPower, worldMatrix, particle.direction, particle);
  50508. }
  50509. particle.lifeTime = BABYLON.Scalar.RandomRange(this.minLifeTime, this.maxLifeTime);
  50510. particle.size = BABYLON.Scalar.RandomRange(this.minSize, this.maxSize);
  50511. particle.angularSpeed = BABYLON.Scalar.RandomRange(this.minAngularSpeed, this.maxAngularSpeed);
  50512. var step = BABYLON.Scalar.RandomRange(0, 1.0);
  50513. BABYLON.Color4.LerpToRef(this.color1, this.color2, step, particle.color);
  50514. this.colorDead.subtractToRef(particle.color, this._colorDiff);
  50515. this._colorDiff.scaleToRef(1.0 / particle.lifeTime, particle.colorStep);
  50516. }
  50517. };
  50518. ParticleSystem.prototype._getEffect = function () {
  50519. if (this._customEffect) {
  50520. return this._customEffect;
  50521. }
  50522. ;
  50523. var defines = [];
  50524. if (this._scene.clipPlane) {
  50525. defines.push("#define CLIPPLANE");
  50526. }
  50527. if (this._isAnimationSheetEnabled) {
  50528. defines.push("#define ANIMATESHEET");
  50529. }
  50530. // Effect
  50531. var join = defines.join("\n");
  50532. if (this._cachedDefines !== join) {
  50533. this._cachedDefines = join;
  50534. var attributesNamesOrOptions;
  50535. var effectCreationOption;
  50536. if (this._isAnimationSheetEnabled) {
  50537. attributesNamesOrOptions = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.ColorKind, "options", "cellIndex"];
  50538. effectCreationOption = ["invView", "view", "projection", "particlesInfos", "vClipPlane", "textureMask"];
  50539. }
  50540. else {
  50541. attributesNamesOrOptions = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.ColorKind, "options"];
  50542. effectCreationOption = ["invView", "view", "projection", "vClipPlane", "textureMask"];
  50543. }
  50544. this._effect = this._scene.getEngine().createEffect("particles", attributesNamesOrOptions, effectCreationOption, ["diffuseSampler"], join);
  50545. }
  50546. return this._effect;
  50547. };
  50548. /**
  50549. * Animates the particle system for the current frame by emitting new particles and or animating the living ones.
  50550. */
  50551. ParticleSystem.prototype.animate = function () {
  50552. if (!this._started)
  50553. return;
  50554. var effect = this._getEffect();
  50555. // Check
  50556. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady())
  50557. return;
  50558. if (this._currentRenderId === this._scene.getRenderId()) {
  50559. return;
  50560. }
  50561. this._currentRenderId = this._scene.getRenderId();
  50562. this._scaledUpdateSpeed = this.updateSpeed * this._scene.getAnimationRatio();
  50563. // determine the number of particles we need to create
  50564. var newParticles;
  50565. if (this.manualEmitCount > -1) {
  50566. newParticles = this.manualEmitCount;
  50567. this._newPartsExcess = 0;
  50568. this.manualEmitCount = 0;
  50569. }
  50570. else {
  50571. newParticles = ((this.emitRate * this._scaledUpdateSpeed) >> 0);
  50572. this._newPartsExcess += this.emitRate * this._scaledUpdateSpeed - newParticles;
  50573. }
  50574. if (this._newPartsExcess > 1.0) {
  50575. newParticles += this._newPartsExcess >> 0;
  50576. this._newPartsExcess -= this._newPartsExcess >> 0;
  50577. }
  50578. this._alive = false;
  50579. if (!this._stopped) {
  50580. this._actualFrame += this._scaledUpdateSpeed;
  50581. if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration)
  50582. this.stop();
  50583. }
  50584. else {
  50585. newParticles = 0;
  50586. }
  50587. this._update(newParticles);
  50588. // Stopped?
  50589. if (this._stopped) {
  50590. if (!this._alive) {
  50591. this._started = false;
  50592. if (this.onAnimationEnd) {
  50593. this.onAnimationEnd();
  50594. }
  50595. if (this.disposeOnStop) {
  50596. this._scene._toBeDisposed.push(this);
  50597. }
  50598. }
  50599. }
  50600. // Animation sheet
  50601. if (this._isAnimationSheetEnabled) {
  50602. this._appendParticleVertexes = this._appenedParticleVertexesWithSheet;
  50603. }
  50604. else {
  50605. this._appendParticleVertexes = this._appenedParticleVertexesNoSheet;
  50606. }
  50607. // Update VBO
  50608. var offset = 0;
  50609. for (var index = 0; index < this._particles.length; index++) {
  50610. var particle = this._particles[index];
  50611. this._appendParticleVertexes(offset, particle);
  50612. offset += 4;
  50613. }
  50614. if (this._vertexBuffer) {
  50615. this._vertexBuffer.update(this._vertexData);
  50616. }
  50617. };
  50618. ParticleSystem.prototype._appenedParticleVertexesWithSheet = function (offset, particle) {
  50619. this._appendParticleVertexWithAnimation(offset++, particle, 0, 0);
  50620. this._appendParticleVertexWithAnimation(offset++, particle, 1, 0);
  50621. this._appendParticleVertexWithAnimation(offset++, particle, 1, 1);
  50622. this._appendParticleVertexWithAnimation(offset++, particle, 0, 1);
  50623. };
  50624. ParticleSystem.prototype._appenedParticleVertexesNoSheet = function (offset, particle) {
  50625. this._appendParticleVertex(offset++, particle, 0, 0);
  50626. this._appendParticleVertex(offset++, particle, 1, 0);
  50627. this._appendParticleVertex(offset++, particle, 1, 1);
  50628. this._appendParticleVertex(offset++, particle, 0, 1);
  50629. };
  50630. /**
  50631. * Rebuilds the particle system.
  50632. */
  50633. ParticleSystem.prototype.rebuild = function () {
  50634. this._createIndexBuffer();
  50635. if (this._vertexBuffer) {
  50636. this._vertexBuffer._rebuild();
  50637. }
  50638. };
  50639. /**
  50640. * Renders the particle system in its current state.
  50641. * @returns the current number of particles.
  50642. */
  50643. ParticleSystem.prototype.render = function () {
  50644. var effect = this._getEffect();
  50645. // Check
  50646. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady() || !this._particles.length)
  50647. return 0;
  50648. var engine = this._scene.getEngine();
  50649. // Render
  50650. engine.enableEffect(effect);
  50651. engine.setState(false);
  50652. var viewMatrix = this._scene.getViewMatrix();
  50653. effect.setTexture("diffuseSampler", this.particleTexture);
  50654. effect.setMatrix("view", viewMatrix);
  50655. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  50656. if (this._isAnimationSheetEnabled) {
  50657. var baseSize = this.particleTexture.getBaseSize();
  50658. effect.setFloat3("particlesInfos", this.spriteCellWidth / baseSize.width, this.spriteCellHeight / baseSize.height, baseSize.width / this.spriteCellWidth);
  50659. }
  50660. effect.setFloat4("textureMask", this.textureMask.r, this.textureMask.g, this.textureMask.b, this.textureMask.a);
  50661. if (this._scene.clipPlane) {
  50662. var clipPlane = this._scene.clipPlane;
  50663. var invView = viewMatrix.clone();
  50664. invView.invert();
  50665. effect.setMatrix("invView", invView);
  50666. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  50667. }
  50668. // VBOs
  50669. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  50670. // Draw order
  50671. if (this.blendMode === ParticleSystem.BLENDMODE_ONEONE) {
  50672. engine.setAlphaMode(BABYLON.Engine.ALPHA_ONEONE);
  50673. }
  50674. else {
  50675. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  50676. }
  50677. if (this.forceDepthWrite) {
  50678. engine.setDepthWrite(true);
  50679. }
  50680. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, this._particles.length * 6);
  50681. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  50682. return this._particles.length;
  50683. };
  50684. /**
  50685. * Disposes the particle system and free the associated resources.
  50686. */
  50687. ParticleSystem.prototype.dispose = function () {
  50688. if (this._vertexBuffer) {
  50689. this._vertexBuffer.dispose();
  50690. this._vertexBuffer = null;
  50691. }
  50692. if (this._indexBuffer) {
  50693. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  50694. this._indexBuffer = null;
  50695. }
  50696. if (this.particleTexture) {
  50697. this.particleTexture.dispose();
  50698. this.particleTexture = null;
  50699. }
  50700. // Remove from scene
  50701. var index = this._scene.particleSystems.indexOf(this);
  50702. if (index > -1) {
  50703. this._scene.particleSystems.splice(index, 1);
  50704. }
  50705. // Callback
  50706. this.onDisposeObservable.notifyObservers(this);
  50707. this.onDisposeObservable.clear();
  50708. };
  50709. /**
  50710. * Creates a Sphere Emitter for the particle system. (emits along the sphere radius)
  50711. * @param radius The radius of the sphere to emit from
  50712. * @returns the emitter
  50713. */
  50714. ParticleSystem.prototype.createSphereEmitter = function (radius) {
  50715. if (radius === void 0) { radius = 1; }
  50716. var particleEmitter = new BABYLON.SphereParticleEmitter(radius);
  50717. this.particleEmitterType = particleEmitter;
  50718. return particleEmitter;
  50719. };
  50720. /**
  50721. * Creates a Directed Sphere Emitter for the particle system. (emits between direction1 and direction2)
  50722. * @param radius The radius of the sphere to emit from
  50723. * @param direction1 Particles are emitted between the direction1 and direction2 from within the sphere
  50724. * @param direction2 Particles are emitted between the direction1 and direction2 from within the sphere
  50725. * @returns the emitter
  50726. */
  50727. ParticleSystem.prototype.createDirectedSphereEmitter = function (radius, direction1, direction2) {
  50728. if (radius === void 0) { radius = 1; }
  50729. if (direction1 === void 0) { direction1 = new BABYLON.Vector3(0, 1.0, 0); }
  50730. if (direction2 === void 0) { direction2 = new BABYLON.Vector3(0, 1.0, 0); }
  50731. var particleEmitter = new BABYLON.SphereDirectedParticleEmitter(radius, direction1, direction2);
  50732. this.particleEmitterType = particleEmitter;
  50733. return particleEmitter;
  50734. };
  50735. /**
  50736. * Creates a Cone Emitter for the particle system. (emits from the cone to the particle position)
  50737. * @param radius The radius of the cone to emit from
  50738. * @param angle The base angle of the cone
  50739. * @returns the emitter
  50740. */
  50741. ParticleSystem.prototype.createConeEmitter = function (radius, angle) {
  50742. if (radius === void 0) { radius = 1; }
  50743. if (angle === void 0) { angle = Math.PI / 4; }
  50744. var particleEmitter = new BABYLON.ConeParticleEmitter(radius, angle);
  50745. this.particleEmitterType = particleEmitter;
  50746. return particleEmitter;
  50747. };
  50748. // 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.
  50749. /**
  50750. * Creates a Box Emitter for the particle system. (emits between direction1 and direction2 from withing the box defined by minEmitBox and maxEmitBox)
  50751. * @param direction1 Particles are emitted between the direction1 and direction2 from within the box
  50752. * @param direction2 Particles are emitted between the direction1 and direction2 from within the box
  50753. * @param minEmitBox Particles are emitted from the box between minEmitBox and maxEmitBox
  50754. * @param maxEmitBox Particles are emitted from the box between minEmitBox and maxEmitBox
  50755. * @returns the emitter
  50756. */
  50757. ParticleSystem.prototype.createBoxEmitter = function (direction1, direction2, minEmitBox, maxEmitBox) {
  50758. var particleEmitter = new BABYLON.BoxParticleEmitter(this);
  50759. this.direction1 = direction1;
  50760. this.direction2 = direction2;
  50761. this.minEmitBox = minEmitBox;
  50762. this.maxEmitBox = maxEmitBox;
  50763. this.particleEmitterType = particleEmitter;
  50764. return particleEmitter;
  50765. };
  50766. /**
  50767. * Clones the particle system.
  50768. * @param name The name of the cloned object
  50769. * @param newEmitter The new emitter to use
  50770. * @returns the cloned particle system
  50771. */
  50772. ParticleSystem.prototype.clone = function (name, newEmitter) {
  50773. var custom = null;
  50774. var program = null;
  50775. if (this.customShader != null) {
  50776. program = this.customShader;
  50777. var defines = (program.shaderOptions.defines.length > 0) ? program.shaderOptions.defines.join("\n") : "";
  50778. custom = this._scene.getEngine().createEffectForParticles(program.shaderPath.fragmentElement, program.shaderOptions.uniforms, program.shaderOptions.samplers, defines);
  50779. }
  50780. var result = new ParticleSystem(name, this._capacity, this._scene, custom);
  50781. result.customShader = program;
  50782. BABYLON.Tools.DeepCopy(this, result, ["particles", "customShader"]);
  50783. if (newEmitter === undefined) {
  50784. newEmitter = this.emitter;
  50785. }
  50786. result.emitter = newEmitter;
  50787. if (this.particleTexture) {
  50788. result.particleTexture = new BABYLON.Texture(this.particleTexture.url, this._scene);
  50789. }
  50790. if (!this.preventAutoStart) {
  50791. result.start();
  50792. }
  50793. return result;
  50794. };
  50795. /**
  50796. * Serializes the particle system to a JSON object.
  50797. * @returns the JSON object
  50798. */
  50799. ParticleSystem.prototype.serialize = function () {
  50800. var serializationObject = {};
  50801. serializationObject.name = this.name;
  50802. serializationObject.id = this.id;
  50803. // Emitter
  50804. if (this.emitter.position) {
  50805. var emitterMesh = this.emitter;
  50806. serializationObject.emitterId = emitterMesh.id;
  50807. }
  50808. else {
  50809. var emitterPosition = this.emitter;
  50810. serializationObject.emitter = emitterPosition.asArray();
  50811. }
  50812. serializationObject.capacity = this.getCapacity();
  50813. if (this.particleTexture) {
  50814. serializationObject.textureName = this.particleTexture.name;
  50815. }
  50816. // Animations
  50817. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  50818. // Particle system
  50819. serializationObject.minAngularSpeed = this.minAngularSpeed;
  50820. serializationObject.maxAngularSpeed = this.maxAngularSpeed;
  50821. serializationObject.minSize = this.minSize;
  50822. serializationObject.maxSize = this.maxSize;
  50823. serializationObject.minEmitPower = this.minEmitPower;
  50824. serializationObject.maxEmitPower = this.maxEmitPower;
  50825. serializationObject.minLifeTime = this.minLifeTime;
  50826. serializationObject.maxLifeTime = this.maxLifeTime;
  50827. serializationObject.emitRate = this.emitRate;
  50828. serializationObject.minEmitBox = this.minEmitBox.asArray();
  50829. serializationObject.maxEmitBox = this.maxEmitBox.asArray();
  50830. serializationObject.gravity = this.gravity.asArray();
  50831. serializationObject.direction1 = this.direction1.asArray();
  50832. serializationObject.direction2 = this.direction2.asArray();
  50833. serializationObject.color1 = this.color1.asArray();
  50834. serializationObject.color2 = this.color2.asArray();
  50835. serializationObject.colorDead = this.colorDead.asArray();
  50836. serializationObject.updateSpeed = this.updateSpeed;
  50837. serializationObject.targetStopDuration = this.targetStopDuration;
  50838. serializationObject.textureMask = this.textureMask.asArray();
  50839. serializationObject.blendMode = this.blendMode;
  50840. serializationObject.customShader = this.customShader;
  50841. serializationObject.preventAutoStart = this.preventAutoStart;
  50842. serializationObject.startSpriteCellID = this.startSpriteCellID;
  50843. serializationObject.endSpriteCellID = this.endSpriteCellID;
  50844. serializationObject.spriteCellLoop = this.spriteCellLoop;
  50845. serializationObject.spriteCellChangeSpeed = this.spriteCellChangeSpeed;
  50846. serializationObject.spriteCellWidth = this.spriteCellWidth;
  50847. serializationObject.spriteCellHeight = this.spriteCellHeight;
  50848. serializationObject.isAnimationSheetEnabled = this._isAnimationSheetEnabled;
  50849. return serializationObject;
  50850. };
  50851. /**
  50852. * Parses a JSON object to create a particle system.
  50853. * @param parsedParticleSystem The JSON object to parse
  50854. * @param scene The scene to create the particle system in
  50855. * @param rootUrl The root url to use to load external dependencies like texture
  50856. * @returns the Parsed particle system
  50857. */
  50858. ParticleSystem.Parse = function (parsedParticleSystem, scene, rootUrl) {
  50859. var name = parsedParticleSystem.name;
  50860. var custom = null;
  50861. var program = null;
  50862. if (parsedParticleSystem.customShader) {
  50863. program = parsedParticleSystem.customShader;
  50864. var defines = (program.shaderOptions.defines.length > 0) ? program.shaderOptions.defines.join("\n") : "";
  50865. custom = scene.getEngine().createEffectForParticles(program.shaderPath.fragmentElement, program.shaderOptions.uniforms, program.shaderOptions.samplers, defines);
  50866. }
  50867. var particleSystem = new ParticleSystem(name, parsedParticleSystem.capacity, scene, custom, parsedParticleSystem.isAnimationSheetEnabled);
  50868. particleSystem.customShader = program;
  50869. if (parsedParticleSystem.id) {
  50870. particleSystem.id = parsedParticleSystem.id;
  50871. }
  50872. // Auto start
  50873. if (parsedParticleSystem.preventAutoStart) {
  50874. particleSystem.preventAutoStart = parsedParticleSystem.preventAutoStart;
  50875. }
  50876. // Texture
  50877. if (parsedParticleSystem.textureName) {
  50878. particleSystem.particleTexture = new BABYLON.Texture(rootUrl + parsedParticleSystem.textureName, scene);
  50879. particleSystem.particleTexture.name = parsedParticleSystem.textureName;
  50880. }
  50881. // Emitter
  50882. if (parsedParticleSystem.emitterId) {
  50883. particleSystem.emitter = scene.getLastMeshByID(parsedParticleSystem.emitterId);
  50884. }
  50885. else {
  50886. particleSystem.emitter = BABYLON.Vector3.FromArray(parsedParticleSystem.emitter);
  50887. }
  50888. // Animations
  50889. if (parsedParticleSystem.animations) {
  50890. for (var animationIndex = 0; animationIndex < parsedParticleSystem.animations.length; animationIndex++) {
  50891. var parsedAnimation = parsedParticleSystem.animations[animationIndex];
  50892. particleSystem.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  50893. }
  50894. }
  50895. if (parsedParticleSystem.autoAnimate) {
  50896. scene.beginAnimation(particleSystem, parsedParticleSystem.autoAnimateFrom, parsedParticleSystem.autoAnimateTo, parsedParticleSystem.autoAnimateLoop, parsedParticleSystem.autoAnimateSpeed || 1.0);
  50897. }
  50898. // Particle system
  50899. particleSystem.minAngularSpeed = parsedParticleSystem.minAngularSpeed;
  50900. particleSystem.maxAngularSpeed = parsedParticleSystem.maxAngularSpeed;
  50901. particleSystem.minSize = parsedParticleSystem.minSize;
  50902. particleSystem.maxSize = parsedParticleSystem.maxSize;
  50903. particleSystem.minLifeTime = parsedParticleSystem.minLifeTime;
  50904. particleSystem.maxLifeTime = parsedParticleSystem.maxLifeTime;
  50905. particleSystem.minEmitPower = parsedParticleSystem.minEmitPower;
  50906. particleSystem.maxEmitPower = parsedParticleSystem.maxEmitPower;
  50907. particleSystem.emitRate = parsedParticleSystem.emitRate;
  50908. particleSystem.minEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.minEmitBox);
  50909. particleSystem.maxEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.maxEmitBox);
  50910. particleSystem.gravity = BABYLON.Vector3.FromArray(parsedParticleSystem.gravity);
  50911. particleSystem.direction1 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction1);
  50912. particleSystem.direction2 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction2);
  50913. particleSystem.color1 = BABYLON.Color4.FromArray(parsedParticleSystem.color1);
  50914. particleSystem.color2 = BABYLON.Color4.FromArray(parsedParticleSystem.color2);
  50915. particleSystem.colorDead = BABYLON.Color4.FromArray(parsedParticleSystem.colorDead);
  50916. particleSystem.updateSpeed = parsedParticleSystem.updateSpeed;
  50917. particleSystem.targetStopDuration = parsedParticleSystem.targetStopDuration;
  50918. particleSystem.textureMask = BABYLON.Color4.FromArray(parsedParticleSystem.textureMask);
  50919. particleSystem.blendMode = parsedParticleSystem.blendMode;
  50920. particleSystem.startSpriteCellID = parsedParticleSystem.startSpriteCellID;
  50921. particleSystem.endSpriteCellID = parsedParticleSystem.endSpriteCellID;
  50922. particleSystem.spriteCellLoop = parsedParticleSystem.spriteCellLoop;
  50923. particleSystem.spriteCellChangeSpeed = parsedParticleSystem.spriteCellChangeSpeed;
  50924. particleSystem.spriteCellWidth = parsedParticleSystem.spriteCellWidth;
  50925. particleSystem.spriteCellHeight = parsedParticleSystem.spriteCellHeight;
  50926. if (!particleSystem.preventAutoStart) {
  50927. particleSystem.start();
  50928. }
  50929. return particleSystem;
  50930. };
  50931. /**
  50932. * Source color is added to the destination color without alpha affecting the result.
  50933. */
  50934. ParticleSystem.BLENDMODE_ONEONE = 0;
  50935. /**
  50936. * Blend current color and particle color using particle’s alpha.
  50937. */
  50938. ParticleSystem.BLENDMODE_STANDARD = 1;
  50939. return ParticleSystem;
  50940. }());
  50941. BABYLON.ParticleSystem = ParticleSystem;
  50942. })(BABYLON || (BABYLON = {}));
  50943. //# sourceMappingURL=babylon.particleSystem.js.map
  50944. var BABYLON;
  50945. (function (BABYLON) {
  50946. /**
  50947. * Particle emitter emitting particles from the inside of a box.
  50948. * It emits the particles randomly between 2 given directions.
  50949. */
  50950. var BoxParticleEmitter = /** @class */ (function () {
  50951. // to be updated like the rest of emitters when breaking changes.
  50952. // all property should be come public variables and passed through constructor.
  50953. /**
  50954. * Creates a new instance of @see BoxParticleEmitter
  50955. * @param _particleSystem the particle system associated with the emitter
  50956. */
  50957. function BoxParticleEmitter(_particleSystem) {
  50958. this._particleSystem = _particleSystem;
  50959. }
  50960. Object.defineProperty(BoxParticleEmitter.prototype, "direction1", {
  50961. /**
  50962. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  50963. */
  50964. get: function () {
  50965. return this._particleSystem.direction1;
  50966. },
  50967. /**
  50968. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  50969. */
  50970. set: function (value) {
  50971. this._particleSystem.direction1 = value;
  50972. },
  50973. enumerable: true,
  50974. configurable: true
  50975. });
  50976. Object.defineProperty(BoxParticleEmitter.prototype, "direction2", {
  50977. /**
  50978. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  50979. */
  50980. get: function () {
  50981. return this._particleSystem.direction2;
  50982. },
  50983. /**
  50984. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  50985. */
  50986. set: function (value) {
  50987. this._particleSystem.direction2 = value;
  50988. },
  50989. enumerable: true,
  50990. configurable: true
  50991. });
  50992. Object.defineProperty(BoxParticleEmitter.prototype, "minEmitBox", {
  50993. /**
  50994. * 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.
  50995. */
  50996. get: function () {
  50997. return this._particleSystem.minEmitBox;
  50998. },
  50999. /**
  51000. * 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.
  51001. */
  51002. set: function (value) {
  51003. this._particleSystem.minEmitBox = value;
  51004. },
  51005. enumerable: true,
  51006. configurable: true
  51007. });
  51008. Object.defineProperty(BoxParticleEmitter.prototype, "maxEmitBox", {
  51009. /**
  51010. * 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.
  51011. */
  51012. get: function () {
  51013. return this._particleSystem.maxEmitBox;
  51014. },
  51015. /**
  51016. * 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.
  51017. */
  51018. set: function (value) {
  51019. this._particleSystem.maxEmitBox = value;
  51020. },
  51021. enumerable: true,
  51022. configurable: true
  51023. });
  51024. /**
  51025. * Called by the particle System when the direction is computed for the created particle.
  51026. * @param emitPower is the power of the particle (speed)
  51027. * @param worldMatrix is the world matrix of the particle system
  51028. * @param directionToUpdate is the direction vector to update with the result
  51029. * @param particle is the particle we are computed the direction for
  51030. */
  51031. BoxParticleEmitter.prototype.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  51032. var randX = BABYLON.Scalar.RandomRange(this.direction1.x, this.direction2.x);
  51033. var randY = BABYLON.Scalar.RandomRange(this.direction1.y, this.direction2.y);
  51034. var randZ = BABYLON.Scalar.RandomRange(this.direction1.z, this.direction2.z);
  51035. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX * emitPower, randY * emitPower, randZ * emitPower, worldMatrix, directionToUpdate);
  51036. };
  51037. /**
  51038. * Called by the particle System when the position is computed for the created particle.
  51039. * @param worldMatrix is the world matrix of the particle system
  51040. * @param positionToUpdate is the position vector to update with the result
  51041. * @param particle is the particle we are computed the position for
  51042. */
  51043. BoxParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  51044. var randX = BABYLON.Scalar.RandomRange(this.minEmitBox.x, this.maxEmitBox.x);
  51045. var randY = BABYLON.Scalar.RandomRange(this.minEmitBox.y, this.maxEmitBox.y);
  51046. var randZ = BABYLON.Scalar.RandomRange(this.minEmitBox.z, this.maxEmitBox.z);
  51047. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  51048. };
  51049. /**
  51050. * Clones the current emitter and returns a copy of it
  51051. * @returns the new emitter
  51052. */
  51053. BoxParticleEmitter.prototype.clone = function () {
  51054. var newOne = new BoxParticleEmitter(this._particleSystem);
  51055. BABYLON.Tools.DeepCopy(this, newOne);
  51056. return newOne;
  51057. };
  51058. return BoxParticleEmitter;
  51059. }());
  51060. BABYLON.BoxParticleEmitter = BoxParticleEmitter;
  51061. })(BABYLON || (BABYLON = {}));
  51062. //# sourceMappingURL=babylon.boxParticleEmitter.js.map
  51063. var BABYLON;
  51064. (function (BABYLON) {
  51065. /**
  51066. * Particle emitter emitting particles from the inside of a cone.
  51067. * It emits the particles alongside the cone volume from the base to the particle.
  51068. * The emission direction might be randomized.
  51069. */
  51070. var ConeParticleEmitter = /** @class */ (function () {
  51071. /**
  51072. * Creates a new instance of @see ConeParticleEmitter
  51073. * @param radius the radius of the emission cone
  51074. * @param angles the cone base angle
  51075. * @param directionRandomizer defines how much to randomize the particle direction [0-1]
  51076. */
  51077. function ConeParticleEmitter(radius,
  51078. /**
  51079. * The radius of the emission cone.
  51080. */
  51081. angle,
  51082. /**
  51083. * The cone base angle.
  51084. */
  51085. directionRandomizer) {
  51086. if (directionRandomizer === void 0) { directionRandomizer = 0; }
  51087. this.angle = angle;
  51088. this.directionRandomizer = directionRandomizer;
  51089. this.radius = radius;
  51090. }
  51091. Object.defineProperty(ConeParticleEmitter.prototype, "radius", {
  51092. /**
  51093. * Gets the radius of the emission cone.
  51094. */
  51095. get: function () {
  51096. return this._radius;
  51097. },
  51098. /**
  51099. * Sets the radius of the emission cone.
  51100. */
  51101. set: function (value) {
  51102. this._radius = value;
  51103. if (this.angle !== 0) {
  51104. this._height = value / Math.tan(this.angle / 2);
  51105. }
  51106. else {
  51107. this._height = 1;
  51108. }
  51109. },
  51110. enumerable: true,
  51111. configurable: true
  51112. });
  51113. /**
  51114. * Called by the particle System when the direction is computed for the created particle.
  51115. * @param emitPower is the power of the particle (speed)
  51116. * @param worldMatrix is the world matrix of the particle system
  51117. * @param directionToUpdate is the direction vector to update with the result
  51118. * @param particle is the particle we are computed the direction for
  51119. */
  51120. ConeParticleEmitter.prototype.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  51121. if (this.angle === 0) {
  51122. BABYLON.Vector3.TransformNormalFromFloatsToRef(0, emitPower, 0, worldMatrix, directionToUpdate);
  51123. }
  51124. else {
  51125. // measure the direction Vector from the emitter to the particle.
  51126. var direction = particle.position.subtract(worldMatrix.getTranslation()).normalize();
  51127. var randX = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  51128. var randY = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  51129. var randZ = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  51130. direction.x += randX;
  51131. direction.y += randY;
  51132. direction.z += randZ;
  51133. direction.normalize();
  51134. BABYLON.Vector3.TransformNormalFromFloatsToRef(direction.x * emitPower, direction.y * emitPower, direction.z * emitPower, worldMatrix, directionToUpdate);
  51135. }
  51136. };
  51137. /**
  51138. * Called by the particle System when the position is computed for the created particle.
  51139. * @param worldMatrix is the world matrix of the particle system
  51140. * @param positionToUpdate is the position vector to update with the result
  51141. * @param particle is the particle we are computed the position for
  51142. */
  51143. ConeParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  51144. var s = BABYLON.Scalar.RandomRange(0, Math.PI * 2);
  51145. var h = BABYLON.Scalar.RandomRange(0, 1);
  51146. // Better distribution in a cone at normal angles.
  51147. h = 1 - h * h;
  51148. var radius = BABYLON.Scalar.RandomRange(0, this._radius);
  51149. radius = radius * h / this._height;
  51150. var randX = radius * Math.sin(s);
  51151. var randZ = radius * Math.cos(s);
  51152. var randY = h;
  51153. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  51154. };
  51155. /**
  51156. * Clones the current emitter and returns a copy of it
  51157. * @returns the new emitter
  51158. */
  51159. ConeParticleEmitter.prototype.clone = function () {
  51160. var newOne = new ConeParticleEmitter(this.radius, this.angle, this.directionRandomizer);
  51161. BABYLON.Tools.DeepCopy(this, newOne);
  51162. return newOne;
  51163. };
  51164. return ConeParticleEmitter;
  51165. }());
  51166. BABYLON.ConeParticleEmitter = ConeParticleEmitter;
  51167. })(BABYLON || (BABYLON = {}));
  51168. //# sourceMappingURL=babylon.coneParticleEmitter.js.map
  51169. var BABYLON;
  51170. (function (BABYLON) {
  51171. /**
  51172. * Particle emitter emitting particles from the inside of a sphere.
  51173. * It emits the particles alongside the sphere radius. The emission direction might be randomized.
  51174. */
  51175. var SphereParticleEmitter = /** @class */ (function () {
  51176. /**
  51177. * Creates a new instance of @see SphereParticleEmitter
  51178. * @param radius the radius of the emission sphere
  51179. * @param directionRandomizer defines how much to randomize the particle direction [0-1]
  51180. */
  51181. function SphereParticleEmitter(
  51182. /**
  51183. * The radius of the emission sphere.
  51184. */
  51185. radius,
  51186. /**
  51187. * How much to randomize the particle direction [0-1].
  51188. */
  51189. directionRandomizer) {
  51190. if (directionRandomizer === void 0) { directionRandomizer = 0; }
  51191. this.radius = radius;
  51192. this.directionRandomizer = directionRandomizer;
  51193. }
  51194. /**
  51195. * Called by the particle System when the direction is computed for the created particle.
  51196. * @param emitPower is the power of the particle (speed)
  51197. * @param worldMatrix is the world matrix of the particle system
  51198. * @param directionToUpdate is the direction vector to update with the result
  51199. * @param particle is the particle we are computed the direction for
  51200. */
  51201. SphereParticleEmitter.prototype.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  51202. var direction = particle.position.subtract(worldMatrix.getTranslation()).normalize();
  51203. var randX = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  51204. var randY = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  51205. var randZ = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  51206. direction.x += randX;
  51207. direction.y += randY;
  51208. direction.z += randZ;
  51209. direction.normalize();
  51210. BABYLON.Vector3.TransformNormalFromFloatsToRef(direction.x * emitPower, direction.y * emitPower, direction.z * emitPower, worldMatrix, directionToUpdate);
  51211. };
  51212. /**
  51213. * Called by the particle System when the position is computed for the created particle.
  51214. * @param worldMatrix is the world matrix of the particle system
  51215. * @param positionToUpdate is the position vector to update with the result
  51216. * @param particle is the particle we are computed the position for
  51217. */
  51218. SphereParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  51219. var phi = BABYLON.Scalar.RandomRange(0, 2 * Math.PI);
  51220. var theta = BABYLON.Scalar.RandomRange(0, Math.PI);
  51221. var randX = this.radius * Math.cos(phi) * Math.sin(theta);
  51222. var randY = this.radius * Math.cos(theta);
  51223. var randZ = this.radius * Math.sin(phi) * Math.sin(theta);
  51224. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  51225. };
  51226. /**
  51227. * Clones the current emitter and returns a copy of it
  51228. * @returns the new emitter
  51229. */
  51230. SphereParticleEmitter.prototype.clone = function () {
  51231. var newOne = new SphereParticleEmitter(this.radius, this.directionRandomizer);
  51232. BABYLON.Tools.DeepCopy(this, newOne);
  51233. return newOne;
  51234. };
  51235. return SphereParticleEmitter;
  51236. }());
  51237. BABYLON.SphereParticleEmitter = SphereParticleEmitter;
  51238. /**
  51239. * Particle emitter emitting particles from the inside of a sphere.
  51240. * It emits the particles randomly between two vectors.
  51241. */
  51242. var SphereDirectedParticleEmitter = /** @class */ (function (_super) {
  51243. __extends(SphereDirectedParticleEmitter, _super);
  51244. /**
  51245. * Creates a new instance of @see SphereDirectedParticleEmitter
  51246. * @param radius the radius of the emission sphere
  51247. * @param direction1 the min limit of the emission direction
  51248. * @param direction2 the max limit of the emission direction
  51249. */
  51250. function SphereDirectedParticleEmitter(radius,
  51251. /**
  51252. * The min limit of the emission direction.
  51253. */
  51254. direction1,
  51255. /**
  51256. * The max limit of the emission direction.
  51257. */
  51258. direction2) {
  51259. var _this = _super.call(this, radius) || this;
  51260. _this.direction1 = direction1;
  51261. _this.direction2 = direction2;
  51262. return _this;
  51263. }
  51264. /**
  51265. * Called by the particle System when the direction is computed for the created particle.
  51266. * @param emitPower is the power of the particle (speed)
  51267. * @param worldMatrix is the world matrix of the particle system
  51268. * @param directionToUpdate is the direction vector to update with the result
  51269. * @param particle is the particle we are computed the direction for
  51270. */
  51271. SphereDirectedParticleEmitter.prototype.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  51272. var randX = BABYLON.Scalar.RandomRange(this.direction1.x, this.direction2.x);
  51273. var randY = BABYLON.Scalar.RandomRange(this.direction1.y, this.direction2.y);
  51274. var randZ = BABYLON.Scalar.RandomRange(this.direction1.z, this.direction2.z);
  51275. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX * emitPower, randY * emitPower, randZ * emitPower, worldMatrix, directionToUpdate);
  51276. };
  51277. /**
  51278. * Clones the current emitter and returns a copy of it
  51279. * @returns the new emitter
  51280. */
  51281. SphereDirectedParticleEmitter.prototype.clone = function () {
  51282. var newOne = new SphereDirectedParticleEmitter(this.radius, this.direction1, this.direction2);
  51283. BABYLON.Tools.DeepCopy(this, newOne);
  51284. return newOne;
  51285. };
  51286. return SphereDirectedParticleEmitter;
  51287. }(SphereParticleEmitter));
  51288. BABYLON.SphereDirectedParticleEmitter = SphereDirectedParticleEmitter;
  51289. })(BABYLON || (BABYLON = {}));
  51290. //# sourceMappingURL=babylon.sphereParticleEmitter.js.map
  51291. //# sourceMappingURL=babylon.IParticleEmitterType.js.map
  51292. var BABYLON;
  51293. (function (BABYLON) {
  51294. /**
  51295. * Represents one particle of a solid particle system.
  51296. * @see SolidParticleSystem
  51297. */
  51298. var SolidParticle = /** @class */ (function () {
  51299. /**
  51300. * Creates a Solid Particle object.
  51301. * Don't create particles manually, use instead the Solid Particle System internal tools like _addParticle()
  51302. * @param particleIndex (integer) is the particle index in the Solid Particle System pool. It's also the particle identifier.
  51303. * @param positionIndex (integer) is the starting index of the particle vertices in the SPS "positions" array.
  51304. * @param indiceIndex (integer) is the starting index of the particle indices in the SPS "indices" array.
  51305. * @param model (ModelShape) is a reference to the model shape on what the particle is designed.
  51306. * @param shapeId (integer) is the model shape identifier in the SPS.
  51307. * @param idxInShape (integer) is the index of the particle in the current model (ex: the 10th box of addShape(box, 30))
  51308. * @param modelBoundingInfo is the reference to the model BoundingInfo used for intersection computations.
  51309. */
  51310. function SolidParticle(particleIndex, positionIndex, indiceIndex, model, shapeId, idxInShape, sps, modelBoundingInfo) {
  51311. if (modelBoundingInfo === void 0) { modelBoundingInfo = null; }
  51312. /**
  51313. * particle global index
  51314. */
  51315. this.idx = 0;
  51316. /**
  51317. * The color of the particle
  51318. */
  51319. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  51320. /**
  51321. * The world space position of the particle.
  51322. */
  51323. this.position = BABYLON.Vector3.Zero();
  51324. /**
  51325. * The world space rotation of the particle. (Not use if rotationQuaternion is set)
  51326. */
  51327. this.rotation = BABYLON.Vector3.Zero();
  51328. /**
  51329. * The scaling of the particle.
  51330. */
  51331. this.scaling = BABYLON.Vector3.One();
  51332. /**
  51333. * The uvs of the particle.
  51334. */
  51335. this.uvs = new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  51336. /**
  51337. * The current speed of the particle.
  51338. */
  51339. this.velocity = BABYLON.Vector3.Zero();
  51340. /**
  51341. * The pivot point in the particle local space.
  51342. */
  51343. this.pivot = BABYLON.Vector3.Zero();
  51344. /**
  51345. * Must the particle be translated from its pivot point in its local space ?
  51346. * In this case, the pivot point is set at the origin of the particle local space and the particle is translated.
  51347. * Default : false
  51348. */
  51349. this.translateFromPivot = false;
  51350. /**
  51351. * Is the particle active or not ?
  51352. */
  51353. this.alive = true;
  51354. /**
  51355. * Is the particle visible or not ?
  51356. */
  51357. this.isVisible = true;
  51358. /**
  51359. * Index of this particle in the global "positions" array (Internal use)
  51360. */
  51361. this._pos = 0;
  51362. /**
  51363. * Index of this particle in the global "indices" array (Internal use)
  51364. */
  51365. this._ind = 0;
  51366. /**
  51367. * ModelShape id of this particle
  51368. */
  51369. this.shapeId = 0;
  51370. /**
  51371. * Index of the particle in its shape id (Internal use)
  51372. */
  51373. this.idxInShape = 0;
  51374. /**
  51375. * Still set as invisible in order to skip useless computations (Internal use)
  51376. */
  51377. this._stillInvisible = false;
  51378. /**
  51379. * Last computed particle rotation matrix
  51380. */
  51381. this._rotationMatrix = [1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0];
  51382. /**
  51383. * Parent particle Id, if any.
  51384. * Default null.
  51385. */
  51386. this.parentId = null;
  51387. /**
  51388. * Internal global position in the SPS.
  51389. */
  51390. this._globalPosition = BABYLON.Vector3.Zero();
  51391. this.idx = particleIndex;
  51392. this._pos = positionIndex;
  51393. this._ind = indiceIndex;
  51394. this._model = model;
  51395. this.shapeId = shapeId;
  51396. this.idxInShape = idxInShape;
  51397. this._sps = sps;
  51398. if (modelBoundingInfo) {
  51399. this._modelBoundingInfo = modelBoundingInfo;
  51400. this._boundingInfo = new BABYLON.BoundingInfo(modelBoundingInfo.minimum, modelBoundingInfo.maximum);
  51401. }
  51402. }
  51403. Object.defineProperty(SolidParticle.prototype, "scale", {
  51404. /**
  51405. * Legacy support, changed scale to scaling
  51406. */
  51407. get: function () {
  51408. return this.scaling;
  51409. },
  51410. /**
  51411. * Legacy support, changed scale to scaling
  51412. */
  51413. set: function (scale) {
  51414. this.scaling = scale;
  51415. },
  51416. enumerable: true,
  51417. configurable: true
  51418. });
  51419. Object.defineProperty(SolidParticle.prototype, "quaternion", {
  51420. /**
  51421. * Legacy support, changed quaternion to rotationQuaternion
  51422. */
  51423. get: function () {
  51424. return this.rotationQuaternion;
  51425. },
  51426. /**
  51427. * Legacy support, changed quaternion to rotationQuaternion
  51428. */
  51429. set: function (q) {
  51430. this.rotationQuaternion = q;
  51431. },
  51432. enumerable: true,
  51433. configurable: true
  51434. });
  51435. /**
  51436. * Returns a boolean. True if the particle intersects another particle or another mesh, else false.
  51437. * The intersection is computed on the particle bounding sphere and Axis Aligned Bounding Box (AABB)
  51438. * @param target is the object (solid particle or mesh) what the intersection is computed against.
  51439. * @returns true if it intersects
  51440. */
  51441. SolidParticle.prototype.intersectsMesh = function (target) {
  51442. if (!this._boundingInfo || !target._boundingInfo) {
  51443. return false;
  51444. }
  51445. if (this._sps._bSphereOnly) {
  51446. return BABYLON.BoundingSphere.Intersects(this._boundingInfo.boundingSphere, target._boundingInfo.boundingSphere);
  51447. }
  51448. return this._boundingInfo.intersects(target._boundingInfo, false);
  51449. };
  51450. return SolidParticle;
  51451. }());
  51452. BABYLON.SolidParticle = SolidParticle;
  51453. /**
  51454. * Represents the shape of the model used by one particle of a solid particle system.
  51455. * SPS internal tool, don't use it manually.
  51456. * @see SolidParticleSystem
  51457. */
  51458. var ModelShape = /** @class */ (function () {
  51459. /**
  51460. * 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.
  51461. * SPS internal tool, don't use it manually.
  51462. * @ignore
  51463. */
  51464. function ModelShape(id, shape, indicesLength, shapeUV, posFunction, vtxFunction) {
  51465. /**
  51466. * length of the shape in the model indices array (internal use)
  51467. */
  51468. this._indicesLength = 0;
  51469. this.shapeID = id;
  51470. this._shape = shape;
  51471. this._indicesLength = indicesLength;
  51472. this._shapeUV = shapeUV;
  51473. this._positionFunction = posFunction;
  51474. this._vertexFunction = vtxFunction;
  51475. }
  51476. return ModelShape;
  51477. }());
  51478. BABYLON.ModelShape = ModelShape;
  51479. /**
  51480. * Represents a Depth Sorted Particle in the solid particle system.
  51481. * @see SolidParticleSystem
  51482. */
  51483. var DepthSortedParticle = /** @class */ (function () {
  51484. function DepthSortedParticle() {
  51485. /**
  51486. * Index of the particle in the "indices" array
  51487. */
  51488. this.ind = 0;
  51489. /**
  51490. * Length of the particle shape in the "indices" array
  51491. */
  51492. this.indicesLength = 0;
  51493. /**
  51494. * Squared distance from the particle to the camera
  51495. */
  51496. this.sqDistance = 0.0;
  51497. }
  51498. return DepthSortedParticle;
  51499. }());
  51500. BABYLON.DepthSortedParticle = DepthSortedParticle;
  51501. })(BABYLON || (BABYLON = {}));
  51502. //# sourceMappingURL=babylon.solidParticle.js.map
  51503. var BABYLON;
  51504. (function (BABYLON) {
  51505. /**
  51506. * The SPS is a single updatable mesh. The solid particles are simply separate parts or faces fo this big mesh.
  51507. *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.
  51508. * The SPS is also a particle system. It provides some methods to manage the particles.
  51509. * However it is behavior agnostic. This means it has no emitter, no particle physics, no particle recycler. You have to implement your own behavior.
  51510. *
  51511. * Full documentation here : http://doc.babylonjs.com/overviews/Solid_Particle_System
  51512. */
  51513. var SolidParticleSystem = /** @class */ (function () {
  51514. /**
  51515. * Creates a SPS (Solid Particle System) object.
  51516. * @param name (String) is the SPS name, this will be the underlying mesh name.
  51517. * @param scene (Scene) is the scene in which the SPS is added.
  51518. * @param updatable (optional boolean, default true) : if the SPS must be updatable or immutable.
  51519. * @param isPickable (optional boolean, default false) : if the solid particles must be pickable.
  51520. * @param enableDepthSort (optional boolean, default false) : if the solid particles must be sorted in the geometry according to their distance to the camera.
  51521. * @param particleIntersection (optional boolean, default false) : if the solid particle intersections must be computed.
  51522. * @param boundingSphereOnly (optional boolean, default false) : if the particle intersection must be computed only with the bounding sphere (no bounding box computation, so faster).
  51523. * @param bSphereRadiusFactor (optional float, default 1.0) : a number to multiply the boundind sphere radius by in order to reduce it for instance.
  51524. * @example bSphereRadiusFactor = 1.0 / Math.sqrt(3.0) => the bounding sphere exactly matches a spherical mesh.
  51525. */
  51526. function SolidParticleSystem(name, scene, options) {
  51527. /**
  51528. * The SPS array of Solid Particle objects. Just access each particle as with any classic array.
  51529. * Example : var p = SPS.particles[i];
  51530. */
  51531. this.particles = new Array();
  51532. /**
  51533. * The SPS total number of particles. Read only. Use SPS.counter instead if you need to set your own value.
  51534. */
  51535. this.nbParticles = 0;
  51536. /**
  51537. * If the particles must ever face the camera (default false). Useful for planar particles.
  51538. */
  51539. this.billboard = false;
  51540. /**
  51541. * Recompute normals when adding a shape
  51542. */
  51543. this.recomputeNormals = true;
  51544. /**
  51545. * This a counter ofr your own usage. It's not set by any SPS functions.
  51546. */
  51547. this.counter = 0;
  51548. /**
  51549. * This empty object is intended to store some SPS specific or temporary values in order to lower the Garbage Collector activity.
  51550. * Please read : http://doc.babylonjs.com/overviews/Solid_Particle_System#garbage-collector-concerns
  51551. */
  51552. this.vars = {};
  51553. /**
  51554. * If the particle intersection must be computed only with the bounding sphere (no bounding box computation, so faster). (Internal use only)
  51555. */
  51556. this._bSphereOnly = false;
  51557. /**
  51558. * A number to multiply the boundind sphere radius by in order to reduce it for instance. (Internal use only)
  51559. */
  51560. this._bSphereRadiusFactor = 1.0;
  51561. this._positions = new Array();
  51562. this._indices = new Array();
  51563. this._normals = new Array();
  51564. this._colors = new Array();
  51565. this._uvs = new Array();
  51566. this._index = 0; // indices index
  51567. this._updatable = true;
  51568. this._pickable = false;
  51569. this._isVisibilityBoxLocked = false;
  51570. this._alwaysVisible = false;
  51571. this._depthSort = false;
  51572. this._shapeCounter = 0;
  51573. this._copy = new BABYLON.SolidParticle(0, 0, 0, null, 0, 0, this);
  51574. this._color = new BABYLON.Color4(0, 0, 0, 0);
  51575. this._computeParticleColor = true;
  51576. this._computeParticleTexture = true;
  51577. this._computeParticleRotation = true;
  51578. this._computeParticleVertex = false;
  51579. this._computeBoundingBox = false;
  51580. this._depthSortParticles = true;
  51581. this._cam_axisZ = BABYLON.Vector3.Zero();
  51582. this._cam_axisY = BABYLON.Vector3.Zero();
  51583. this._cam_axisX = BABYLON.Vector3.Zero();
  51584. this._axisZ = BABYLON.Axis.Z;
  51585. this._camDir = BABYLON.Vector3.Zero();
  51586. this._camInvertedPosition = BABYLON.Vector3.Zero();
  51587. this._rotMatrix = new BABYLON.Matrix();
  51588. this._invertMatrix = new BABYLON.Matrix();
  51589. this._rotated = BABYLON.Vector3.Zero();
  51590. this._quaternion = new BABYLON.Quaternion();
  51591. this._vertex = BABYLON.Vector3.Zero();
  51592. this._normal = BABYLON.Vector3.Zero();
  51593. this._yaw = 0.0;
  51594. this._pitch = 0.0;
  51595. this._roll = 0.0;
  51596. this._halfroll = 0.0;
  51597. this._halfpitch = 0.0;
  51598. this._halfyaw = 0.0;
  51599. this._sinRoll = 0.0;
  51600. this._cosRoll = 0.0;
  51601. this._sinPitch = 0.0;
  51602. this._cosPitch = 0.0;
  51603. this._sinYaw = 0.0;
  51604. this._cosYaw = 0.0;
  51605. this._mustUnrotateFixedNormals = false;
  51606. this._minimum = BABYLON.Vector3.Zero();
  51607. this._maximum = BABYLON.Vector3.Zero();
  51608. this._minBbox = BABYLON.Vector3.Zero();
  51609. this._maxBbox = BABYLON.Vector3.Zero();
  51610. this._particlesIntersect = false;
  51611. this._depthSortFunction = function (p1, p2) {
  51612. return (p2.sqDistance - p1.sqDistance);
  51613. };
  51614. this._needs32Bits = false;
  51615. this._pivotBackTranslation = BABYLON.Vector3.Zero();
  51616. this._scaledPivot = BABYLON.Vector3.Zero();
  51617. this._particleHasParent = false;
  51618. this.name = name;
  51619. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  51620. this._camera = scene.activeCamera;
  51621. this._pickable = options ? options.isPickable : false;
  51622. this._depthSort = options ? options.enableDepthSort : false;
  51623. this._particlesIntersect = options ? options.particleIntersection : false;
  51624. this._bSphereOnly = options ? options.boundingSphereOnly : false;
  51625. this._bSphereRadiusFactor = (options && options.bSphereRadiusFactor) ? options.bSphereRadiusFactor : 1.0;
  51626. if (options && options.updatable) {
  51627. this._updatable = options.updatable;
  51628. }
  51629. else {
  51630. this._updatable = true;
  51631. }
  51632. if (this._pickable) {
  51633. this.pickedParticles = [];
  51634. }
  51635. if (this._depthSort) {
  51636. this.depthSortedParticles = [];
  51637. }
  51638. }
  51639. /**
  51640. * Builds the SPS underlying mesh. Returns a standard Mesh.
  51641. * If no model shape was added to the SPS, the returned mesh is just a single triangular plane.
  51642. * @returns the created mesh
  51643. */
  51644. SolidParticleSystem.prototype.buildMesh = function () {
  51645. if (this.nbParticles === 0) {
  51646. var triangle = BABYLON.MeshBuilder.CreateDisc("", { radius: 1, tessellation: 3 }, this._scene);
  51647. this.addShape(triangle, 1);
  51648. triangle.dispose();
  51649. }
  51650. this._indices32 = (this._needs32Bits) ? new Uint32Array(this._indices) : new Uint16Array(this._indices);
  51651. this._positions32 = new Float32Array(this._positions);
  51652. this._uvs32 = new Float32Array(this._uvs);
  51653. this._colors32 = new Float32Array(this._colors);
  51654. if (this.recomputeNormals) {
  51655. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices32, this._normals);
  51656. }
  51657. this._normals32 = new Float32Array(this._normals);
  51658. this._fixedNormal32 = new Float32Array(this._normals);
  51659. if (this._mustUnrotateFixedNormals) {
  51660. this._unrotateFixedNormals();
  51661. }
  51662. var vertexData = new BABYLON.VertexData();
  51663. vertexData.indices = (this._depthSort) ? this._indices : this._indices32;
  51664. vertexData.set(this._positions32, BABYLON.VertexBuffer.PositionKind);
  51665. vertexData.set(this._normals32, BABYLON.VertexBuffer.NormalKind);
  51666. if (this._uvs32) {
  51667. vertexData.set(this._uvs32, BABYLON.VertexBuffer.UVKind);
  51668. ;
  51669. }
  51670. if (this._colors32) {
  51671. vertexData.set(this._colors32, BABYLON.VertexBuffer.ColorKind);
  51672. }
  51673. var mesh = new BABYLON.Mesh(this.name, this._scene);
  51674. vertexData.applyToMesh(mesh, this._updatable);
  51675. this.mesh = mesh;
  51676. this.mesh.isPickable = this._pickable;
  51677. // free memory
  51678. if (!this._depthSort) {
  51679. this._indices = null;
  51680. }
  51681. this._positions = null;
  51682. this._normals = null;
  51683. this._uvs = null;
  51684. this._colors = null;
  51685. if (!this._updatable) {
  51686. this.particles.length = 0;
  51687. }
  51688. return mesh;
  51689. };
  51690. /**
  51691. * Digests the mesh and generates as many solid particles in the system as wanted. Returns the SPS.
  51692. * These particles will have the same geometry than the mesh parts and will be positioned at the same localisation than the mesh original places.
  51693. * Thus the particles generated from `digest()` have their property `position` set yet.
  51694. * @param mesh ( Mesh ) is the mesh to be digested
  51695. * @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
  51696. * {delta} (optional integer, default 0) is the random extra number of facets per particle , each particle will have between `facetNb` and `facetNb + delta` facets
  51697. * {number} (optional positive integer) is the wanted number of particles : each particle is built with `mesh_total_facets / number` facets
  51698. * @returns the current SPS
  51699. */
  51700. SolidParticleSystem.prototype.digest = function (mesh, options) {
  51701. var size = (options && options.facetNb) || 1;
  51702. var number = (options && options.number) || 0;
  51703. var delta = (options && options.delta) || 0;
  51704. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  51705. var meshInd = mesh.getIndices();
  51706. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  51707. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  51708. var meshNor = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  51709. var f = 0; // facet counter
  51710. var totalFacets = meshInd.length / 3; // a facet is a triangle, so 3 indices
  51711. // compute size from number
  51712. if (number) {
  51713. number = (number > totalFacets) ? totalFacets : number;
  51714. size = Math.round(totalFacets / number);
  51715. delta = 0;
  51716. }
  51717. else {
  51718. size = (size > totalFacets) ? totalFacets : size;
  51719. }
  51720. var facetPos = []; // submesh positions
  51721. var facetInd = []; // submesh indices
  51722. var facetUV = []; // submesh UV
  51723. var facetCol = []; // submesh colors
  51724. var barycenter = BABYLON.Vector3.Zero();
  51725. var sizeO = size;
  51726. while (f < totalFacets) {
  51727. size = sizeO + Math.floor((1 + delta) * Math.random());
  51728. if (f > totalFacets - size) {
  51729. size = totalFacets - f;
  51730. }
  51731. // reset temp arrays
  51732. facetPos.length = 0;
  51733. facetInd.length = 0;
  51734. facetUV.length = 0;
  51735. facetCol.length = 0;
  51736. // iterate over "size" facets
  51737. var fi = 0;
  51738. for (var j = f * 3; j < (f + size) * 3; j++) {
  51739. facetInd.push(fi);
  51740. var i = meshInd[j];
  51741. facetPos.push(meshPos[i * 3], meshPos[i * 3 + 1], meshPos[i * 3 + 2]);
  51742. if (meshUV) {
  51743. facetUV.push(meshUV[i * 2], meshUV[i * 2 + 1]);
  51744. }
  51745. if (meshCol) {
  51746. facetCol.push(meshCol[i * 4], meshCol[i * 4 + 1], meshCol[i * 4 + 2], meshCol[i * 4 + 3]);
  51747. }
  51748. fi++;
  51749. }
  51750. // create a model shape for each single particle
  51751. var idx = this.nbParticles;
  51752. var shape = this._posToShape(facetPos);
  51753. var shapeUV = this._uvsToShapeUV(facetUV);
  51754. // compute the barycenter of the shape
  51755. var v;
  51756. for (v = 0; v < shape.length; v++) {
  51757. barycenter.addInPlace(shape[v]);
  51758. }
  51759. barycenter.scaleInPlace(1 / shape.length);
  51760. // shift the shape from its barycenter to the origin
  51761. for (v = 0; v < shape.length; v++) {
  51762. shape[v].subtractInPlace(barycenter);
  51763. }
  51764. var bInfo;
  51765. if (this._particlesIntersect) {
  51766. bInfo = new BABYLON.BoundingInfo(barycenter, barycenter);
  51767. }
  51768. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, size * 3, shapeUV, null, null);
  51769. // add the particle in the SPS
  51770. var currentPos = this._positions.length;
  51771. var currentInd = this._indices.length;
  51772. this._meshBuilder(this._index, shape, this._positions, facetInd, this._indices, facetUV, this._uvs, facetCol, this._colors, meshNor, this._normals, idx, 0, null);
  51773. this._addParticle(idx, currentPos, currentInd, modelShape, this._shapeCounter, 0, bInfo);
  51774. // initialize the particle position
  51775. this.particles[this.nbParticles].position.addInPlace(barycenter);
  51776. this._index += shape.length;
  51777. idx++;
  51778. this.nbParticles++;
  51779. this._shapeCounter++;
  51780. f += size;
  51781. }
  51782. return this;
  51783. };
  51784. // unrotate the fixed normals in case the mesh was built with pre-rotated particles, ex : use of positionFunction in addShape()
  51785. SolidParticleSystem.prototype._unrotateFixedNormals = function () {
  51786. var index = 0;
  51787. var idx = 0;
  51788. for (var p = 0; p < this.particles.length; p++) {
  51789. this._particle = this.particles[p];
  51790. this._shape = this._particle._model._shape;
  51791. if (this._particle.rotationQuaternion) {
  51792. this._quaternion.copyFrom(this._particle.rotationQuaternion);
  51793. }
  51794. else {
  51795. this._yaw = this._particle.rotation.y;
  51796. this._pitch = this._particle.rotation.x;
  51797. this._roll = this._particle.rotation.z;
  51798. this._quaternionRotationYPR();
  51799. }
  51800. this._quaternionToRotationMatrix();
  51801. this._rotMatrix.invertToRef(this._invertMatrix);
  51802. for (var pt = 0; pt < this._shape.length; pt++) {
  51803. idx = index + pt * 3;
  51804. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._normals32[idx], this._normals32[idx + 1], this._normals32[idx + 2], this._invertMatrix, this._normal);
  51805. this._fixedNormal32[idx] = this._normal.x;
  51806. this._fixedNormal32[idx + 1] = this._normal.y;
  51807. this._fixedNormal32[idx + 2] = this._normal.z;
  51808. }
  51809. index = idx + 3;
  51810. }
  51811. };
  51812. //reset copy
  51813. SolidParticleSystem.prototype._resetCopy = function () {
  51814. this._copy.position.x = 0;
  51815. this._copy.position.y = 0;
  51816. this._copy.position.z = 0;
  51817. this._copy.rotation.x = 0;
  51818. this._copy.rotation.y = 0;
  51819. this._copy.rotation.z = 0;
  51820. this._copy.rotationQuaternion = null;
  51821. this._copy.scaling.x = 1.0;
  51822. this._copy.scaling.y = 1.0;
  51823. this._copy.scaling.z = 1.0;
  51824. this._copy.uvs.x = 0;
  51825. this._copy.uvs.y = 0;
  51826. this._copy.uvs.z = 1.0;
  51827. this._copy.uvs.w = 1.0;
  51828. this._copy.color = null;
  51829. this._copy.translateFromPivot = false;
  51830. };
  51831. // _meshBuilder : inserts the shape model in the global SPS mesh
  51832. SolidParticleSystem.prototype._meshBuilder = function (p, shape, positions, meshInd, indices, meshUV, uvs, meshCol, colors, meshNor, normals, idx, idxInShape, options) {
  51833. var i;
  51834. var u = 0;
  51835. var c = 0;
  51836. var n = 0;
  51837. this._resetCopy();
  51838. if (options && options.positionFunction) {
  51839. options.positionFunction(this._copy, idx, idxInShape);
  51840. this._mustUnrotateFixedNormals = true;
  51841. }
  51842. if (this._copy.rotationQuaternion) {
  51843. this._quaternion.copyFrom(this._copy.rotationQuaternion);
  51844. }
  51845. else {
  51846. this._yaw = this._copy.rotation.y;
  51847. this._pitch = this._copy.rotation.x;
  51848. this._roll = this._copy.rotation.z;
  51849. this._quaternionRotationYPR();
  51850. }
  51851. this._quaternionToRotationMatrix();
  51852. this._scaledPivot.x = this._copy.pivot.x * this._copy.scaling.x;
  51853. this._scaledPivot.y = this._copy.pivot.y * this._copy.scaling.y;
  51854. this._scaledPivot.z = this._copy.pivot.z * this._copy.scaling.z;
  51855. if (this._copy.translateFromPivot) {
  51856. this._pivotBackTranslation.copyFromFloats(0.0, 0.0, 0.0);
  51857. }
  51858. else {
  51859. this._pivotBackTranslation.copyFrom(this._scaledPivot);
  51860. }
  51861. for (i = 0; i < shape.length; i++) {
  51862. this._vertex.x = shape[i].x;
  51863. this._vertex.y = shape[i].y;
  51864. this._vertex.z = shape[i].z;
  51865. if (options && options.vertexFunction) {
  51866. options.vertexFunction(this._copy, this._vertex, i);
  51867. }
  51868. this._vertex.x *= this._copy.scaling.x;
  51869. this._vertex.y *= this._copy.scaling.y;
  51870. this._vertex.z *= this._copy.scaling.z;
  51871. this._vertex.x -= this._scaledPivot.x;
  51872. this._vertex.y -= this._scaledPivot.y;
  51873. this._vertex.z -= this._scaledPivot.z;
  51874. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  51875. this._rotated.addInPlace(this._pivotBackTranslation);
  51876. positions.push(this._copy.position.x + this._rotated.x, this._copy.position.y + this._rotated.y, this._copy.position.z + this._rotated.z);
  51877. if (meshUV) {
  51878. 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);
  51879. u += 2;
  51880. }
  51881. if (this._copy.color) {
  51882. this._color = this._copy.color;
  51883. }
  51884. else if (meshCol && meshCol[c] !== undefined) {
  51885. this._color.r = meshCol[c];
  51886. this._color.g = meshCol[c + 1];
  51887. this._color.b = meshCol[c + 2];
  51888. this._color.a = meshCol[c + 3];
  51889. }
  51890. else {
  51891. this._color.r = 1.0;
  51892. this._color.g = 1.0;
  51893. this._color.b = 1.0;
  51894. this._color.a = 1.0;
  51895. }
  51896. colors.push(this._color.r, this._color.g, this._color.b, this._color.a);
  51897. c += 4;
  51898. if (!this.recomputeNormals && meshNor) {
  51899. this._normal.x = meshNor[n];
  51900. this._normal.y = meshNor[n + 1];
  51901. this._normal.z = meshNor[n + 2];
  51902. BABYLON.Vector3.TransformNormalToRef(this._normal, this._rotMatrix, this._normal);
  51903. normals.push(this._normal.x, this._normal.y, this._normal.z);
  51904. n += 3;
  51905. }
  51906. }
  51907. for (i = 0; i < meshInd.length; i++) {
  51908. var current_ind = p + meshInd[i];
  51909. indices.push(current_ind);
  51910. if (current_ind > 65535) {
  51911. this._needs32Bits = true;
  51912. }
  51913. }
  51914. if (this._pickable) {
  51915. var nbfaces = meshInd.length / 3;
  51916. for (i = 0; i < nbfaces; i++) {
  51917. this.pickedParticles.push({ idx: idx, faceId: i });
  51918. }
  51919. }
  51920. if (this._depthSort) {
  51921. this.depthSortedParticles.push(new BABYLON.DepthSortedParticle());
  51922. }
  51923. return this._copy;
  51924. };
  51925. // returns a shape array from positions array
  51926. SolidParticleSystem.prototype._posToShape = function (positions) {
  51927. var shape = [];
  51928. for (var i = 0; i < positions.length; i += 3) {
  51929. shape.push(new BABYLON.Vector3(positions[i], positions[i + 1], positions[i + 2]));
  51930. }
  51931. return shape;
  51932. };
  51933. // returns a shapeUV array from a Vector4 uvs
  51934. SolidParticleSystem.prototype._uvsToShapeUV = function (uvs) {
  51935. var shapeUV = [];
  51936. if (uvs) {
  51937. for (var i = 0; i < uvs.length; i++)
  51938. shapeUV.push(uvs[i]);
  51939. }
  51940. return shapeUV;
  51941. };
  51942. // adds a new particle object in the particles array
  51943. SolidParticleSystem.prototype._addParticle = function (idx, idxpos, idxind, model, shapeId, idxInShape, bInfo) {
  51944. if (bInfo === void 0) { bInfo = null; }
  51945. var sp = new BABYLON.SolidParticle(idx, idxpos, idxind, model, shapeId, idxInShape, this, bInfo);
  51946. this.particles.push(sp);
  51947. return sp;
  51948. };
  51949. /**
  51950. * Adds some particles to the SPS from the model shape. Returns the shape id.
  51951. * Please read the doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#create-an-immutable-sps
  51952. * @param mesh is any Mesh object that will be used as a model for the solid particles.
  51953. * @param nb (positive integer) the number of particles to be created from this model
  51954. * @param options {positionFunction} is an optional javascript function to called for each particle on SPS creation.
  51955. * {vertexFunction} is an optional javascript function to called for each vertex of each particle on SPS creation
  51956. * @returns the number of shapes in the system
  51957. */
  51958. SolidParticleSystem.prototype.addShape = function (mesh, nb, options) {
  51959. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  51960. var meshInd = mesh.getIndices();
  51961. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  51962. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  51963. var meshNor = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  51964. var bbInfo;
  51965. if (this._particlesIntersect) {
  51966. bbInfo = mesh.getBoundingInfo();
  51967. }
  51968. var shape = this._posToShape(meshPos);
  51969. var shapeUV = this._uvsToShapeUV(meshUV);
  51970. var posfunc = options ? options.positionFunction : null;
  51971. var vtxfunc = options ? options.vertexFunction : null;
  51972. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, meshInd.length, shapeUV, posfunc, vtxfunc);
  51973. // particles
  51974. var sp;
  51975. var currentCopy;
  51976. var idx = this.nbParticles;
  51977. for (var i = 0; i < nb; i++) {
  51978. var currentPos = this._positions.length;
  51979. var currentInd = this._indices.length;
  51980. currentCopy = this._meshBuilder(this._index, shape, this._positions, meshInd, this._indices, meshUV, this._uvs, meshCol, this._colors, meshNor, this._normals, idx, i, options);
  51981. if (this._updatable) {
  51982. sp = this._addParticle(idx, currentPos, currentInd, modelShape, this._shapeCounter, i, bbInfo);
  51983. sp.position.copyFrom(currentCopy.position);
  51984. sp.rotation.copyFrom(currentCopy.rotation);
  51985. if (currentCopy.rotationQuaternion && sp.rotationQuaternion) {
  51986. sp.rotationQuaternion.copyFrom(currentCopy.rotationQuaternion);
  51987. }
  51988. if (currentCopy.color && sp.color) {
  51989. sp.color.copyFrom(currentCopy.color);
  51990. }
  51991. sp.scaling.copyFrom(currentCopy.scaling);
  51992. sp.uvs.copyFrom(currentCopy.uvs);
  51993. }
  51994. this._index += shape.length;
  51995. idx++;
  51996. }
  51997. this.nbParticles += nb;
  51998. this._shapeCounter++;
  51999. return this._shapeCounter - 1;
  52000. };
  52001. // rebuilds a particle back to its just built status : if needed, recomputes the custom positions and vertices
  52002. SolidParticleSystem.prototype._rebuildParticle = function (particle) {
  52003. this._resetCopy();
  52004. if (particle._model._positionFunction) {
  52005. particle._model._positionFunction(this._copy, particle.idx, particle.idxInShape);
  52006. }
  52007. if (this._copy.rotationQuaternion) {
  52008. this._quaternion.copyFrom(this._copy.rotationQuaternion);
  52009. }
  52010. else {
  52011. this._yaw = this._copy.rotation.y;
  52012. this._pitch = this._copy.rotation.x;
  52013. this._roll = this._copy.rotation.z;
  52014. this._quaternionRotationYPR();
  52015. }
  52016. this._quaternionToRotationMatrix();
  52017. this._scaledPivot.x = this._particle.pivot.x * this._particle.scaling.x;
  52018. this._scaledPivot.y = this._particle.pivot.y * this._particle.scaling.y;
  52019. this._scaledPivot.z = this._particle.pivot.z * this._particle.scaling.z;
  52020. if (this._copy.translateFromPivot) {
  52021. this._pivotBackTranslation.copyFromFloats(0.0, 0.0, 0.0);
  52022. }
  52023. else {
  52024. this._pivotBackTranslation.copyFrom(this._scaledPivot);
  52025. }
  52026. this._shape = particle._model._shape;
  52027. for (var pt = 0; pt < this._shape.length; pt++) {
  52028. this._vertex.x = this._shape[pt].x;
  52029. this._vertex.y = this._shape[pt].y;
  52030. this._vertex.z = this._shape[pt].z;
  52031. if (particle._model._vertexFunction) {
  52032. particle._model._vertexFunction(this._copy, this._vertex, pt); // recall to stored vertexFunction
  52033. }
  52034. this._vertex.x *= this._copy.scaling.x;
  52035. this._vertex.y *= this._copy.scaling.y;
  52036. this._vertex.z *= this._copy.scaling.z;
  52037. this._vertex.x -= this._scaledPivot.x;
  52038. this._vertex.y -= this._scaledPivot.y;
  52039. this._vertex.z -= this._scaledPivot.z;
  52040. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  52041. this._rotated.addInPlace(this._pivotBackTranslation);
  52042. this._positions32[particle._pos + pt * 3] = this._copy.position.x + this._rotated.x;
  52043. this._positions32[particle._pos + pt * 3 + 1] = this._copy.position.y + this._rotated.y;
  52044. this._positions32[particle._pos + pt * 3 + 2] = this._copy.position.z + this._rotated.z;
  52045. }
  52046. particle.position.x = 0.0;
  52047. particle.position.y = 0.0;
  52048. particle.position.z = 0.0;
  52049. particle.rotation.x = 0.0;
  52050. particle.rotation.y = 0.0;
  52051. particle.rotation.z = 0.0;
  52052. particle.rotationQuaternion = null;
  52053. particle.scaling.x = 1.0;
  52054. particle.scaling.y = 1.0;
  52055. particle.scaling.z = 1.0;
  52056. particle.uvs.x = 0.0;
  52057. particle.uvs.y = 0.0;
  52058. particle.uvs.z = 1.0;
  52059. particle.uvs.w = 1.0;
  52060. particle.pivot.x = 0.0;
  52061. particle.pivot.y = 0.0;
  52062. particle.pivot.z = 0.0;
  52063. particle.translateFromPivot = false;
  52064. particle.parentId = null;
  52065. };
  52066. /**
  52067. * Rebuilds the whole mesh and updates the VBO : custom positions and vertices are recomputed if needed.
  52068. * @returns the SPS.
  52069. */
  52070. SolidParticleSystem.prototype.rebuildMesh = function () {
  52071. for (var p = 0; p < this.particles.length; p++) {
  52072. this._rebuildParticle(this.particles[p]);
  52073. }
  52074. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  52075. return this;
  52076. };
  52077. /**
  52078. * Sets all the particles : this method actually really updates the mesh according to the particle positions, rotations, colors, textures, etc.
  52079. * This method calls `updateParticle()` for each particle of the SPS.
  52080. * For an animated SPS, it is usually called within the render loop.
  52081. * @param start The particle index in the particle array where to start to compute the particle property values _(default 0)_
  52082. * @param end The particle index in the particle array where to stop to compute the particle property values _(default nbParticle - 1)_
  52083. * @param update If the mesh must be finally updated on this call after all the particle computations _(default true)_
  52084. * @returns the SPS.
  52085. */
  52086. SolidParticleSystem.prototype.setParticles = function (start, end, update) {
  52087. if (start === void 0) { start = 0; }
  52088. if (end === void 0) { end = this.nbParticles - 1; }
  52089. if (update === void 0) { update = true; }
  52090. if (!this._updatable) {
  52091. return this;
  52092. }
  52093. // custom beforeUpdate
  52094. this.beforeUpdateParticles(start, end, update);
  52095. this._cam_axisX.x = 1.0;
  52096. this._cam_axisX.y = 0.0;
  52097. this._cam_axisX.z = 0.0;
  52098. this._cam_axisY.x = 0.0;
  52099. this._cam_axisY.y = 1.0;
  52100. this._cam_axisY.z = 0.0;
  52101. this._cam_axisZ.x = 0.0;
  52102. this._cam_axisZ.y = 0.0;
  52103. this._cam_axisZ.z = 1.0;
  52104. // cases when the World Matrix is to be computed first
  52105. if (this.billboard || this._depthSort) {
  52106. this.mesh.computeWorldMatrix(true);
  52107. this.mesh._worldMatrix.invertToRef(this._invertMatrix);
  52108. }
  52109. // if the particles will always face the camera
  52110. if (this.billboard) {
  52111. // compute the camera position and un-rotate it by the current mesh rotation
  52112. this._camera.getDirectionToRef(this._axisZ, this._camDir);
  52113. BABYLON.Vector3.TransformNormalToRef(this._camDir, this._invertMatrix, this._cam_axisZ);
  52114. this._cam_axisZ.normalize();
  52115. // same for camera up vector extracted from the cam view matrix
  52116. var view = this._camera.getViewMatrix(true);
  52117. BABYLON.Vector3.TransformNormalFromFloatsToRef(view.m[1], view.m[5], view.m[9], this._invertMatrix, this._cam_axisY);
  52118. BABYLON.Vector3.CrossToRef(this._cam_axisY, this._cam_axisZ, this._cam_axisX);
  52119. this._cam_axisY.normalize();
  52120. this._cam_axisX.normalize();
  52121. }
  52122. // if depthSort, compute the camera global position in the mesh local system
  52123. if (this._depthSort) {
  52124. BABYLON.Vector3.TransformCoordinatesToRef(this._camera.globalPosition, this._invertMatrix, this._camInvertedPosition); // then un-rotate the camera
  52125. }
  52126. BABYLON.Matrix.IdentityToRef(this._rotMatrix);
  52127. var idx = 0; // current position index in the global array positions32
  52128. var index = 0; // position start index in the global array positions32 of the current particle
  52129. var colidx = 0; // current color index in the global array colors32
  52130. var colorIndex = 0; // color start index in the global array colors32 of the current particle
  52131. var uvidx = 0; // current uv index in the global array uvs32
  52132. var uvIndex = 0; // uv start index in the global array uvs32 of the current particle
  52133. var pt = 0; // current index in the particle model shape
  52134. if (this.mesh.isFacetDataEnabled) {
  52135. this._computeBoundingBox = true;
  52136. }
  52137. end = (end >= this.nbParticles) ? this.nbParticles - 1 : end;
  52138. if (this._computeBoundingBox) {
  52139. if (start == 0 && end == this.nbParticles - 1) {
  52140. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this._minimum);
  52141. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this._maximum);
  52142. }
  52143. else {
  52144. if (this.mesh._boundingInfo) {
  52145. this._minimum.copyFrom(this.mesh._boundingInfo.boundingBox.minimum);
  52146. this._maximum.copyFrom(this.mesh._boundingInfo.boundingBox.maximum);
  52147. }
  52148. }
  52149. }
  52150. // particle loop
  52151. index = this.particles[start]._pos;
  52152. var vpos = (index / 3) | 0;
  52153. colorIndex = vpos * 4;
  52154. uvIndex = vpos * 2;
  52155. for (var p = start; p <= end; p++) {
  52156. this._particle = this.particles[p];
  52157. this._shape = this._particle._model._shape;
  52158. this._shapeUV = this._particle._model._shapeUV;
  52159. // call to custom user function to update the particle properties
  52160. this.updateParticle(this._particle);
  52161. // camera-particle distance for depth sorting
  52162. if (this._depthSort && this._depthSortParticles) {
  52163. var dsp = this.depthSortedParticles[p];
  52164. dsp.ind = this._particle._ind;
  52165. dsp.indicesLength = this._particle._model._indicesLength;
  52166. dsp.sqDistance = BABYLON.Vector3.DistanceSquared(this._particle.position, this._camInvertedPosition);
  52167. }
  52168. // skip the computations for inactive or already invisible particles
  52169. if (!this._particle.alive || (this._particle._stillInvisible && !this._particle.isVisible)) {
  52170. // increment indexes for the next particle
  52171. pt = this._shape.length;
  52172. index += pt * 3;
  52173. colorIndex += pt * 4;
  52174. uvIndex += pt * 2;
  52175. continue;
  52176. }
  52177. if (this._particle.isVisible) {
  52178. this._particle._stillInvisible = false; // un-mark permanent invisibility
  52179. this._particleHasParent = (this._particle.parentId !== null);
  52180. this._scaledPivot.x = this._particle.pivot.x * this._particle.scaling.x;
  52181. this._scaledPivot.y = this._particle.pivot.y * this._particle.scaling.y;
  52182. this._scaledPivot.z = this._particle.pivot.z * this._particle.scaling.z;
  52183. // particle rotation matrix
  52184. if (this.billboard) {
  52185. this._particle.rotation.x = 0.0;
  52186. this._particle.rotation.y = 0.0;
  52187. }
  52188. if (this._computeParticleRotation || this.billboard) {
  52189. if (this._particle.rotationQuaternion) {
  52190. this._quaternion.copyFrom(this._particle.rotationQuaternion);
  52191. }
  52192. else {
  52193. this._yaw = this._particle.rotation.y;
  52194. this._pitch = this._particle.rotation.x;
  52195. this._roll = this._particle.rotation.z;
  52196. this._quaternionRotationYPR();
  52197. }
  52198. this._quaternionToRotationMatrix();
  52199. }
  52200. if (this._particleHasParent) {
  52201. this._parent = this.particles[this._particle.parentId];
  52202. 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];
  52203. 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];
  52204. 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];
  52205. this._particle._globalPosition.x = this._parent._globalPosition.x + this._rotated.x;
  52206. this._particle._globalPosition.y = this._parent._globalPosition.y + this._rotated.y;
  52207. this._particle._globalPosition.z = this._parent._globalPosition.z + this._rotated.z;
  52208. if (this._computeParticleRotation || this.billboard) {
  52209. 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];
  52210. 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];
  52211. 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];
  52212. 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];
  52213. 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];
  52214. 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];
  52215. 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];
  52216. 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];
  52217. 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];
  52218. }
  52219. }
  52220. else {
  52221. this._particle._globalPosition.x = this._particle.position.x;
  52222. this._particle._globalPosition.y = this._particle.position.y;
  52223. this._particle._globalPosition.z = this._particle.position.z;
  52224. if (this._computeParticleRotation || this.billboard) {
  52225. this._particle._rotationMatrix[0] = this._rotMatrix.m[0];
  52226. this._particle._rotationMatrix[1] = this._rotMatrix.m[1];
  52227. this._particle._rotationMatrix[2] = this._rotMatrix.m[2];
  52228. this._particle._rotationMatrix[3] = this._rotMatrix.m[4];
  52229. this._particle._rotationMatrix[4] = this._rotMatrix.m[5];
  52230. this._particle._rotationMatrix[5] = this._rotMatrix.m[6];
  52231. this._particle._rotationMatrix[6] = this._rotMatrix.m[8];
  52232. this._particle._rotationMatrix[7] = this._rotMatrix.m[9];
  52233. this._particle._rotationMatrix[8] = this._rotMatrix.m[10];
  52234. }
  52235. }
  52236. if (this._particle.translateFromPivot) {
  52237. this._pivotBackTranslation.x = 0.0;
  52238. this._pivotBackTranslation.y = 0.0;
  52239. this._pivotBackTranslation.z = 0.0;
  52240. }
  52241. else {
  52242. this._pivotBackTranslation.x = this._scaledPivot.x;
  52243. this._pivotBackTranslation.y = this._scaledPivot.y;
  52244. this._pivotBackTranslation.z = this._scaledPivot.z;
  52245. }
  52246. // particle vertex loop
  52247. for (pt = 0; pt < this._shape.length; pt++) {
  52248. idx = index + pt * 3;
  52249. colidx = colorIndex + pt * 4;
  52250. uvidx = uvIndex + pt * 2;
  52251. this._vertex.x = this._shape[pt].x;
  52252. this._vertex.y = this._shape[pt].y;
  52253. this._vertex.z = this._shape[pt].z;
  52254. if (this._computeParticleVertex) {
  52255. this.updateParticleVertex(this._particle, this._vertex, pt);
  52256. }
  52257. // positions
  52258. this._vertex.x *= this._particle.scaling.x;
  52259. this._vertex.y *= this._particle.scaling.y;
  52260. this._vertex.z *= this._particle.scaling.z;
  52261. this._vertex.x -= this._scaledPivot.x;
  52262. this._vertex.y -= this._scaledPivot.y;
  52263. this._vertex.z -= this._scaledPivot.z;
  52264. this._rotated.x = this._vertex.x * this._particle._rotationMatrix[0] + this._vertex.y * this._particle._rotationMatrix[3] + this._vertex.z * this._particle._rotationMatrix[6];
  52265. this._rotated.y = this._vertex.x * this._particle._rotationMatrix[1] + this._vertex.y * this._particle._rotationMatrix[4] + this._vertex.z * this._particle._rotationMatrix[7];
  52266. this._rotated.z = this._vertex.x * this._particle._rotationMatrix[2] + this._vertex.y * this._particle._rotationMatrix[5] + this._vertex.z * this._particle._rotationMatrix[8];
  52267. this._rotated.x += this._pivotBackTranslation.x;
  52268. this._rotated.y += this._pivotBackTranslation.y;
  52269. this._rotated.z += this._pivotBackTranslation.z;
  52270. 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;
  52271. 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;
  52272. 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;
  52273. if (this._computeBoundingBox) {
  52274. if (this._positions32[idx] < this._minimum.x) {
  52275. this._minimum.x = this._positions32[idx];
  52276. }
  52277. if (this._positions32[idx] > this._maximum.x) {
  52278. this._maximum.x = this._positions32[idx];
  52279. }
  52280. if (this._positions32[idx + 1] < this._minimum.y) {
  52281. this._minimum.y = this._positions32[idx + 1];
  52282. }
  52283. if (this._positions32[idx + 1] > this._maximum.y) {
  52284. this._maximum.y = this._positions32[idx + 1];
  52285. }
  52286. if (this._positions32[idx + 2] < this._minimum.z) {
  52287. this._minimum.z = this._positions32[idx + 2];
  52288. }
  52289. if (this._positions32[idx + 2] > this._maximum.z) {
  52290. this._maximum.z = this._positions32[idx + 2];
  52291. }
  52292. }
  52293. // normals : if the particles can't be morphed then just rotate the normals, what is much more faster than ComputeNormals()
  52294. if (!this._computeParticleVertex) {
  52295. this._normal.x = this._fixedNormal32[idx];
  52296. this._normal.y = this._fixedNormal32[idx + 1];
  52297. this._normal.z = this._fixedNormal32[idx + 2];
  52298. this._rotated.x = this._normal.x * this._particle._rotationMatrix[0] + this._normal.y * this._particle._rotationMatrix[3] + this._normal.z * this._particle._rotationMatrix[6];
  52299. this._rotated.y = this._normal.x * this._particle._rotationMatrix[1] + this._normal.y * this._particle._rotationMatrix[4] + this._normal.z * this._particle._rotationMatrix[7];
  52300. this._rotated.z = this._normal.x * this._particle._rotationMatrix[2] + this._normal.y * this._particle._rotationMatrix[5] + this._normal.z * this._particle._rotationMatrix[8];
  52301. this._normals32[idx] = this._cam_axisX.x * this._rotated.x + this._cam_axisY.x * this._rotated.y + this._cam_axisZ.x * this._rotated.z;
  52302. 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;
  52303. 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;
  52304. }
  52305. if (this._computeParticleColor && this._particle.color) {
  52306. this._colors32[colidx] = this._particle.color.r;
  52307. this._colors32[colidx + 1] = this._particle.color.g;
  52308. this._colors32[colidx + 2] = this._particle.color.b;
  52309. this._colors32[colidx + 3] = this._particle.color.a;
  52310. }
  52311. if (this._computeParticleTexture) {
  52312. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  52313. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  52314. }
  52315. }
  52316. }
  52317. else {
  52318. this._particle._stillInvisible = true; // mark the particle as invisible
  52319. for (pt = 0; pt < this._shape.length; pt++) {
  52320. idx = index + pt * 3;
  52321. colidx = colorIndex + pt * 4;
  52322. uvidx = uvIndex + pt * 2;
  52323. this._positions32[idx] = 0.0;
  52324. this._positions32[idx + 1] = 0.0;
  52325. this._positions32[idx + 2] = 0.0;
  52326. this._normals32[idx] = 0.0;
  52327. this._normals32[idx + 1] = 0.0;
  52328. this._normals32[idx + 2] = 0.0;
  52329. if (this._computeParticleColor && this._particle.color) {
  52330. this._colors32[colidx] = this._particle.color.r;
  52331. this._colors32[colidx + 1] = this._particle.color.g;
  52332. this._colors32[colidx + 2] = this._particle.color.b;
  52333. this._colors32[colidx + 3] = this._particle.color.a;
  52334. }
  52335. if (this._computeParticleTexture) {
  52336. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  52337. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  52338. }
  52339. }
  52340. }
  52341. // if the particle intersections must be computed : update the bbInfo
  52342. if (this._particlesIntersect) {
  52343. var bInfo = this._particle._boundingInfo;
  52344. var bBox = bInfo.boundingBox;
  52345. var bSphere = bInfo.boundingSphere;
  52346. if (!this._bSphereOnly) {
  52347. // place, scale and rotate the particle bbox within the SPS local system, then update it
  52348. for (var b = 0; b < bBox.vectors.length; b++) {
  52349. this._vertex.x = this._particle._modelBoundingInfo.boundingBox.vectors[b].x * this._particle.scaling.x;
  52350. this._vertex.y = this._particle._modelBoundingInfo.boundingBox.vectors[b].y * this._particle.scaling.y;
  52351. this._vertex.z = this._particle._modelBoundingInfo.boundingBox.vectors[b].z * this._particle.scaling.z;
  52352. this._rotated.x = this._vertex.x * this._particle._rotationMatrix[0] + this._vertex.y * this._particle._rotationMatrix[3] + this._vertex.z * this._particle._rotationMatrix[6];
  52353. this._rotated.y = this._vertex.x * this._particle._rotationMatrix[1] + this._vertex.y * this._particle._rotationMatrix[4] + this._vertex.z * this._particle._rotationMatrix[7];
  52354. this._rotated.z = this._vertex.x * this._particle._rotationMatrix[2] + this._vertex.y * this._particle._rotationMatrix[5] + this._vertex.z * this._particle._rotationMatrix[8];
  52355. 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;
  52356. 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;
  52357. 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;
  52358. }
  52359. bBox._update(this.mesh._worldMatrix);
  52360. }
  52361. // place and scale the particle bouding sphere in the SPS local system, then update it
  52362. this._minBbox.x = this._particle._modelBoundingInfo.minimum.x * this._particle.scaling.x;
  52363. this._minBbox.y = this._particle._modelBoundingInfo.minimum.y * this._particle.scaling.y;
  52364. this._minBbox.z = this._particle._modelBoundingInfo.minimum.z * this._particle.scaling.z;
  52365. this._maxBbox.x = this._particle._modelBoundingInfo.maximum.x * this._particle.scaling.x;
  52366. this._maxBbox.y = this._particle._modelBoundingInfo.maximum.y * this._particle.scaling.y;
  52367. this._maxBbox.z = this._particle._modelBoundingInfo.maximum.z * this._particle.scaling.z;
  52368. bSphere.center.x = this._particle._globalPosition.x + (this._minBbox.x + this._maxBbox.x) * 0.5;
  52369. bSphere.center.y = this._particle._globalPosition.y + (this._minBbox.y + this._maxBbox.y) * 0.5;
  52370. bSphere.center.z = this._particle._globalPosition.z + (this._minBbox.z + this._maxBbox.z) * 0.5;
  52371. 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));
  52372. bSphere._update(this.mesh._worldMatrix);
  52373. }
  52374. // increment indexes for the next particle
  52375. index = idx + 3;
  52376. colorIndex = colidx + 4;
  52377. uvIndex = uvidx + 2;
  52378. }
  52379. // if the VBO must be updated
  52380. if (update) {
  52381. if (this._computeParticleColor) {
  52382. this.mesh.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this._colors32, false, false);
  52383. }
  52384. if (this._computeParticleTexture) {
  52385. this.mesh.updateVerticesData(BABYLON.VertexBuffer.UVKind, this._uvs32, false, false);
  52386. }
  52387. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  52388. if (!this.mesh.areNormalsFrozen || this.mesh.isFacetDataEnabled) {
  52389. if (this._computeParticleVertex || this.mesh.isFacetDataEnabled) {
  52390. // recompute the normals only if the particles can be morphed, update then also the normal reference array _fixedNormal32[]
  52391. var params = this.mesh.isFacetDataEnabled ? this.mesh.getFacetDataParameters() : null;
  52392. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices32, this._normals32, params);
  52393. for (var i = 0; i < this._normals32.length; i++) {
  52394. this._fixedNormal32[i] = this._normals32[i];
  52395. }
  52396. }
  52397. if (!this.mesh.areNormalsFrozen) {
  52398. this.mesh.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this._normals32, false, false);
  52399. }
  52400. }
  52401. if (this._depthSort && this._depthSortParticles) {
  52402. this.depthSortedParticles.sort(this._depthSortFunction);
  52403. var dspl = this.depthSortedParticles.length;
  52404. var sorted = 0;
  52405. var lind = 0;
  52406. var sind = 0;
  52407. var sid = 0;
  52408. for (sorted = 0; sorted < dspl; sorted++) {
  52409. lind = this.depthSortedParticles[sorted].indicesLength;
  52410. sind = this.depthSortedParticles[sorted].ind;
  52411. for (var i = 0; i < lind; i++) {
  52412. this._indices32[sid] = this._indices[sind + i];
  52413. sid++;
  52414. }
  52415. }
  52416. this.mesh.updateIndices(this._indices32);
  52417. }
  52418. }
  52419. if (this._computeBoundingBox) {
  52420. this.mesh._boundingInfo = new BABYLON.BoundingInfo(this._minimum, this._maximum);
  52421. this.mesh._boundingInfo.update(this.mesh._worldMatrix);
  52422. }
  52423. this.afterUpdateParticles(start, end, update);
  52424. return this;
  52425. };
  52426. SolidParticleSystem.prototype._quaternionRotationYPR = function () {
  52427. this._halfroll = this._roll * 0.5;
  52428. this._halfpitch = this._pitch * 0.5;
  52429. this._halfyaw = this._yaw * 0.5;
  52430. this._sinRoll = Math.sin(this._halfroll);
  52431. this._cosRoll = Math.cos(this._halfroll);
  52432. this._sinPitch = Math.sin(this._halfpitch);
  52433. this._cosPitch = Math.cos(this._halfpitch);
  52434. this._sinYaw = Math.sin(this._halfyaw);
  52435. this._cosYaw = Math.cos(this._halfyaw);
  52436. this._quaternion.x = this._cosYaw * this._sinPitch * this._cosRoll + this._sinYaw * this._cosPitch * this._sinRoll;
  52437. this._quaternion.y = this._sinYaw * this._cosPitch * this._cosRoll - this._cosYaw * this._sinPitch * this._sinRoll;
  52438. this._quaternion.z = this._cosYaw * this._cosPitch * this._sinRoll - this._sinYaw * this._sinPitch * this._cosRoll;
  52439. this._quaternion.w = this._cosYaw * this._cosPitch * this._cosRoll + this._sinYaw * this._sinPitch * this._sinRoll;
  52440. };
  52441. SolidParticleSystem.prototype._quaternionToRotationMatrix = function () {
  52442. this._rotMatrix.m[0] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.z * this._quaternion.z));
  52443. this._rotMatrix.m[1] = 2.0 * (this._quaternion.x * this._quaternion.y + this._quaternion.z * this._quaternion.w);
  52444. this._rotMatrix.m[2] = 2.0 * (this._quaternion.z * this._quaternion.x - this._quaternion.y * this._quaternion.w);
  52445. this._rotMatrix.m[3] = 0;
  52446. this._rotMatrix.m[4] = 2.0 * (this._quaternion.x * this._quaternion.y - this._quaternion.z * this._quaternion.w);
  52447. this._rotMatrix.m[5] = 1.0 - (2.0 * (this._quaternion.z * this._quaternion.z + this._quaternion.x * this._quaternion.x));
  52448. this._rotMatrix.m[6] = 2.0 * (this._quaternion.y * this._quaternion.z + this._quaternion.x * this._quaternion.w);
  52449. this._rotMatrix.m[7] = 0;
  52450. this._rotMatrix.m[8] = 2.0 * (this._quaternion.z * this._quaternion.x + this._quaternion.y * this._quaternion.w);
  52451. this._rotMatrix.m[9] = 2.0 * (this._quaternion.y * this._quaternion.z - this._quaternion.x * this._quaternion.w);
  52452. this._rotMatrix.m[10] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.x * this._quaternion.x));
  52453. this._rotMatrix.m[11] = 0;
  52454. this._rotMatrix.m[12] = 0;
  52455. this._rotMatrix.m[13] = 0;
  52456. this._rotMatrix.m[14] = 0;
  52457. this._rotMatrix.m[15] = 1.0;
  52458. };
  52459. /**
  52460. * Disposes the SPS.
  52461. */
  52462. SolidParticleSystem.prototype.dispose = function () {
  52463. this.mesh.dispose();
  52464. this.vars = null;
  52465. // drop references to internal big arrays for the GC
  52466. this._positions = null;
  52467. this._indices = null;
  52468. this._normals = null;
  52469. this._uvs = null;
  52470. this._colors = null;
  52471. this._indices32 = null;
  52472. this._positions32 = null;
  52473. this._normals32 = null;
  52474. this._fixedNormal32 = null;
  52475. this._uvs32 = null;
  52476. this._colors32 = null;
  52477. this.pickedParticles = null;
  52478. };
  52479. /**
  52480. * Visibilty helper : Recomputes the visible size according to the mesh bounding box
  52481. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  52482. * @returns the SPS.
  52483. */
  52484. SolidParticleSystem.prototype.refreshVisibleSize = function () {
  52485. if (!this._isVisibilityBoxLocked) {
  52486. this.mesh.refreshBoundingInfo();
  52487. }
  52488. return this;
  52489. };
  52490. /**
  52491. * Visibility helper : Sets the size of a visibility box, this sets the underlying mesh bounding box.
  52492. * @param size the size (float) of the visibility box
  52493. * note : this doesn't lock the SPS mesh bounding box.
  52494. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  52495. */
  52496. SolidParticleSystem.prototype.setVisibilityBox = function (size) {
  52497. var vis = size / 2;
  52498. this.mesh._boundingInfo = new BABYLON.BoundingInfo(new BABYLON.Vector3(-vis, -vis, -vis), new BABYLON.Vector3(vis, vis, vis));
  52499. };
  52500. Object.defineProperty(SolidParticleSystem.prototype, "isAlwaysVisible", {
  52501. /**
  52502. * Gets whether the SPS as always visible or not
  52503. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  52504. */
  52505. get: function () {
  52506. return this._alwaysVisible;
  52507. },
  52508. /**
  52509. * Sets the SPS as always visible or not
  52510. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  52511. */
  52512. set: function (val) {
  52513. this._alwaysVisible = val;
  52514. this.mesh.alwaysSelectAsActiveMesh = val;
  52515. },
  52516. enumerable: true,
  52517. configurable: true
  52518. });
  52519. Object.defineProperty(SolidParticleSystem.prototype, "isVisibilityBoxLocked", {
  52520. /**
  52521. * Gets if the SPS visibility box as locked or not. This enables/disables the underlying mesh bounding box updates.
  52522. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  52523. */
  52524. get: function () {
  52525. return this._isVisibilityBoxLocked;
  52526. },
  52527. /**
  52528. * Sets the SPS visibility box as locked or not. This enables/disables the underlying mesh bounding box updates.
  52529. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  52530. */
  52531. set: function (val) {
  52532. this._isVisibilityBoxLocked = val;
  52533. var boundingInfo = this.mesh.getBoundingInfo();
  52534. boundingInfo.isLocked = val;
  52535. },
  52536. enumerable: true,
  52537. configurable: true
  52538. });
  52539. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleRotation", {
  52540. /**
  52541. * Gets if `setParticles()` computes the particle rotations or not.
  52542. * Default value : true. The SPS is faster when it's set to false.
  52543. * Note : the particle rotations aren't stored values, so setting `computeParticleRotation` to false will prevents the particle to rotate.
  52544. */
  52545. get: function () {
  52546. return this._computeParticleRotation;
  52547. },
  52548. /**
  52549. * Tells to `setParticles()` to compute the particle rotations or not.
  52550. * Default value : true. The SPS is faster when it's set to false.
  52551. * Note : the particle rotations aren't stored values, so setting `computeParticleRotation` to false will prevents the particle to rotate.
  52552. */
  52553. set: function (val) {
  52554. this._computeParticleRotation = val;
  52555. },
  52556. enumerable: true,
  52557. configurable: true
  52558. });
  52559. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleColor", {
  52560. /**
  52561. * Gets if `setParticles()` computes the particle colors or not.
  52562. * Default value : true. The SPS is faster when it's set to false.
  52563. * Note : the particle colors are stored values, so setting `computeParticleColor` to false will keep yet the last colors set.
  52564. */
  52565. get: function () {
  52566. return this._computeParticleColor;
  52567. },
  52568. /**
  52569. * Tells to `setParticles()` to compute the particle colors or not.
  52570. * Default value : true. The SPS is faster when it's set to false.
  52571. * Note : the particle colors are stored values, so setting `computeParticleColor` to false will keep yet the last colors set.
  52572. */
  52573. set: function (val) {
  52574. this._computeParticleColor = val;
  52575. },
  52576. enumerable: true,
  52577. configurable: true
  52578. });
  52579. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleTexture", {
  52580. /**
  52581. * Gets if `setParticles()` computes the particle textures or not.
  52582. * Default value : true. The SPS is faster when it's set to false.
  52583. * Note : the particle textures are stored values, so setting `computeParticleTexture` to false will keep yet the last colors set.
  52584. */
  52585. get: function () {
  52586. return this._computeParticleTexture;
  52587. },
  52588. set: function (val) {
  52589. this._computeParticleTexture = val;
  52590. },
  52591. enumerable: true,
  52592. configurable: true
  52593. });
  52594. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleVertex", {
  52595. /**
  52596. * Gets if `setParticles()` calls the vertex function for each vertex of each particle, or not.
  52597. * Default value : false. The SPS is faster when it's set to false.
  52598. * Note : the particle custom vertex positions aren't stored values.
  52599. */
  52600. get: function () {
  52601. return this._computeParticleVertex;
  52602. },
  52603. /**
  52604. * Tells to `setParticles()` to call the vertex function for each vertex of each particle, or not.
  52605. * Default value : false. The SPS is faster when it's set to false.
  52606. * Note : the particle custom vertex positions aren't stored values.
  52607. */
  52608. set: function (val) {
  52609. this._computeParticleVertex = val;
  52610. },
  52611. enumerable: true,
  52612. configurable: true
  52613. });
  52614. Object.defineProperty(SolidParticleSystem.prototype, "computeBoundingBox", {
  52615. /**
  52616. * Gets if `setParticles()` computes or not the mesh bounding box when computing the particle positions.
  52617. */
  52618. get: function () {
  52619. return this._computeBoundingBox;
  52620. },
  52621. /**
  52622. * Tells to `setParticles()` to compute or not the mesh bounding box when computing the particle positions.
  52623. */
  52624. set: function (val) {
  52625. this._computeBoundingBox = val;
  52626. },
  52627. enumerable: true,
  52628. configurable: true
  52629. });
  52630. Object.defineProperty(SolidParticleSystem.prototype, "depthSortParticles", {
  52631. /**
  52632. * Gets if `setParticles()` sorts or not the distance between each particle and the camera.
  52633. * Skipped when `enableDepthSort` is set to `false` (default) at construction time.
  52634. * Default : `true`
  52635. */
  52636. get: function () {
  52637. return this._depthSortParticles;
  52638. },
  52639. /**
  52640. * Tells to `setParticles()` to sort or not the distance between each particle and the camera.
  52641. * Skipped when `enableDepthSort` is set to `false` (default) at construction time.
  52642. * Default : `true`
  52643. */
  52644. set: function (val) {
  52645. this._depthSortParticles = val;
  52646. },
  52647. enumerable: true,
  52648. configurable: true
  52649. });
  52650. // =======================================================================
  52651. // Particle behavior logic
  52652. // these following methods may be overwritten by the user to fit his needs
  52653. /**
  52654. * This function does nothing. It may be overwritten to set all the particle first values.
  52655. * The SPS doesn't call this function, you may have to call it by your own.
  52656. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  52657. */
  52658. SolidParticleSystem.prototype.initParticles = function () {
  52659. };
  52660. /**
  52661. * This function does nothing. It may be overwritten to recycle a particle.
  52662. * The SPS doesn't call this function, you may have to call it by your own.
  52663. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  52664. * @param particle The particle to recycle
  52665. * @returns the recycled particle
  52666. */
  52667. SolidParticleSystem.prototype.recycleParticle = function (particle) {
  52668. return particle;
  52669. };
  52670. /**
  52671. * Updates a particle : this function should be overwritten by the user.
  52672. * It is called on each particle by `setParticles()`. This is the place to code each particle behavior.
  52673. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  52674. * @example : just set a particle position or velocity and recycle conditions
  52675. * @param particle The particle to update
  52676. * @returns the updated particle
  52677. */
  52678. SolidParticleSystem.prototype.updateParticle = function (particle) {
  52679. return particle;
  52680. };
  52681. /**
  52682. * Updates a vertex of a particle : it can be overwritten by the user.
  52683. * This will be called on each vertex particle by `setParticles()` if `computeParticleVertex` is set to true only.
  52684. * @param particle the current particle
  52685. * @param vertex the current index of the current particle
  52686. * @param pt the index of the current vertex in the particle shape
  52687. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#update-each-particle-shape
  52688. * @example : just set a vertex particle position
  52689. * @returns the updated vertex
  52690. */
  52691. SolidParticleSystem.prototype.updateParticleVertex = function (particle, vertex, pt) {
  52692. return vertex;
  52693. };
  52694. /**
  52695. * This will be called before any other treatment by `setParticles()` and will be passed three parameters.
  52696. * This does nothing and may be overwritten by the user.
  52697. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  52698. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  52699. * @param update the boolean update value actually passed to setParticles()
  52700. */
  52701. SolidParticleSystem.prototype.beforeUpdateParticles = function (start, stop, update) {
  52702. };
  52703. /**
  52704. * This will be called by `setParticles()` after all the other treatments and just before the actual mesh update.
  52705. * This will be passed three parameters.
  52706. * This does nothing and may be overwritten by the user.
  52707. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  52708. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  52709. * @param update the boolean update value actually passed to setParticles()
  52710. */
  52711. SolidParticleSystem.prototype.afterUpdateParticles = function (start, stop, update) {
  52712. };
  52713. return SolidParticleSystem;
  52714. }());
  52715. BABYLON.SolidParticleSystem = SolidParticleSystem;
  52716. })(BABYLON || (BABYLON = {}));
  52717. //# sourceMappingURL=babylon.solidParticleSystem.js.map
  52718. var BABYLON;
  52719. (function (BABYLON) {
  52720. var ShaderMaterial = /** @class */ (function (_super) {
  52721. __extends(ShaderMaterial, _super);
  52722. function ShaderMaterial(name, scene, shaderPath, options) {
  52723. var _this = _super.call(this, name, scene) || this;
  52724. _this._textures = {};
  52725. _this._textureArrays = {};
  52726. _this._floats = {};
  52727. _this._ints = {};
  52728. _this._floatsArrays = {};
  52729. _this._colors3 = {};
  52730. _this._colors3Arrays = {};
  52731. _this._colors4 = {};
  52732. _this._vectors2 = {};
  52733. _this._vectors3 = {};
  52734. _this._vectors4 = {};
  52735. _this._matrices = {};
  52736. _this._matrices3x3 = {};
  52737. _this._matrices2x2 = {};
  52738. _this._vectors2Arrays = {};
  52739. _this._vectors3Arrays = {};
  52740. _this._cachedWorldViewMatrix = new BABYLON.Matrix();
  52741. _this._shaderPath = shaderPath;
  52742. options.needAlphaBlending = options.needAlphaBlending || false;
  52743. options.needAlphaTesting = options.needAlphaTesting || false;
  52744. options.attributes = options.attributes || ["position", "normal", "uv"];
  52745. options.uniforms = options.uniforms || ["worldViewProjection"];
  52746. options.uniformBuffers = options.uniformBuffers || [];
  52747. options.samplers = options.samplers || [];
  52748. options.defines = options.defines || [];
  52749. _this._options = options;
  52750. return _this;
  52751. }
  52752. ShaderMaterial.prototype.getClassName = function () {
  52753. return "ShaderMaterial";
  52754. };
  52755. ShaderMaterial.prototype.needAlphaBlending = function () {
  52756. return this._options.needAlphaBlending;
  52757. };
  52758. ShaderMaterial.prototype.needAlphaTesting = function () {
  52759. return this._options.needAlphaTesting;
  52760. };
  52761. ShaderMaterial.prototype._checkUniform = function (uniformName) {
  52762. if (this._options.uniforms.indexOf(uniformName) === -1) {
  52763. this._options.uniforms.push(uniformName);
  52764. }
  52765. };
  52766. ShaderMaterial.prototype.setTexture = function (name, texture) {
  52767. if (this._options.samplers.indexOf(name) === -1) {
  52768. this._options.samplers.push(name);
  52769. }
  52770. this._textures[name] = texture;
  52771. return this;
  52772. };
  52773. ShaderMaterial.prototype.setTextureArray = function (name, textures) {
  52774. if (this._options.samplers.indexOf(name) === -1) {
  52775. this._options.samplers.push(name);
  52776. }
  52777. this._checkUniform(name);
  52778. this._textureArrays[name] = textures;
  52779. return this;
  52780. };
  52781. ShaderMaterial.prototype.setFloat = function (name, value) {
  52782. this._checkUniform(name);
  52783. this._floats[name] = value;
  52784. return this;
  52785. };
  52786. ShaderMaterial.prototype.setInt = function (name, value) {
  52787. this._checkUniform(name);
  52788. this._ints[name] = value;
  52789. return this;
  52790. };
  52791. ShaderMaterial.prototype.setFloats = function (name, value) {
  52792. this._checkUniform(name);
  52793. this._floatsArrays[name] = value;
  52794. return this;
  52795. };
  52796. ShaderMaterial.prototype.setColor3 = function (name, value) {
  52797. this._checkUniform(name);
  52798. this._colors3[name] = value;
  52799. return this;
  52800. };
  52801. ShaderMaterial.prototype.setColor3Array = function (name, value) {
  52802. this._checkUniform(name);
  52803. this._colors3Arrays[name] = value.reduce(function (arr, color) {
  52804. color.toArray(arr, arr.length);
  52805. return arr;
  52806. }, []);
  52807. return this;
  52808. };
  52809. ShaderMaterial.prototype.setColor4 = function (name, value) {
  52810. this._checkUniform(name);
  52811. this._colors4[name] = value;
  52812. return this;
  52813. };
  52814. ShaderMaterial.prototype.setVector2 = function (name, value) {
  52815. this._checkUniform(name);
  52816. this._vectors2[name] = value;
  52817. return this;
  52818. };
  52819. ShaderMaterial.prototype.setVector3 = function (name, value) {
  52820. this._checkUniform(name);
  52821. this._vectors3[name] = value;
  52822. return this;
  52823. };
  52824. ShaderMaterial.prototype.setVector4 = function (name, value) {
  52825. this._checkUniform(name);
  52826. this._vectors4[name] = value;
  52827. return this;
  52828. };
  52829. ShaderMaterial.prototype.setMatrix = function (name, value) {
  52830. this._checkUniform(name);
  52831. this._matrices[name] = value;
  52832. return this;
  52833. };
  52834. ShaderMaterial.prototype.setMatrix3x3 = function (name, value) {
  52835. this._checkUniform(name);
  52836. this._matrices3x3[name] = value;
  52837. return this;
  52838. };
  52839. ShaderMaterial.prototype.setMatrix2x2 = function (name, value) {
  52840. this._checkUniform(name);
  52841. this._matrices2x2[name] = value;
  52842. return this;
  52843. };
  52844. ShaderMaterial.prototype.setArray2 = function (name, value) {
  52845. this._checkUniform(name);
  52846. this._vectors2Arrays[name] = value;
  52847. return this;
  52848. };
  52849. ShaderMaterial.prototype.setArray3 = function (name, value) {
  52850. this._checkUniform(name);
  52851. this._vectors3Arrays[name] = value;
  52852. return this;
  52853. };
  52854. ShaderMaterial.prototype._checkCache = function (scene, mesh, useInstances) {
  52855. if (!mesh) {
  52856. return true;
  52857. }
  52858. if (this._effect && (this._effect.defines.indexOf("#define INSTANCES") !== -1) !== useInstances) {
  52859. return false;
  52860. }
  52861. return false;
  52862. };
  52863. ShaderMaterial.prototype.isReady = function (mesh, useInstances) {
  52864. var scene = this.getScene();
  52865. var engine = scene.getEngine();
  52866. if (!this.checkReadyOnEveryCall) {
  52867. if (this._renderId === scene.getRenderId()) {
  52868. if (this._checkCache(scene, mesh, useInstances)) {
  52869. return true;
  52870. }
  52871. }
  52872. }
  52873. // Instances
  52874. var defines = [];
  52875. var attribs = [];
  52876. var fallbacks = new BABYLON.EffectFallbacks();
  52877. if (useInstances) {
  52878. defines.push("#define INSTANCES");
  52879. }
  52880. for (var index = 0; index < this._options.defines.length; index++) {
  52881. defines.push(this._options.defines[index]);
  52882. }
  52883. for (var index = 0; index < this._options.attributes.length; index++) {
  52884. attribs.push(this._options.attributes[index]);
  52885. }
  52886. if (mesh && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  52887. attribs.push(BABYLON.VertexBuffer.ColorKind);
  52888. defines.push("#define VERTEXCOLOR");
  52889. }
  52890. // Bones
  52891. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  52892. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  52893. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  52894. if (mesh.numBoneInfluencers > 4) {
  52895. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  52896. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  52897. }
  52898. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  52899. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  52900. fallbacks.addCPUSkinningFallback(0, mesh);
  52901. if (this._options.uniforms.indexOf("mBones") === -1) {
  52902. this._options.uniforms.push("mBones");
  52903. }
  52904. }
  52905. else {
  52906. defines.push("#define NUM_BONE_INFLUENCERS 0");
  52907. }
  52908. // Textures
  52909. for (var name in this._textures) {
  52910. if (!this._textures[name].isReady()) {
  52911. return false;
  52912. }
  52913. }
  52914. // Alpha test
  52915. if (mesh && this._shouldTurnAlphaTestOn(mesh)) {
  52916. defines.push("#define ALPHATEST");
  52917. }
  52918. var previousEffect = this._effect;
  52919. var join = defines.join("\n");
  52920. this._effect = engine.createEffect(this._shaderPath, {
  52921. attributes: attribs,
  52922. uniformsNames: this._options.uniforms,
  52923. uniformBuffersNames: this._options.uniformBuffers,
  52924. samplers: this._options.samplers,
  52925. defines: join,
  52926. fallbacks: fallbacks,
  52927. onCompiled: this.onCompiled,
  52928. onError: this.onError
  52929. }, engine);
  52930. if (!this._effect.isReady()) {
  52931. return false;
  52932. }
  52933. if (previousEffect !== this._effect) {
  52934. scene.resetCachedMaterial();
  52935. }
  52936. this._renderId = scene.getRenderId();
  52937. return true;
  52938. };
  52939. ShaderMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  52940. var scene = this.getScene();
  52941. if (!this._effect) {
  52942. return;
  52943. }
  52944. if (this._options.uniforms.indexOf("world") !== -1) {
  52945. this._effect.setMatrix("world", world);
  52946. }
  52947. if (this._options.uniforms.indexOf("worldView") !== -1) {
  52948. world.multiplyToRef(scene.getViewMatrix(), this._cachedWorldViewMatrix);
  52949. this._effect.setMatrix("worldView", this._cachedWorldViewMatrix);
  52950. }
  52951. if (this._options.uniforms.indexOf("worldViewProjection") !== -1) {
  52952. this._effect.setMatrix("worldViewProjection", world.multiply(scene.getTransformMatrix()));
  52953. }
  52954. };
  52955. ShaderMaterial.prototype.bind = function (world, mesh) {
  52956. // Std values
  52957. this.bindOnlyWorldMatrix(world);
  52958. if (this._effect && this.getScene().getCachedMaterial() !== this) {
  52959. if (this._options.uniforms.indexOf("view") !== -1) {
  52960. this._effect.setMatrix("view", this.getScene().getViewMatrix());
  52961. }
  52962. if (this._options.uniforms.indexOf("projection") !== -1) {
  52963. this._effect.setMatrix("projection", this.getScene().getProjectionMatrix());
  52964. }
  52965. if (this._options.uniforms.indexOf("viewProjection") !== -1) {
  52966. this._effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  52967. }
  52968. // Bones
  52969. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._effect);
  52970. var name;
  52971. // Texture
  52972. for (name in this._textures) {
  52973. this._effect.setTexture(name, this._textures[name]);
  52974. }
  52975. // Texture arrays
  52976. for (name in this._textureArrays) {
  52977. this._effect.setTextureArray(name, this._textureArrays[name]);
  52978. }
  52979. // Int
  52980. for (name in this._ints) {
  52981. this._effect.setInt(name, this._ints[name]);
  52982. }
  52983. // Float
  52984. for (name in this._floats) {
  52985. this._effect.setFloat(name, this._floats[name]);
  52986. }
  52987. // Floats
  52988. for (name in this._floatsArrays) {
  52989. this._effect.setArray(name, this._floatsArrays[name]);
  52990. }
  52991. // Color3
  52992. for (name in this._colors3) {
  52993. this._effect.setColor3(name, this._colors3[name]);
  52994. }
  52995. for (name in this._colors3Arrays) {
  52996. this._effect.setArray3(name, this._colors3Arrays[name]);
  52997. }
  52998. // Color4
  52999. for (name in this._colors4) {
  53000. var color = this._colors4[name];
  53001. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  53002. }
  53003. // Vector2
  53004. for (name in this._vectors2) {
  53005. this._effect.setVector2(name, this._vectors2[name]);
  53006. }
  53007. // Vector3
  53008. for (name in this._vectors3) {
  53009. this._effect.setVector3(name, this._vectors3[name]);
  53010. }
  53011. // Vector4
  53012. for (name in this._vectors4) {
  53013. this._effect.setVector4(name, this._vectors4[name]);
  53014. }
  53015. // Matrix
  53016. for (name in this._matrices) {
  53017. this._effect.setMatrix(name, this._matrices[name]);
  53018. }
  53019. // Matrix 3x3
  53020. for (name in this._matrices3x3) {
  53021. this._effect.setMatrix3x3(name, this._matrices3x3[name]);
  53022. }
  53023. // Matrix 2x2
  53024. for (name in this._matrices2x2) {
  53025. this._effect.setMatrix2x2(name, this._matrices2x2[name]);
  53026. }
  53027. // Vector2Array
  53028. for (name in this._vectors2Arrays) {
  53029. this._effect.setArray2(name, this._vectors2Arrays[name]);
  53030. }
  53031. // Vector3Array
  53032. for (name in this._vectors3Arrays) {
  53033. this._effect.setArray3(name, this._vectors3Arrays[name]);
  53034. }
  53035. }
  53036. this._afterBind(mesh);
  53037. };
  53038. ShaderMaterial.prototype.getActiveTextures = function () {
  53039. var activeTextures = _super.prototype.getActiveTextures.call(this);
  53040. for (var name in this._textures) {
  53041. activeTextures.push(this._textures[name]);
  53042. }
  53043. for (var name in this._textureArrays) {
  53044. var array = this._textureArrays[name];
  53045. for (var index = 0; index < array.length; index++) {
  53046. activeTextures.push(array[index]);
  53047. }
  53048. }
  53049. return activeTextures;
  53050. };
  53051. ShaderMaterial.prototype.hasTexture = function (texture) {
  53052. if (_super.prototype.hasTexture.call(this, texture)) {
  53053. return true;
  53054. }
  53055. for (var name in this._textures) {
  53056. if (this._textures[name] === texture) {
  53057. return true;
  53058. }
  53059. }
  53060. for (var name in this._textureArrays) {
  53061. var array = this._textureArrays[name];
  53062. for (var index = 0; index < array.length; index++) {
  53063. if (array[index] === texture) {
  53064. return true;
  53065. }
  53066. }
  53067. }
  53068. return false;
  53069. };
  53070. ShaderMaterial.prototype.clone = function (name) {
  53071. var newShaderMaterial = new ShaderMaterial(name, this.getScene(), this._shaderPath, this._options);
  53072. return newShaderMaterial;
  53073. };
  53074. ShaderMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  53075. if (forceDisposeTextures) {
  53076. var name;
  53077. for (name in this._textures) {
  53078. this._textures[name].dispose();
  53079. }
  53080. for (name in this._textureArrays) {
  53081. var array = this._textureArrays[name];
  53082. for (var index = 0; index < array.length; index++) {
  53083. array[index].dispose();
  53084. }
  53085. }
  53086. }
  53087. this._textures = {};
  53088. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  53089. };
  53090. ShaderMaterial.prototype.serialize = function () {
  53091. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  53092. serializationObject.customType = "BABYLON.ShaderMaterial";
  53093. serializationObject.options = this._options;
  53094. serializationObject.shaderPath = this._shaderPath;
  53095. var name;
  53096. // Texture
  53097. serializationObject.textures = {};
  53098. for (name in this._textures) {
  53099. serializationObject.textures[name] = this._textures[name].serialize();
  53100. }
  53101. // Texture arrays
  53102. serializationObject.textureArrays = {};
  53103. for (name in this._textureArrays) {
  53104. serializationObject.textureArrays[name] = [];
  53105. var array = this._textureArrays[name];
  53106. for (var index = 0; index < array.length; index++) {
  53107. serializationObject.textureArrays[name].push(array[index].serialize());
  53108. }
  53109. }
  53110. // Float
  53111. serializationObject.floats = {};
  53112. for (name in this._floats) {
  53113. serializationObject.floats[name] = this._floats[name];
  53114. }
  53115. // Float s
  53116. serializationObject.FloatArrays = {};
  53117. for (name in this._floatsArrays) {
  53118. serializationObject.FloatArrays[name] = this._floatsArrays[name];
  53119. }
  53120. // Color3
  53121. serializationObject.colors3 = {};
  53122. for (name in this._colors3) {
  53123. serializationObject.colors3[name] = this._colors3[name].asArray();
  53124. }
  53125. // Color3 array
  53126. serializationObject.colors3Arrays = {};
  53127. for (name in this._colors3Arrays) {
  53128. serializationObject.colors3Arrays[name] = this._colors3Arrays[name];
  53129. }
  53130. // Color4
  53131. serializationObject.colors4 = {};
  53132. for (name in this._colors4) {
  53133. serializationObject.colors4[name] = this._colors4[name].asArray();
  53134. }
  53135. // Vector2
  53136. serializationObject.vectors2 = {};
  53137. for (name in this._vectors2) {
  53138. serializationObject.vectors2[name] = this._vectors2[name].asArray();
  53139. }
  53140. // Vector3
  53141. serializationObject.vectors3 = {};
  53142. for (name in this._vectors3) {
  53143. serializationObject.vectors3[name] = this._vectors3[name].asArray();
  53144. }
  53145. // Vector4
  53146. serializationObject.vectors4 = {};
  53147. for (name in this._vectors4) {
  53148. serializationObject.vectors4[name] = this._vectors4[name].asArray();
  53149. }
  53150. // Matrix
  53151. serializationObject.matrices = {};
  53152. for (name in this._matrices) {
  53153. serializationObject.matrices[name] = this._matrices[name].asArray();
  53154. }
  53155. // Matrix 3x3
  53156. serializationObject.matrices3x3 = {};
  53157. for (name in this._matrices3x3) {
  53158. serializationObject.matrices3x3[name] = this._matrices3x3[name];
  53159. }
  53160. // Matrix 2x2
  53161. serializationObject.matrices2x2 = {};
  53162. for (name in this._matrices2x2) {
  53163. serializationObject.matrices2x2[name] = this._matrices2x2[name];
  53164. }
  53165. // Vector2Array
  53166. serializationObject.vectors2Arrays = {};
  53167. for (name in this._vectors2Arrays) {
  53168. serializationObject.vectors2Arrays[name] = this._vectors2Arrays[name];
  53169. }
  53170. // Vector3Array
  53171. serializationObject.vectors3Arrays = {};
  53172. for (name in this._vectors3Arrays) {
  53173. serializationObject.vectors3Arrays[name] = this._vectors3Arrays[name];
  53174. }
  53175. return serializationObject;
  53176. };
  53177. ShaderMaterial.Parse = function (source, scene, rootUrl) {
  53178. var material = BABYLON.SerializationHelper.Parse(function () { return new ShaderMaterial(source.name, scene, source.shaderPath, source.options); }, source, scene, rootUrl);
  53179. var name;
  53180. // Texture
  53181. for (name in source.textures) {
  53182. material.setTexture(name, BABYLON.Texture.Parse(source.textures[name], scene, rootUrl));
  53183. }
  53184. // Texture arrays
  53185. for (name in source.textureArrays) {
  53186. var array = source.textureArrays[name];
  53187. var textureArray = new Array();
  53188. for (var index = 0; index < array.length; index++) {
  53189. textureArray.push(BABYLON.Texture.Parse(array[index], scene, rootUrl));
  53190. }
  53191. material.setTextureArray(name, textureArray);
  53192. }
  53193. // Float
  53194. for (name in source.floats) {
  53195. material.setFloat(name, source.floats[name]);
  53196. }
  53197. // Float s
  53198. for (name in source.floatsArrays) {
  53199. material.setFloats(name, source.floatsArrays[name]);
  53200. }
  53201. // Color3
  53202. for (name in source.colors3) {
  53203. material.setColor3(name, BABYLON.Color3.FromArray(source.colors3[name]));
  53204. }
  53205. // Color3 arrays
  53206. for (name in source.colors3Arrays) {
  53207. var colors = source.colors3Arrays[name].reduce(function (arr, num, i) {
  53208. if (i % 3 === 0) {
  53209. arr.push([num]);
  53210. }
  53211. else {
  53212. arr[arr.length - 1].push(num);
  53213. }
  53214. return arr;
  53215. }, []).map(function (color) { return BABYLON.Color3.FromArray(color); });
  53216. material.setColor3Array(name, colors);
  53217. }
  53218. // Color4
  53219. for (name in source.colors4) {
  53220. material.setColor4(name, BABYLON.Color4.FromArray(source.colors4[name]));
  53221. }
  53222. // Vector2
  53223. for (name in source.vectors2) {
  53224. material.setVector2(name, BABYLON.Vector2.FromArray(source.vectors2[name]));
  53225. }
  53226. // Vector3
  53227. for (name in source.vectors3) {
  53228. material.setVector3(name, BABYLON.Vector3.FromArray(source.vectors3[name]));
  53229. }
  53230. // Vector4
  53231. for (name in source.vectors4) {
  53232. material.setVector4(name, BABYLON.Vector4.FromArray(source.vectors4[name]));
  53233. }
  53234. // Matrix
  53235. for (name in source.matrices) {
  53236. material.setMatrix(name, BABYLON.Matrix.FromArray(source.matrices[name]));
  53237. }
  53238. // Matrix 3x3
  53239. for (name in source.matrices3x3) {
  53240. material.setMatrix3x3(name, source.matrices3x3[name]);
  53241. }
  53242. // Matrix 2x2
  53243. for (name in source.matrices2x2) {
  53244. material.setMatrix2x2(name, source.matrices2x2[name]);
  53245. }
  53246. // Vector2Array
  53247. for (name in source.vectors2Arrays) {
  53248. material.setArray2(name, source.vectors2Arrays[name]);
  53249. }
  53250. // Vector3Array
  53251. for (name in source.vectors3Arrays) {
  53252. material.setArray3(name, source.vectors3Arrays[name]);
  53253. }
  53254. return material;
  53255. };
  53256. return ShaderMaterial;
  53257. }(BABYLON.Material));
  53258. BABYLON.ShaderMaterial = ShaderMaterial;
  53259. })(BABYLON || (BABYLON = {}));
  53260. //# sourceMappingURL=babylon.shaderMaterial.js.map
  53261. var BABYLON;
  53262. (function (BABYLON) {
  53263. var GroundMesh = /** @class */ (function (_super) {
  53264. __extends(GroundMesh, _super);
  53265. function GroundMesh(name, scene) {
  53266. var _this = _super.call(this, name, scene) || this;
  53267. _this.generateOctree = false;
  53268. return _this;
  53269. }
  53270. GroundMesh.prototype.getClassName = function () {
  53271. return "GroundMesh";
  53272. };
  53273. Object.defineProperty(GroundMesh.prototype, "subdivisions", {
  53274. get: function () {
  53275. return Math.min(this._subdivisionsX, this._subdivisionsY);
  53276. },
  53277. enumerable: true,
  53278. configurable: true
  53279. });
  53280. Object.defineProperty(GroundMesh.prototype, "subdivisionsX", {
  53281. get: function () {
  53282. return this._subdivisionsX;
  53283. },
  53284. enumerable: true,
  53285. configurable: true
  53286. });
  53287. Object.defineProperty(GroundMesh.prototype, "subdivisionsY", {
  53288. get: function () {
  53289. return this._subdivisionsY;
  53290. },
  53291. enumerable: true,
  53292. configurable: true
  53293. });
  53294. GroundMesh.prototype.optimize = function (chunksCount, octreeBlocksSize) {
  53295. if (octreeBlocksSize === void 0) { octreeBlocksSize = 32; }
  53296. this._subdivisionsX = chunksCount;
  53297. this._subdivisionsY = chunksCount;
  53298. this.subdivide(chunksCount);
  53299. this.createOrUpdateSubmeshesOctree(octreeBlocksSize);
  53300. };
  53301. /**
  53302. * Returns a height (y) value in the Worl system :
  53303. * the ground altitude at the coordinates (x, z) expressed in the World system.
  53304. * Returns the ground y position if (x, z) are outside the ground surface.
  53305. */
  53306. GroundMesh.prototype.getHeightAtCoordinates = function (x, z) {
  53307. var world = this.getWorldMatrix();
  53308. var invMat = BABYLON.Tmp.Matrix[5];
  53309. world.invertToRef(invMat);
  53310. var tmpVect = BABYLON.Tmp.Vector3[8];
  53311. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, 0.0, z, invMat, tmpVect); // transform x,z in the mesh local space
  53312. x = tmpVect.x;
  53313. z = tmpVect.z;
  53314. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  53315. return this.position.y;
  53316. }
  53317. if (!this._heightQuads || this._heightQuads.length == 0) {
  53318. this._initHeightQuads();
  53319. this._computeHeightQuads();
  53320. }
  53321. var facet = this._getFacetAt(x, z);
  53322. var y = -(facet.x * x + facet.z * z + facet.w) / facet.y;
  53323. // return y in the World system
  53324. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(0.0, y, 0.0, world, tmpVect);
  53325. return tmpVect.y;
  53326. };
  53327. /**
  53328. * Returns a normalized vector (Vector3) orthogonal to the ground
  53329. * at the ground coordinates (x, z) expressed in the World system.
  53330. * Returns Vector3(0.0, 1.0, 0.0) if (x, z) are outside the ground surface.
  53331. */
  53332. GroundMesh.prototype.getNormalAtCoordinates = function (x, z) {
  53333. var normal = new BABYLON.Vector3(0.0, 1.0, 0.0);
  53334. this.getNormalAtCoordinatesToRef(x, z, normal);
  53335. return normal;
  53336. };
  53337. /**
  53338. * Updates the Vector3 passed a reference with a normalized vector orthogonal to the ground
  53339. * at the ground coordinates (x, z) expressed in the World system.
  53340. * Doesn't uptade the reference Vector3 if (x, z) are outside the ground surface.
  53341. * Returns the GroundMesh.
  53342. */
  53343. GroundMesh.prototype.getNormalAtCoordinatesToRef = function (x, z, ref) {
  53344. var world = this.getWorldMatrix();
  53345. var tmpMat = BABYLON.Tmp.Matrix[5];
  53346. world.invertToRef(tmpMat);
  53347. var tmpVect = BABYLON.Tmp.Vector3[8];
  53348. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, 0.0, z, tmpMat, tmpVect); // transform x,z in the mesh local space
  53349. x = tmpVect.x;
  53350. z = tmpVect.z;
  53351. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  53352. return this;
  53353. }
  53354. if (!this._heightQuads || this._heightQuads.length == 0) {
  53355. this._initHeightQuads();
  53356. this._computeHeightQuads();
  53357. }
  53358. var facet = this._getFacetAt(x, z);
  53359. BABYLON.Vector3.TransformNormalFromFloatsToRef(facet.x, facet.y, facet.z, world, ref);
  53360. return this;
  53361. };
  53362. /**
  53363. * Force the heights to be recomputed for getHeightAtCoordinates() or getNormalAtCoordinates()
  53364. * if the ground has been updated.
  53365. * This can be used in the render loop.
  53366. * Returns the GroundMesh.
  53367. */
  53368. GroundMesh.prototype.updateCoordinateHeights = function () {
  53369. if (!this._heightQuads || this._heightQuads.length == 0) {
  53370. this._initHeightQuads();
  53371. }
  53372. this._computeHeightQuads();
  53373. return this;
  53374. };
  53375. // Returns the element "facet" from the heightQuads array relative to (x, z) local coordinates
  53376. GroundMesh.prototype._getFacetAt = function (x, z) {
  53377. // retrieve col and row from x, z coordinates in the ground local system
  53378. var col = Math.floor((x + this._maxX) * this._subdivisionsX / this._width);
  53379. var row = Math.floor(-(z + this._maxZ) * this._subdivisionsY / this._height + this._subdivisionsY);
  53380. var quad = this._heightQuads[row * this._subdivisionsX + col];
  53381. var facet;
  53382. if (z < quad.slope.x * x + quad.slope.y) {
  53383. facet = quad.facet1;
  53384. }
  53385. else {
  53386. facet = quad.facet2;
  53387. }
  53388. return facet;
  53389. };
  53390. // Creates and populates the heightMap array with "facet" elements :
  53391. // a quad is two triangular facets separated by a slope, so a "facet" element is 1 slope + 2 facets
  53392. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  53393. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  53394. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  53395. // Returns the GroundMesh.
  53396. GroundMesh.prototype._initHeightQuads = function () {
  53397. var subdivisionsX = this._subdivisionsX;
  53398. var subdivisionsY = this._subdivisionsY;
  53399. this._heightQuads = new Array();
  53400. for (var row = 0; row < subdivisionsY; row++) {
  53401. for (var col = 0; col < subdivisionsX; col++) {
  53402. 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) };
  53403. this._heightQuads[row * subdivisionsX + col] = quad;
  53404. }
  53405. }
  53406. return this;
  53407. };
  53408. // Compute each quad element values and update the the heightMap array :
  53409. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  53410. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  53411. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  53412. // Returns the GroundMesh.
  53413. GroundMesh.prototype._computeHeightQuads = function () {
  53414. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  53415. if (!positions) {
  53416. return this;
  53417. }
  53418. var v1 = BABYLON.Tmp.Vector3[3];
  53419. var v2 = BABYLON.Tmp.Vector3[2];
  53420. var v3 = BABYLON.Tmp.Vector3[1];
  53421. var v4 = BABYLON.Tmp.Vector3[0];
  53422. var v1v2 = BABYLON.Tmp.Vector3[4];
  53423. var v1v3 = BABYLON.Tmp.Vector3[5];
  53424. var v1v4 = BABYLON.Tmp.Vector3[6];
  53425. var norm1 = BABYLON.Tmp.Vector3[7];
  53426. var norm2 = BABYLON.Tmp.Vector3[8];
  53427. var i = 0;
  53428. var j = 0;
  53429. var k = 0;
  53430. var cd = 0; // 2D slope coefficient : z = cd * x + h
  53431. var h = 0;
  53432. var d1 = 0; // facet plane equation : ax + by + cz + d = 0
  53433. var d2 = 0;
  53434. var subdivisionsX = this._subdivisionsX;
  53435. var subdivisionsY = this._subdivisionsY;
  53436. for (var row = 0; row < subdivisionsY; row++) {
  53437. for (var col = 0; col < subdivisionsX; col++) {
  53438. i = col * 3;
  53439. j = row * (subdivisionsX + 1) * 3;
  53440. k = (row + 1) * (subdivisionsX + 1) * 3;
  53441. v1.x = positions[j + i];
  53442. v1.y = positions[j + i + 1];
  53443. v1.z = positions[j + i + 2];
  53444. v2.x = positions[j + i + 3];
  53445. v2.y = positions[j + i + 4];
  53446. v2.z = positions[j + i + 5];
  53447. v3.x = positions[k + i];
  53448. v3.y = positions[k + i + 1];
  53449. v3.z = positions[k + i + 2];
  53450. v4.x = positions[k + i + 3];
  53451. v4.y = positions[k + i + 4];
  53452. v4.z = positions[k + i + 5];
  53453. // 2D slope V1V4
  53454. cd = (v4.z - v1.z) / (v4.x - v1.x);
  53455. h = v1.z - cd * v1.x; // v1 belongs to the slope
  53456. // facet equations :
  53457. // we compute each facet normal vector
  53458. // the equation of the facet plane is : norm.x * x + norm.y * y + norm.z * z + d = 0
  53459. // we compute the value d by applying the equation to v1 which belongs to the plane
  53460. // then we store the facet equation in a Vector4
  53461. v2.subtractToRef(v1, v1v2);
  53462. v3.subtractToRef(v1, v1v3);
  53463. v4.subtractToRef(v1, v1v4);
  53464. BABYLON.Vector3.CrossToRef(v1v4, v1v3, norm1); // caution : CrossToRef uses the Tmp class
  53465. BABYLON.Vector3.CrossToRef(v1v2, v1v4, norm2);
  53466. norm1.normalize();
  53467. norm2.normalize();
  53468. d1 = -(norm1.x * v1.x + norm1.y * v1.y + norm1.z * v1.z);
  53469. d2 = -(norm2.x * v2.x + norm2.y * v2.y + norm2.z * v2.z);
  53470. var quad = this._heightQuads[row * subdivisionsX + col];
  53471. quad.slope.copyFromFloats(cd, h);
  53472. quad.facet1.copyFromFloats(norm1.x, norm1.y, norm1.z, d1);
  53473. quad.facet2.copyFromFloats(norm2.x, norm2.y, norm2.z, d2);
  53474. }
  53475. }
  53476. return this;
  53477. };
  53478. GroundMesh.prototype.serialize = function (serializationObject) {
  53479. _super.prototype.serialize.call(this, serializationObject);
  53480. serializationObject.subdivisionsX = this._subdivisionsX;
  53481. serializationObject.subdivisionsY = this._subdivisionsY;
  53482. serializationObject.minX = this._minX;
  53483. serializationObject.maxX = this._maxX;
  53484. serializationObject.minZ = this._minZ;
  53485. serializationObject.maxZ = this._maxZ;
  53486. serializationObject.width = this._width;
  53487. serializationObject.height = this._height;
  53488. };
  53489. GroundMesh.Parse = function (parsedMesh, scene) {
  53490. var result = new GroundMesh(parsedMesh.name, scene);
  53491. result._subdivisionsX = parsedMesh.subdivisionsX || 1;
  53492. result._subdivisionsY = parsedMesh.subdivisionsY || 1;
  53493. result._minX = parsedMesh.minX;
  53494. result._maxX = parsedMesh.maxX;
  53495. result._minZ = parsedMesh.minZ;
  53496. result._maxZ = parsedMesh.maxZ;
  53497. result._width = parsedMesh.width;
  53498. result._height = parsedMesh.height;
  53499. return result;
  53500. };
  53501. return GroundMesh;
  53502. }(BABYLON.Mesh));
  53503. BABYLON.GroundMesh = GroundMesh;
  53504. })(BABYLON || (BABYLON = {}));
  53505. //# sourceMappingURL=babylon.groundMesh.js.map
  53506. var BABYLON;
  53507. (function (BABYLON) {
  53508. /**
  53509. * Creates an instance based on a source mesh.
  53510. */
  53511. var InstancedMesh = /** @class */ (function (_super) {
  53512. __extends(InstancedMesh, _super);
  53513. function InstancedMesh(name, source) {
  53514. var _this = _super.call(this, name, source.getScene()) || this;
  53515. source.instances.push(_this);
  53516. _this._sourceMesh = source;
  53517. _this.position.copyFrom(source.position);
  53518. _this.rotation.copyFrom(source.rotation);
  53519. _this.scaling.copyFrom(source.scaling);
  53520. if (source.rotationQuaternion) {
  53521. _this.rotationQuaternion = source.rotationQuaternion.clone();
  53522. }
  53523. _this.infiniteDistance = source.infiniteDistance;
  53524. _this.setPivotMatrix(source.getPivotMatrix());
  53525. _this.refreshBoundingInfo();
  53526. _this._syncSubMeshes();
  53527. return _this;
  53528. }
  53529. /**
  53530. * Returns the string "InstancedMesh".
  53531. */
  53532. InstancedMesh.prototype.getClassName = function () {
  53533. return "InstancedMesh";
  53534. };
  53535. Object.defineProperty(InstancedMesh.prototype, "receiveShadows", {
  53536. // Methods
  53537. get: function () {
  53538. return this._sourceMesh.receiveShadows;
  53539. },
  53540. enumerable: true,
  53541. configurable: true
  53542. });
  53543. Object.defineProperty(InstancedMesh.prototype, "material", {
  53544. get: function () {
  53545. return this._sourceMesh.material;
  53546. },
  53547. enumerable: true,
  53548. configurable: true
  53549. });
  53550. Object.defineProperty(InstancedMesh.prototype, "visibility", {
  53551. get: function () {
  53552. return this._sourceMesh.visibility;
  53553. },
  53554. enumerable: true,
  53555. configurable: true
  53556. });
  53557. Object.defineProperty(InstancedMesh.prototype, "skeleton", {
  53558. get: function () {
  53559. return this._sourceMesh.skeleton;
  53560. },
  53561. enumerable: true,
  53562. configurable: true
  53563. });
  53564. Object.defineProperty(InstancedMesh.prototype, "renderingGroupId", {
  53565. get: function () {
  53566. return this._sourceMesh.renderingGroupId;
  53567. },
  53568. enumerable: true,
  53569. configurable: true
  53570. });
  53571. /**
  53572. * Returns the total number of vertices (integer).
  53573. */
  53574. InstancedMesh.prototype.getTotalVertices = function () {
  53575. return this._sourceMesh.getTotalVertices();
  53576. };
  53577. Object.defineProperty(InstancedMesh.prototype, "sourceMesh", {
  53578. get: function () {
  53579. return this._sourceMesh;
  53580. },
  53581. enumerable: true,
  53582. configurable: true
  53583. });
  53584. /**
  53585. * Is this node ready to be used/rendered
  53586. * @param completeCheck defines if a complete check (including materials and lights) has to be done (false by default)
  53587. * @return {boolean} is it ready
  53588. */
  53589. InstancedMesh.prototype.isReady = function (completeCheck) {
  53590. if (completeCheck === void 0) { completeCheck = false; }
  53591. return this._sourceMesh.isReady(completeCheck, true);
  53592. };
  53593. /**
  53594. * Returns a float array or a Float32Array of the requested kind of data : positons, normals, uvs, etc.
  53595. */
  53596. InstancedMesh.prototype.getVerticesData = function (kind, copyWhenShared) {
  53597. return this._sourceMesh.getVerticesData(kind, copyWhenShared);
  53598. };
  53599. /**
  53600. * Sets the vertex data of the mesh geometry for the requested `kind`.
  53601. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  53602. * The `data` are either a numeric array either a Float32Array.
  53603. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  53604. * 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).
  53605. * Note that a new underlying VertexBuffer object is created each call.
  53606. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  53607. *
  53608. * Possible `kind` values :
  53609. * - BABYLON.VertexBuffer.PositionKind
  53610. * - BABYLON.VertexBuffer.UVKind
  53611. * - BABYLON.VertexBuffer.UV2Kind
  53612. * - BABYLON.VertexBuffer.UV3Kind
  53613. * - BABYLON.VertexBuffer.UV4Kind
  53614. * - BABYLON.VertexBuffer.UV5Kind
  53615. * - BABYLON.VertexBuffer.UV6Kind
  53616. * - BABYLON.VertexBuffer.ColorKind
  53617. * - BABYLON.VertexBuffer.MatricesIndicesKind
  53618. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  53619. * - BABYLON.VertexBuffer.MatricesWeightsKind
  53620. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  53621. *
  53622. * Returns the Mesh.
  53623. */
  53624. InstancedMesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  53625. if (this.sourceMesh) {
  53626. this.sourceMesh.setVerticesData(kind, data, updatable, stride);
  53627. }
  53628. return this.sourceMesh;
  53629. };
  53630. /**
  53631. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  53632. * If the mesh has no geometry, it is simply returned as it is.
  53633. * The `data` are either a numeric array either a Float32Array.
  53634. * No new underlying VertexBuffer object is created.
  53635. * 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.
  53636. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  53637. *
  53638. * Possible `kind` values :
  53639. * - BABYLON.VertexBuffer.PositionKind
  53640. * - BABYLON.VertexBuffer.UVKind
  53641. * - BABYLON.VertexBuffer.UV2Kind
  53642. * - BABYLON.VertexBuffer.UV3Kind
  53643. * - BABYLON.VertexBuffer.UV4Kind
  53644. * - BABYLON.VertexBuffer.UV5Kind
  53645. * - BABYLON.VertexBuffer.UV6Kind
  53646. * - BABYLON.VertexBuffer.ColorKind
  53647. * - BABYLON.VertexBuffer.MatricesIndicesKind
  53648. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  53649. * - BABYLON.VertexBuffer.MatricesWeightsKind
  53650. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  53651. *
  53652. * Returns the Mesh.
  53653. */
  53654. InstancedMesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  53655. if (this.sourceMesh) {
  53656. this.sourceMesh.updateVerticesData(kind, data, updateExtends, makeItUnique);
  53657. }
  53658. return this.sourceMesh;
  53659. };
  53660. /**
  53661. * Sets the mesh indices.
  53662. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array).
  53663. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  53664. * This method creates a new index buffer each call.
  53665. * Returns the Mesh.
  53666. */
  53667. InstancedMesh.prototype.setIndices = function (indices, totalVertices) {
  53668. if (totalVertices === void 0) { totalVertices = null; }
  53669. if (this.sourceMesh) {
  53670. this.sourceMesh.setIndices(indices, totalVertices);
  53671. }
  53672. return this.sourceMesh;
  53673. };
  53674. /**
  53675. * Boolean : True if the mesh owns the requested kind of data.
  53676. */
  53677. InstancedMesh.prototype.isVerticesDataPresent = function (kind) {
  53678. return this._sourceMesh.isVerticesDataPresent(kind);
  53679. };
  53680. /**
  53681. * Returns an array of indices (IndicesArray).
  53682. */
  53683. InstancedMesh.prototype.getIndices = function () {
  53684. return this._sourceMesh.getIndices();
  53685. };
  53686. Object.defineProperty(InstancedMesh.prototype, "_positions", {
  53687. get: function () {
  53688. return this._sourceMesh._positions;
  53689. },
  53690. enumerable: true,
  53691. configurable: true
  53692. });
  53693. /**
  53694. * Sets a new updated BoundingInfo to the mesh.
  53695. * Returns the mesh.
  53696. */
  53697. InstancedMesh.prototype.refreshBoundingInfo = function () {
  53698. var meshBB = this._sourceMesh.getBoundingInfo();
  53699. this._boundingInfo = new BABYLON.BoundingInfo(meshBB.minimum.clone(), meshBB.maximum.clone());
  53700. this._updateBoundingInfo();
  53701. return this;
  53702. };
  53703. InstancedMesh.prototype._preActivate = function () {
  53704. if (this._currentLOD) {
  53705. this._currentLOD._preActivate();
  53706. }
  53707. return this;
  53708. };
  53709. InstancedMesh.prototype._activate = function (renderId) {
  53710. if (this._currentLOD) {
  53711. this._currentLOD._registerInstanceForRenderId(this, renderId);
  53712. }
  53713. return this;
  53714. };
  53715. /**
  53716. * Returns the current associated LOD AbstractMesh.
  53717. */
  53718. InstancedMesh.prototype.getLOD = function (camera) {
  53719. if (!camera) {
  53720. return this;
  53721. }
  53722. var boundingInfo = this.getBoundingInfo();
  53723. this._currentLOD = this.sourceMesh.getLOD(camera, boundingInfo.boundingSphere);
  53724. if (this._currentLOD === this.sourceMesh) {
  53725. return this;
  53726. }
  53727. return this._currentLOD;
  53728. };
  53729. InstancedMesh.prototype._syncSubMeshes = function () {
  53730. this.releaseSubMeshes();
  53731. if (this._sourceMesh.subMeshes) {
  53732. for (var index = 0; index < this._sourceMesh.subMeshes.length; index++) {
  53733. this._sourceMesh.subMeshes[index].clone(this, this._sourceMesh);
  53734. }
  53735. }
  53736. return this;
  53737. };
  53738. InstancedMesh.prototype._generatePointsArray = function () {
  53739. return this._sourceMesh._generatePointsArray();
  53740. };
  53741. /**
  53742. * Creates a new InstancedMesh from the current mesh.
  53743. * - name (string) : the cloned mesh name
  53744. * - newParent (optional Node) : the optional Node to parent the clone to.
  53745. * - doNotCloneChildren (optional boolean, default `false`) : if `true` the model children aren't cloned.
  53746. *
  53747. * Returns the clone.
  53748. */
  53749. InstancedMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  53750. var result = this._sourceMesh.createInstance(name);
  53751. // Deep copy
  53752. BABYLON.Tools.DeepCopy(this, result, ["name", "subMeshes", "uniqueId"], []);
  53753. // Bounding info
  53754. this.refreshBoundingInfo();
  53755. // Parent
  53756. if (newParent) {
  53757. result.parent = newParent;
  53758. }
  53759. if (!doNotCloneChildren) {
  53760. // Children
  53761. for (var index = 0; index < this.getScene().meshes.length; index++) {
  53762. var mesh = this.getScene().meshes[index];
  53763. if (mesh.parent === this) {
  53764. mesh.clone(mesh.name, result);
  53765. }
  53766. }
  53767. }
  53768. result.computeWorldMatrix(true);
  53769. return result;
  53770. };
  53771. /**
  53772. * Disposes the InstancedMesh.
  53773. * Returns nothing.
  53774. */
  53775. InstancedMesh.prototype.dispose = function (doNotRecurse) {
  53776. // Remove from mesh
  53777. var index = this._sourceMesh.instances.indexOf(this);
  53778. this._sourceMesh.instances.splice(index, 1);
  53779. _super.prototype.dispose.call(this, doNotRecurse);
  53780. };
  53781. return InstancedMesh;
  53782. }(BABYLON.AbstractMesh));
  53783. BABYLON.InstancedMesh = InstancedMesh;
  53784. })(BABYLON || (BABYLON = {}));
  53785. //# sourceMappingURL=babylon.instancedMesh.js.map
  53786. var BABYLON;
  53787. (function (BABYLON) {
  53788. var LinesMesh = /** @class */ (function (_super) {
  53789. __extends(LinesMesh, _super);
  53790. function LinesMesh(name, scene, parent, source, doNotCloneChildren, useVertexColor, useVertexAlpha) {
  53791. if (scene === void 0) { scene = null; }
  53792. if (parent === void 0) { parent = null; }
  53793. var _this = _super.call(this, name, scene, parent, source, doNotCloneChildren) || this;
  53794. _this.useVertexColor = useVertexColor;
  53795. _this.useVertexAlpha = useVertexAlpha;
  53796. _this.color = new BABYLON.Color3(1, 1, 1);
  53797. _this.alpha = 1;
  53798. if (source) {
  53799. _this.color = source.color.clone();
  53800. _this.alpha = source.alpha;
  53801. _this.useVertexColor = source.useVertexColor;
  53802. _this.useVertexAlpha = source.useVertexAlpha;
  53803. }
  53804. _this._intersectionThreshold = 0.1;
  53805. var defines = [];
  53806. var options = {
  53807. attributes: [BABYLON.VertexBuffer.PositionKind],
  53808. uniforms: ["world", "viewProjection"],
  53809. needAlphaBlending: true,
  53810. defines: defines
  53811. };
  53812. if (useVertexAlpha === false) {
  53813. options.needAlphaBlending = false;
  53814. }
  53815. if (!useVertexColor) {
  53816. options.uniforms.push("color");
  53817. }
  53818. else {
  53819. options.defines.push("#define VERTEXCOLOR");
  53820. options.attributes.push(BABYLON.VertexBuffer.ColorKind);
  53821. }
  53822. _this._colorShader = new BABYLON.ShaderMaterial("colorShader", _this.getScene(), "color", options);
  53823. return _this;
  53824. }
  53825. Object.defineProperty(LinesMesh.prototype, "intersectionThreshold", {
  53826. /**
  53827. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  53828. * This margin is expressed in world space coordinates, so its value may vary.
  53829. * Default value is 0.1
  53830. * @returns the intersection Threshold value.
  53831. */
  53832. get: function () {
  53833. return this._intersectionThreshold;
  53834. },
  53835. /**
  53836. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  53837. * This margin is expressed in world space coordinates, so its value may vary.
  53838. * @param value the new threshold to apply
  53839. */
  53840. set: function (value) {
  53841. if (this._intersectionThreshold === value) {
  53842. return;
  53843. }
  53844. this._intersectionThreshold = value;
  53845. if (this.geometry) {
  53846. this.geometry.boundingBias = new BABYLON.Vector2(0, value);
  53847. }
  53848. },
  53849. enumerable: true,
  53850. configurable: true
  53851. });
  53852. /**
  53853. * Returns the string "LineMesh"
  53854. */
  53855. LinesMesh.prototype.getClassName = function () {
  53856. return "LinesMesh";
  53857. };
  53858. Object.defineProperty(LinesMesh.prototype, "material", {
  53859. get: function () {
  53860. return this._colorShader;
  53861. },
  53862. set: function (value) {
  53863. // Do nothing
  53864. },
  53865. enumerable: true,
  53866. configurable: true
  53867. });
  53868. Object.defineProperty(LinesMesh.prototype, "checkCollisions", {
  53869. get: function () {
  53870. return false;
  53871. },
  53872. enumerable: true,
  53873. configurable: true
  53874. });
  53875. LinesMesh.prototype.createInstance = function (name) {
  53876. throw new Error("LinesMeshes do not support createInstance.");
  53877. };
  53878. LinesMesh.prototype._bind = function (subMesh, effect, fillMode) {
  53879. if (!this._geometry) {
  53880. return this;
  53881. }
  53882. // VBOs
  53883. this._geometry._bind(this._colorShader.getEffect());
  53884. // Color
  53885. if (!this.useVertexColor) {
  53886. this._colorShader.setColor4("color", this.color.toColor4(this.alpha));
  53887. }
  53888. return this;
  53889. };
  53890. LinesMesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  53891. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  53892. return this;
  53893. }
  53894. var engine = this.getScene().getEngine();
  53895. // Draw order
  53896. engine.drawElementsType(BABYLON.Material.LineListDrawMode, subMesh.indexStart, subMesh.indexCount);
  53897. return this;
  53898. };
  53899. LinesMesh.prototype.dispose = function (doNotRecurse) {
  53900. this._colorShader.dispose();
  53901. _super.prototype.dispose.call(this, doNotRecurse);
  53902. };
  53903. /**
  53904. * Returns a new LineMesh object cloned from the current one.
  53905. */
  53906. LinesMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  53907. return new LinesMesh(name, this.getScene(), newParent, this, doNotCloneChildren);
  53908. };
  53909. return LinesMesh;
  53910. }(BABYLON.Mesh));
  53911. BABYLON.LinesMesh = LinesMesh;
  53912. })(BABYLON || (BABYLON = {}));
  53913. //# sourceMappingURL=babylon.linesMesh.js.map
  53914. var BABYLON;
  53915. (function (BABYLON) {
  53916. var MeshBuilder = /** @class */ (function () {
  53917. function MeshBuilder() {
  53918. }
  53919. MeshBuilder.updateSideOrientation = function (orientation) {
  53920. if (orientation == BABYLON.Mesh.DOUBLESIDE) {
  53921. return BABYLON.Mesh.DOUBLESIDE;
  53922. }
  53923. if (orientation === undefined || orientation === null) {
  53924. return BABYLON.Mesh.FRONTSIDE;
  53925. }
  53926. return orientation;
  53927. };
  53928. /**
  53929. * Creates a box mesh.
  53930. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#box
  53931. * The parameter `size` sets the size (float) of each box side (default 1).
  53932. * You can set some different box dimensions by using the parameters `width`, `height` and `depth` (all by default have the same value than `size`).
  53933. * 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).
  53934. * Please read this tutorial : http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  53935. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  53936. * 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).
  53937. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  53938. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  53939. */
  53940. MeshBuilder.CreateBox = function (name, options, scene) {
  53941. if (scene === void 0) { scene = null; }
  53942. var box = new BABYLON.Mesh(name, scene);
  53943. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  53944. box._originalBuilderSideOrientation = options.sideOrientation;
  53945. var vertexData = BABYLON.VertexData.CreateBox(options);
  53946. vertexData.applyToMesh(box, options.updatable);
  53947. return box;
  53948. };
  53949. /**
  53950. * Creates a sphere mesh.
  53951. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#sphere
  53952. * The parameter `diameter` sets the diameter size (float) of the sphere (default 1).
  53953. * 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`).
  53954. * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32).
  53955. * 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
  53956. * 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).
  53957. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  53958. * 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).
  53959. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  53960. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  53961. */
  53962. MeshBuilder.CreateSphere = function (name, options, scene) {
  53963. var sphere = new BABYLON.Mesh(name, scene);
  53964. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  53965. sphere._originalBuilderSideOrientation = options.sideOrientation;
  53966. var vertexData = BABYLON.VertexData.CreateSphere(options);
  53967. vertexData.applyToMesh(sphere, options.updatable);
  53968. return sphere;
  53969. };
  53970. /**
  53971. * Creates a plane polygonal mesh. By default, this is a disc.
  53972. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#disc
  53973. * The parameter `radius` sets the radius size (float) of the polygon (default 0.5).
  53974. * 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.
  53975. * 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
  53976. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  53977. * 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).
  53978. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  53979. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  53980. */
  53981. MeshBuilder.CreateDisc = function (name, options, scene) {
  53982. if (scene === void 0) { scene = null; }
  53983. var disc = new BABYLON.Mesh(name, scene);
  53984. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  53985. disc._originalBuilderSideOrientation = options.sideOrientation;
  53986. var vertexData = BABYLON.VertexData.CreateDisc(options);
  53987. vertexData.applyToMesh(disc, options.updatable);
  53988. return disc;
  53989. };
  53990. /**
  53991. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided.
  53992. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#icosphere
  53993. * The parameter `radius` sets the radius size (float) of the icosphere (default 1).
  53994. * 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`).
  53995. * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size.
  53996. * 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.
  53997. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  53998. * 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).
  53999. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  54000. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  54001. */
  54002. MeshBuilder.CreateIcoSphere = function (name, options, scene) {
  54003. var sphere = new BABYLON.Mesh(name, scene);
  54004. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  54005. sphere._originalBuilderSideOrientation = options.sideOrientation;
  54006. var vertexData = BABYLON.VertexData.CreateIcoSphere(options);
  54007. vertexData.applyToMesh(sphere, options.updatable);
  54008. return sphere;
  54009. };
  54010. ;
  54011. /**
  54012. * Creates a ribbon mesh.
  54013. * 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.
  54014. *
  54015. * Please read this full tutorial to understand how to design a ribbon : http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  54016. * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry.
  54017. * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array.
  54018. * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array.
  54019. * 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.
  54020. * 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.
  54021. * 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
  54022. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  54023. * 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).
  54024. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  54025. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  54026. * 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.
  54027. * The parameters `colors` is an optional flat array of `Color4` to set/update each ribbon vertex with its own custom color values.
  54028. * 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
  54029. * if you set `closePath` to `true`, there's one extra vertex per path in the geometry.
  54030. * Moreover, you can use the parameter `color` with `instance` (to update the ribbon), only if you previously used it at creation time.
  54031. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  54032. */
  54033. MeshBuilder.CreateRibbon = function (name, options, scene) {
  54034. if (scene === void 0) { scene = null; }
  54035. var pathArray = options.pathArray;
  54036. var closeArray = options.closeArray;
  54037. var closePath = options.closePath;
  54038. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  54039. var instance = options.instance;
  54040. var updatable = options.updatable;
  54041. if (instance) {
  54042. // positionFunction : ribbon case
  54043. // only pathArray and sideOrientation parameters are taken into account for positions update
  54044. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, BABYLON.Tmp.Vector3[0]); // minimum
  54045. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, BABYLON.Tmp.Vector3[1]);
  54046. var positionFunction = function (positions) {
  54047. var minlg = pathArray[0].length;
  54048. var i = 0;
  54049. var ns = (instance._originalBuilderSideOrientation === BABYLON.Mesh.DOUBLESIDE) ? 2 : 1;
  54050. for (var si = 1; si <= ns; si++) {
  54051. for (var p = 0; p < pathArray.length; p++) {
  54052. var path = pathArray[p];
  54053. var l = path.length;
  54054. minlg = (minlg < l) ? minlg : l;
  54055. var j = 0;
  54056. while (j < minlg) {
  54057. positions[i] = path[j].x;
  54058. positions[i + 1] = path[j].y;
  54059. positions[i + 2] = path[j].z;
  54060. if (path[j].x < BABYLON.Tmp.Vector3[0].x) {
  54061. BABYLON.Tmp.Vector3[0].x = path[j].x;
  54062. }
  54063. if (path[j].x > BABYLON.Tmp.Vector3[1].x) {
  54064. BABYLON.Tmp.Vector3[1].x = path[j].x;
  54065. }
  54066. if (path[j].y < BABYLON.Tmp.Vector3[0].y) {
  54067. BABYLON.Tmp.Vector3[0].y = path[j].y;
  54068. }
  54069. if (path[j].y > BABYLON.Tmp.Vector3[1].y) {
  54070. BABYLON.Tmp.Vector3[1].y = path[j].y;
  54071. }
  54072. if (path[j].z < BABYLON.Tmp.Vector3[0].z) {
  54073. BABYLON.Tmp.Vector3[0].z = path[j].z;
  54074. }
  54075. if (path[j].z > BABYLON.Tmp.Vector3[1].z) {
  54076. BABYLON.Tmp.Vector3[1].z = path[j].z;
  54077. }
  54078. j++;
  54079. i += 3;
  54080. }
  54081. if (instance._closePath) {
  54082. positions[i] = path[0].x;
  54083. positions[i + 1] = path[0].y;
  54084. positions[i + 2] = path[0].z;
  54085. i += 3;
  54086. }
  54087. }
  54088. }
  54089. };
  54090. var positions = instance.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  54091. positionFunction(positions);
  54092. instance._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Tmp.Vector3[0], BABYLON.Tmp.Vector3[1]);
  54093. instance._boundingInfo.update(instance._worldMatrix);
  54094. instance.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  54095. if (options.colors) {
  54096. var colors = instance.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  54097. for (var c = 0; c < options.colors.length; c++) {
  54098. colors[c * 4] = options.colors[c].r;
  54099. colors[c * 4 + 1] = options.colors[c].g;
  54100. colors[c * 4 + 2] = options.colors[c].b;
  54101. colors[c * 4 + 3] = options.colors[c].a;
  54102. }
  54103. instance.updateVerticesData(BABYLON.VertexBuffer.ColorKind, colors, false, false);
  54104. }
  54105. if (options.uvs) {
  54106. var uvs = instance.getVerticesData(BABYLON.VertexBuffer.UVKind);
  54107. for (var i = 0; i < options.uvs.length; i++) {
  54108. uvs[i * 2] = options.uvs[i].x;
  54109. uvs[i * 2 + 1] = options.uvs[i].y;
  54110. }
  54111. instance.updateVerticesData(BABYLON.VertexBuffer.UVKind, uvs, false, false);
  54112. }
  54113. if (!instance.areNormalsFrozen || instance.isFacetDataEnabled) {
  54114. var indices = instance.getIndices();
  54115. var normals = instance.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  54116. var params = instance.isFacetDataEnabled ? instance.getFacetDataParameters() : null;
  54117. BABYLON.VertexData.ComputeNormals(positions, indices, normals, params);
  54118. if (instance._closePath) {
  54119. var indexFirst = 0;
  54120. var indexLast = 0;
  54121. for (var p = 0; p < pathArray.length; p++) {
  54122. indexFirst = instance._idx[p] * 3;
  54123. if (p + 1 < pathArray.length) {
  54124. indexLast = (instance._idx[p + 1] - 1) * 3;
  54125. }
  54126. else {
  54127. indexLast = normals.length - 3;
  54128. }
  54129. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  54130. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  54131. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  54132. normals[indexLast] = normals[indexFirst];
  54133. normals[indexLast + 1] = normals[indexFirst + 1];
  54134. normals[indexLast + 2] = normals[indexFirst + 2];
  54135. }
  54136. }
  54137. if (!(instance.areNormalsFrozen)) {
  54138. instance.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  54139. }
  54140. }
  54141. return instance;
  54142. }
  54143. else {
  54144. var ribbon = new BABYLON.Mesh(name, scene);
  54145. ribbon._originalBuilderSideOrientation = sideOrientation;
  54146. var vertexData = BABYLON.VertexData.CreateRibbon(options);
  54147. if (closePath) {
  54148. ribbon._idx = vertexData._idx;
  54149. }
  54150. ribbon._closePath = closePath;
  54151. ribbon._closeArray = closeArray;
  54152. vertexData.applyToMesh(ribbon, updatable);
  54153. return ribbon;
  54154. }
  54155. };
  54156. /**
  54157. * Creates a cylinder or a cone mesh.
  54158. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#cylinder-or-cone
  54159. * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  54160. * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  54161. * 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.
  54162. * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  54163. * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  54164. * The parameter `hasRings` (boolean, default false) makes the subdivisions independent from each other, so they become different faces.
  54165. * The parameter `enclose` (boolean, default false) adds two extra faces per subdivision to a sliced cylinder to close it around its height axis.
  54166. * The parameter `arc` (float, default 1) is the ratio (max 1) to apply to the circumference to slice the cylinder.
  54167. * 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).
  54168. * 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
  54169. * Now, if the cylinder has 5 independent subdivisions (hasRings = true), n equals : top face + 5 stripe surfaces + bottom face = 2 + 5 = 7
  54170. * 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
  54171. * 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.
  54172. * If `enclose` is false, a ring surface is one element.
  54173. * If `enclose` is true, a ring surface is 3 successive elements in the array : the tubular surface, then the two closing faces.
  54174. * 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
  54175. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  54176. * 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).
  54177. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  54178. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  54179. */
  54180. MeshBuilder.CreateCylinder = function (name, options, scene) {
  54181. var cylinder = new BABYLON.Mesh(name, scene);
  54182. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  54183. cylinder._originalBuilderSideOrientation = options.sideOrientation;
  54184. var vertexData = BABYLON.VertexData.CreateCylinder(options);
  54185. vertexData.applyToMesh(cylinder, options.updatable);
  54186. return cylinder;
  54187. };
  54188. /**
  54189. * Creates a torus mesh.
  54190. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus
  54191. * The parameter `diameter` sets the diameter size (float) of the torus (default 1).
  54192. * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5).
  54193. * The parameter `tessellation` sets the number of torus sides (postive integer, default 16).
  54194. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  54195. * 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).
  54196. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  54197. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  54198. */
  54199. MeshBuilder.CreateTorus = function (name, options, scene) {
  54200. var torus = new BABYLON.Mesh(name, scene);
  54201. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  54202. torus._originalBuilderSideOrientation = options.sideOrientation;
  54203. var vertexData = BABYLON.VertexData.CreateTorus(options);
  54204. vertexData.applyToMesh(torus, options.updatable);
  54205. return torus;
  54206. };
  54207. /**
  54208. * Creates a torus knot mesh.
  54209. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus-knot
  54210. * The parameter `radius` sets the global radius size (float) of the torus knot (default 2).
  54211. * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32).
  54212. * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32).
  54213. * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3).
  54214. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  54215. * 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).
  54216. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  54217. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  54218. */
  54219. MeshBuilder.CreateTorusKnot = function (name, options, scene) {
  54220. var torusKnot = new BABYLON.Mesh(name, scene);
  54221. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  54222. torusKnot._originalBuilderSideOrientation = options.sideOrientation;
  54223. var vertexData = BABYLON.VertexData.CreateTorusKnot(options);
  54224. vertexData.applyToMesh(torusKnot, options.updatable);
  54225. return torusKnot;
  54226. };
  54227. /**
  54228. * Creates a line system mesh.
  54229. * A line system is a pool of many lines gathered in a single mesh.
  54230. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#linesystem
  54231. * 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.
  54232. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineSystem to this static function.
  54233. * The parameter `lines` is an array of lines, each line being an array of successive Vector3.
  54234. * 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
  54235. * The optional parameter `colors` is an array of line colors, each line colors being an array of successive Color4, one per line point.
  54236. * The optional parameter `useVertexAlpha' is to be set to `false` (default `true`) when you don't need the alpha blending (faster).
  54237. * 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
  54238. * When updating an instance, remember that only line point positions can change, not the number of points, neither the number of lines.
  54239. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  54240. */
  54241. MeshBuilder.CreateLineSystem = function (name, options, scene) {
  54242. var instance = options.instance;
  54243. var lines = options.lines;
  54244. var colors = options.colors;
  54245. if (instance) {
  54246. var positions = instance.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  54247. var vertexColor;
  54248. var lineColors;
  54249. if (colors) {
  54250. vertexColor = instance.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  54251. }
  54252. var i = 0;
  54253. var c = 0;
  54254. for (var l = 0; l < lines.length; l++) {
  54255. var points = lines[l];
  54256. for (var p = 0; p < points.length; p++) {
  54257. positions[i] = points[p].x;
  54258. positions[i + 1] = points[p].y;
  54259. positions[i + 2] = points[p].z;
  54260. if (colors && vertexColor) {
  54261. lineColors = colors[l];
  54262. vertexColor[c] = lineColors[p].r;
  54263. vertexColor[c + 1] = lineColors[p].g;
  54264. vertexColor[c + 2] = lineColors[p].b;
  54265. vertexColor[c + 3] = lineColors[p].a;
  54266. c += 4;
  54267. }
  54268. i += 3;
  54269. }
  54270. }
  54271. instance.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  54272. if (colors && vertexColor) {
  54273. instance.updateVerticesData(BABYLON.VertexBuffer.ColorKind, vertexColor, false, false);
  54274. }
  54275. return instance;
  54276. }
  54277. // line system creation
  54278. var useVertexColor = (colors) ? true : false;
  54279. var lineSystem = new BABYLON.LinesMesh(name, scene, null, undefined, undefined, useVertexColor, options.useVertexAlpha);
  54280. var vertexData = BABYLON.VertexData.CreateLineSystem(options);
  54281. vertexData.applyToMesh(lineSystem, options.updatable);
  54282. return lineSystem;
  54283. };
  54284. /**
  54285. * Creates a line mesh.
  54286. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#lines
  54287. * 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.
  54288. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  54289. * The parameter `points` is an array successive Vector3.
  54290. * 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
  54291. * The optional parameter `colors` is an array of successive Color4, one per line point.
  54292. * The optional parameter `useVertexAlpha' is to be set to `false` (default `true`) when you don't need alpha blending (faster).
  54293. * When updating an instance, remember that only point positions can change, not the number of points.
  54294. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  54295. */
  54296. MeshBuilder.CreateLines = function (name, options, scene) {
  54297. if (scene === void 0) { scene = null; }
  54298. var colors = (options.colors) ? [options.colors] : null;
  54299. var lines = MeshBuilder.CreateLineSystem(name, { lines: [options.points], updatable: options.updatable, instance: options.instance, colors: colors, useVertexAlpha: options.useVertexAlpha }, scene);
  54300. return lines;
  54301. };
  54302. /**
  54303. * Creates a dashed line mesh.
  54304. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#dashed-lines
  54305. * 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.
  54306. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  54307. * The parameter `points` is an array successive Vector3.
  54308. * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200).
  54309. * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3).
  54310. * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1).
  54311. * 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
  54312. * When updating an instance, remember that only point positions can change, not the number of points.
  54313. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  54314. */
  54315. MeshBuilder.CreateDashedLines = function (name, options, scene) {
  54316. if (scene === void 0) { scene = null; }
  54317. var points = options.points;
  54318. var instance = options.instance;
  54319. var gapSize = options.gapSize || 1;
  54320. var dashSize = options.dashSize || 3;
  54321. if (instance) {
  54322. var positionFunction = function (positions) {
  54323. var curvect = BABYLON.Vector3.Zero();
  54324. var nbSeg = positions.length / 6;
  54325. var lg = 0;
  54326. var nb = 0;
  54327. var shft = 0;
  54328. var dashshft = 0;
  54329. var curshft = 0;
  54330. var p = 0;
  54331. var i = 0;
  54332. var j = 0;
  54333. for (i = 0; i < points.length - 1; i++) {
  54334. points[i + 1].subtractToRef(points[i], curvect);
  54335. lg += curvect.length();
  54336. }
  54337. shft = lg / nbSeg;
  54338. dashshft = instance.dashSize * shft / (instance.dashSize + instance.gapSize);
  54339. for (i = 0; i < points.length - 1; i++) {
  54340. points[i + 1].subtractToRef(points[i], curvect);
  54341. nb = Math.floor(curvect.length() / shft);
  54342. curvect.normalize();
  54343. j = 0;
  54344. while (j < nb && p < positions.length) {
  54345. curshft = shft * j;
  54346. positions[p] = points[i].x + curshft * curvect.x;
  54347. positions[p + 1] = points[i].y + curshft * curvect.y;
  54348. positions[p + 2] = points[i].z + curshft * curvect.z;
  54349. positions[p + 3] = points[i].x + (curshft + dashshft) * curvect.x;
  54350. positions[p + 4] = points[i].y + (curshft + dashshft) * curvect.y;
  54351. positions[p + 5] = points[i].z + (curshft + dashshft) * curvect.z;
  54352. p += 6;
  54353. j++;
  54354. }
  54355. }
  54356. while (p < positions.length) {
  54357. positions[p] = points[i].x;
  54358. positions[p + 1] = points[i].y;
  54359. positions[p + 2] = points[i].z;
  54360. p += 3;
  54361. }
  54362. };
  54363. instance.updateMeshPositions(positionFunction, false);
  54364. return instance;
  54365. }
  54366. // dashed lines creation
  54367. var dashedLines = new BABYLON.LinesMesh(name, scene);
  54368. var vertexData = BABYLON.VertexData.CreateDashedLines(options);
  54369. vertexData.applyToMesh(dashedLines, options.updatable);
  54370. dashedLines.dashSize = dashSize;
  54371. dashedLines.gapSize = gapSize;
  54372. return dashedLines;
  54373. };
  54374. /**
  54375. * Creates an extruded shape mesh.
  54376. * 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.
  54377. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#extruded-shapes
  54378. *
  54379. * Please read this full tutorial to understand how to design an extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  54380. * 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
  54381. * extruded along the Z axis.
  54382. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  54383. * 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.
  54384. * The parameter `scale` (float, default 1) is the value to scale the shape.
  54385. * 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
  54386. * 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
  54387. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  54388. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  54389. * 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).
  54390. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  54391. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  54392. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  54393. */
  54394. MeshBuilder.ExtrudeShape = function (name, options, scene) {
  54395. if (scene === void 0) { scene = null; }
  54396. var path = options.path;
  54397. var shape = options.shape;
  54398. var scale = options.scale || 1;
  54399. var rotation = options.rotation || 0;
  54400. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  54401. var updatable = options.updatable;
  54402. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  54403. var instance = options.instance || null;
  54404. var invertUV = options.invertUV || false;
  54405. 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);
  54406. };
  54407. /**
  54408. * Creates an custom extruded shape mesh.
  54409. * 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.
  54410. * tuto :http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#custom-extruded-shapes
  54411. *
  54412. * Please read this full tutorial to understand how to design a custom extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  54413. * 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
  54414. * extruded along the Z axis.
  54415. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  54416. * 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
  54417. * and the distance of this point from the begining of the path :
  54418. * ```javascript
  54419. * var rotationFunction = function(i, distance) {
  54420. * // do things
  54421. * return rotationValue; }
  54422. * ```
  54423. * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  54424. * 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
  54425. * and the distance of this point from the begining of the path :
  54426. * ```javascript
  54427. * var scaleFunction = function(i, distance) {
  54428. * // do things
  54429. * return scaleValue;}
  54430. * ```
  54431. * It must returns a float value that will be the scale value applied to the shape on each path point.
  54432. * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`.
  54433. * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`.
  54434. * 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
  54435. * 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
  54436. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  54437. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  54438. * 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).
  54439. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  54440. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  54441. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  54442. */
  54443. MeshBuilder.ExtrudeShapeCustom = function (name, options, scene) {
  54444. var path = options.path;
  54445. var shape = options.shape;
  54446. var scaleFunction = options.scaleFunction || (function () { return 1; });
  54447. var rotationFunction = options.rotationFunction || (function () { return 0; });
  54448. var ribbonCloseArray = options.ribbonCloseArray || false;
  54449. var ribbonClosePath = options.ribbonClosePath || false;
  54450. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  54451. var updatable = options.updatable;
  54452. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  54453. var instance = options.instance;
  54454. var invertUV = options.invertUV || false;
  54455. 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);
  54456. };
  54457. /**
  54458. * Creates lathe mesh.
  54459. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe.
  54460. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#lathe
  54461. *
  54462. * 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
  54463. * rotated around the Y axis. It's usually a 2D shape, so the Vector3 z coordinates are often set to zero.
  54464. * The parameter `radius` (positive float, default 1) is the radius value of the lathe.
  54465. * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe.
  54466. * 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.
  54467. * The parameter `closed` (boolean, default true) opens/closes the lathe circumference. This should be set to false when used with the parameter "arc".
  54468. * 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
  54469. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  54470. * 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).
  54471. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  54472. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  54473. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  54474. */
  54475. MeshBuilder.CreateLathe = function (name, options, scene) {
  54476. var arc = options.arc ? ((options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc) : 1.0;
  54477. var closed = (options.closed === undefined) ? true : options.closed;
  54478. var shape = options.shape;
  54479. var radius = options.radius || 1;
  54480. var tessellation = options.tessellation || 64;
  54481. var updatable = options.updatable;
  54482. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  54483. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  54484. var pi2 = Math.PI * 2;
  54485. var paths = new Array();
  54486. var invertUV = options.invertUV || false;
  54487. var i = 0;
  54488. var p = 0;
  54489. var step = pi2 / tessellation * arc;
  54490. var rotated;
  54491. var path = new Array();
  54492. ;
  54493. for (i = 0; i <= tessellation; i++) {
  54494. var path = [];
  54495. if (cap == BABYLON.Mesh.CAP_START || cap == BABYLON.Mesh.CAP_ALL) {
  54496. path.push(new BABYLON.Vector3(0, shape[0].y, 0));
  54497. path.push(new BABYLON.Vector3(Math.cos(i * step) * shape[0].x * radius, shape[0].y, Math.sin(i * step) * shape[0].x * radius));
  54498. }
  54499. for (p = 0; p < shape.length; p++) {
  54500. rotated = new BABYLON.Vector3(Math.cos(i * step) * shape[p].x * radius, shape[p].y, Math.sin(i * step) * shape[p].x * radius);
  54501. path.push(rotated);
  54502. }
  54503. if (cap == BABYLON.Mesh.CAP_END || cap == BABYLON.Mesh.CAP_ALL) {
  54504. 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));
  54505. path.push(new BABYLON.Vector3(0, shape[shape.length - 1].y, 0));
  54506. }
  54507. paths.push(path);
  54508. }
  54509. // lathe ribbon
  54510. var lathe = MeshBuilder.CreateRibbon(name, { pathArray: paths, closeArray: closed, sideOrientation: sideOrientation, updatable: updatable, invertUV: invertUV, frontUVs: options.frontUVs, backUVs: options.backUVs }, scene);
  54511. return lathe;
  54512. };
  54513. /**
  54514. * Creates a plane mesh.
  54515. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  54516. * The parameter `size` sets the size (float) of both sides of the plane at once (default 1).
  54517. * You can set some different plane dimensions by using the parameters `width` and `height` (both by default have the same value than `size`).
  54518. * The parameter `sourcePlane` is a Plane instance. It builds a mesh plane from a Math plane.
  54519. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  54520. * 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).
  54521. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  54522. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  54523. */
  54524. MeshBuilder.CreatePlane = function (name, options, scene) {
  54525. var plane = new BABYLON.Mesh(name, scene);
  54526. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  54527. plane._originalBuilderSideOrientation = options.sideOrientation;
  54528. var vertexData = BABYLON.VertexData.CreatePlane(options);
  54529. vertexData.applyToMesh(plane, options.updatable);
  54530. if (options.sourcePlane) {
  54531. plane.translate(options.sourcePlane.normal, options.sourcePlane.d);
  54532. var product = Math.acos(BABYLON.Vector3.Dot(options.sourcePlane.normal, BABYLON.Axis.Z));
  54533. var vectorProduct = BABYLON.Vector3.Cross(BABYLON.Axis.Z, options.sourcePlane.normal);
  54534. plane.rotate(vectorProduct, product);
  54535. }
  54536. return plane;
  54537. };
  54538. /**
  54539. * Creates a ground mesh.
  54540. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  54541. * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground.
  54542. * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side.
  54543. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  54544. */
  54545. MeshBuilder.CreateGround = function (name, options, scene) {
  54546. var ground = new BABYLON.GroundMesh(name, scene);
  54547. ground._setReady(false);
  54548. ground._subdivisionsX = options.subdivisionsX || options.subdivisions || 1;
  54549. ground._subdivisionsY = options.subdivisionsY || options.subdivisions || 1;
  54550. ground._width = options.width || 1;
  54551. ground._height = options.height || 1;
  54552. ground._maxX = ground._width / 2;
  54553. ground._maxZ = ground._height / 2;
  54554. ground._minX = -ground._maxX;
  54555. ground._minZ = -ground._maxZ;
  54556. var vertexData = BABYLON.VertexData.CreateGround(options);
  54557. vertexData.applyToMesh(ground, options.updatable);
  54558. ground._setReady(true);
  54559. return ground;
  54560. };
  54561. /**
  54562. * Creates a tiled ground mesh.
  54563. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tiled-ground
  54564. * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates.
  54565. * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates.
  54566. * The parameter `subdivisions` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 6, h: 6}`). `w` and `h` are the
  54567. * numbers of subdivisions on the ground width and height. Each subdivision is called a tile.
  54568. * The parameter `precision` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 2, h: 2}`). `w` and `h` are the
  54569. * numbers of subdivisions on the ground width and height of each tile.
  54570. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  54571. */
  54572. MeshBuilder.CreateTiledGround = function (name, options, scene) {
  54573. var tiledGround = new BABYLON.Mesh(name, scene);
  54574. var vertexData = BABYLON.VertexData.CreateTiledGround(options);
  54575. vertexData.applyToMesh(tiledGround, options.updatable);
  54576. return tiledGround;
  54577. };
  54578. /**
  54579. * Creates a ground mesh from a height map.
  54580. * tuto : http://doc.babylonjs.com/tutorials/14._Height_Map
  54581. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#ground-from-a-height-map
  54582. * The parameter `url` sets the URL of the height map image resource.
  54583. * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  54584. * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  54585. * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  54586. * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  54587. * 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.
  54588. * 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).
  54589. * This function is passed the newly built mesh :
  54590. * ```javascript
  54591. * function(mesh) { // do things
  54592. * return; }
  54593. * ```
  54594. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  54595. */
  54596. MeshBuilder.CreateGroundFromHeightMap = function (name, url, options, scene) {
  54597. var width = options.width || 10.0;
  54598. var height = options.height || 10.0;
  54599. var subdivisions = options.subdivisions || 1 | 0;
  54600. var minHeight = options.minHeight || 0.0;
  54601. var maxHeight = options.maxHeight || 1.0;
  54602. var filter = options.colorFilter || new BABYLON.Color3(0.3, 0.59, 0.11);
  54603. var updatable = options.updatable;
  54604. var onReady = options.onReady;
  54605. var ground = new BABYLON.GroundMesh(name, scene);
  54606. ground._subdivisionsX = subdivisions;
  54607. ground._subdivisionsY = subdivisions;
  54608. ground._width = width;
  54609. ground._height = height;
  54610. ground._maxX = ground._width / 2.0;
  54611. ground._maxZ = ground._height / 2.0;
  54612. ground._minX = -ground._maxX;
  54613. ground._minZ = -ground._maxZ;
  54614. ground._setReady(false);
  54615. var onload = function (img) {
  54616. // Getting height map data
  54617. var canvas = document.createElement("canvas");
  54618. var context = canvas.getContext("2d");
  54619. if (!context) {
  54620. throw new Error("Unable to get 2d context for CreateGroundFromHeightMap");
  54621. }
  54622. if (scene.isDisposed) {
  54623. return;
  54624. }
  54625. var bufferWidth = img.width;
  54626. var bufferHeight = img.height;
  54627. canvas.width = bufferWidth;
  54628. canvas.height = bufferHeight;
  54629. context.drawImage(img, 0, 0);
  54630. // Create VertexData from map data
  54631. // Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  54632. var buffer = context.getImageData(0, 0, bufferWidth, bufferHeight).data;
  54633. var vertexData = BABYLON.VertexData.CreateGroundFromHeightMap({
  54634. width: width, height: height,
  54635. subdivisions: subdivisions,
  54636. minHeight: minHeight, maxHeight: maxHeight, colorFilter: filter,
  54637. buffer: buffer, bufferWidth: bufferWidth, bufferHeight: bufferHeight
  54638. });
  54639. vertexData.applyToMesh(ground, updatable);
  54640. ground._setReady(true);
  54641. //execute ready callback, if set
  54642. if (onReady) {
  54643. onReady(ground);
  54644. }
  54645. };
  54646. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  54647. return ground;
  54648. };
  54649. /**
  54650. * Creates a polygon mesh.
  54651. * The polygon's shape will depend on the input parameters and is constructed parallel to a ground mesh.
  54652. * 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.
  54653. * You can set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  54654. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  54655. * 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).
  54656. * Remember you can only change the shape positions, not their number when updating a polygon.
  54657. */
  54658. MeshBuilder.CreatePolygon = function (name, options, scene) {
  54659. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  54660. var shape = options.shape;
  54661. var holes = options.holes || [];
  54662. var depth = options.depth || 0;
  54663. var contours = [];
  54664. var hole = [];
  54665. for (var i = 0; i < shape.length; i++) {
  54666. contours[i] = new BABYLON.Vector2(shape[i].x, shape[i].z);
  54667. }
  54668. var epsilon = 0.00000001;
  54669. if (contours[0].equalsWithEpsilon(contours[contours.length - 1], epsilon)) {
  54670. contours.pop();
  54671. }
  54672. var polygonTriangulation = new BABYLON.PolygonMeshBuilder(name, contours, scene);
  54673. for (var hNb = 0; hNb < holes.length; hNb++) {
  54674. hole = [];
  54675. for (var hPoint = 0; hPoint < holes[hNb].length; hPoint++) {
  54676. hole.push(new BABYLON.Vector2(holes[hNb][hPoint].x, holes[hNb][hPoint].z));
  54677. }
  54678. polygonTriangulation.addHole(hole);
  54679. }
  54680. var polygon = polygonTriangulation.build(options.updatable, depth);
  54681. polygon._originalBuilderSideOrientation = options.sideOrientation;
  54682. var vertexData = BABYLON.VertexData.CreatePolygon(polygon, options.sideOrientation, options.faceUV, options.faceColors, options.frontUVs, options.backUVs);
  54683. vertexData.applyToMesh(polygon, options.updatable);
  54684. return polygon;
  54685. };
  54686. ;
  54687. /**
  54688. * Creates an extruded polygon mesh, with depth in the Y direction.
  54689. * 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).
  54690. * Please read this tutorial : http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  54691. */
  54692. MeshBuilder.ExtrudePolygon = function (name, options, scene) {
  54693. return MeshBuilder.CreatePolygon(name, options, scene);
  54694. };
  54695. ;
  54696. /**
  54697. * Creates a tube mesh.
  54698. * 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.
  54699. *
  54700. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tube
  54701. * The parameter `path` is a required array of successive Vector3. It is the curve used as the axis of the tube.
  54702. * The parameter `radius` (positive float, default 1) sets the tube radius size.
  54703. * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface.
  54704. * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`.
  54705. * 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.
  54706. * It must return a radius value (positive float) :
  54707. * ```javascript
  54708. * var radiusFunction = function(i, distance) {
  54709. * // do things
  54710. * return radius; }
  54711. * ```
  54712. * The parameter `arc` (positive float, maximum 1, default 1) is the ratio to apply to the tube circumference : 2 x PI x arc.
  54713. * 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
  54714. * 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
  54715. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  54716. * 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).
  54717. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  54718. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  54719. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  54720. */
  54721. MeshBuilder.CreateTube = function (name, options, scene) {
  54722. var path = options.path;
  54723. var instance = options.instance;
  54724. var radius = 1.0;
  54725. if (instance) {
  54726. radius = instance.radius;
  54727. }
  54728. if (options.radius !== undefined) {
  54729. radius = options.radius;
  54730. }
  54731. ;
  54732. var tessellation = options.tessellation || 64 | 0;
  54733. var radiusFunction = options.radiusFunction || null;
  54734. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  54735. var invertUV = options.invertUV || false;
  54736. var updatable = options.updatable;
  54737. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  54738. options.arc = options.arc && (options.arc <= 0.0 || options.arc > 1.0) ? 1.0 : options.arc || 1.0;
  54739. // tube geometry
  54740. var tubePathArray = function (path, path3D, circlePaths, radius, tessellation, radiusFunction, cap, arc) {
  54741. var tangents = path3D.getTangents();
  54742. var normals = path3D.getNormals();
  54743. var distances = path3D.getDistances();
  54744. var pi2 = Math.PI * 2;
  54745. var step = pi2 / tessellation * arc;
  54746. var returnRadius = function () { return radius; };
  54747. var radiusFunctionFinal = radiusFunction || returnRadius;
  54748. var circlePath;
  54749. var rad;
  54750. var normal;
  54751. var rotated;
  54752. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  54753. var index = (cap === BABYLON.Mesh._NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  54754. for (var i = 0; i < path.length; i++) {
  54755. rad = radiusFunctionFinal(i, distances[i]); // current radius
  54756. circlePath = Array(); // current circle array
  54757. normal = normals[i]; // current normal
  54758. for (var t = 0; t < tessellation; t++) {
  54759. BABYLON.Matrix.RotationAxisToRef(tangents[i], step * t, rotationMatrix);
  54760. rotated = circlePath[t] ? circlePath[t] : BABYLON.Vector3.Zero();
  54761. BABYLON.Vector3.TransformCoordinatesToRef(normal, rotationMatrix, rotated);
  54762. rotated.scaleInPlace(rad).addInPlace(path[i]);
  54763. circlePath[t] = rotated;
  54764. }
  54765. circlePaths[index] = circlePath;
  54766. index++;
  54767. }
  54768. // cap
  54769. var capPath = function (nbPoints, pathIndex) {
  54770. var pointCap = Array();
  54771. for (var i = 0; i < nbPoints; i++) {
  54772. pointCap.push(path[pathIndex]);
  54773. }
  54774. return pointCap;
  54775. };
  54776. switch (cap) {
  54777. case BABYLON.Mesh.NO_CAP:
  54778. break;
  54779. case BABYLON.Mesh.CAP_START:
  54780. circlePaths[0] = capPath(tessellation, 0);
  54781. circlePaths[1] = circlePaths[2].slice(0);
  54782. break;
  54783. case BABYLON.Mesh.CAP_END:
  54784. circlePaths[index] = circlePaths[index - 1].slice(0);
  54785. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  54786. break;
  54787. case BABYLON.Mesh.CAP_ALL:
  54788. circlePaths[0] = capPath(tessellation, 0);
  54789. circlePaths[1] = circlePaths[2].slice(0);
  54790. circlePaths[index] = circlePaths[index - 1].slice(0);
  54791. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  54792. break;
  54793. default:
  54794. break;
  54795. }
  54796. return circlePaths;
  54797. };
  54798. var path3D;
  54799. var pathArray;
  54800. if (instance) {
  54801. var arc = options.arc || instance.arc;
  54802. path3D = (instance.path3D).update(path);
  54803. pathArray = tubePathArray(path, path3D, instance.pathArray, radius, instance.tessellation, radiusFunction, instance.cap, arc);
  54804. instance = MeshBuilder.CreateRibbon("", { pathArray: pathArray, instance: instance });
  54805. instance.path3D = path3D;
  54806. instance.pathArray = pathArray;
  54807. instance.arc = arc;
  54808. instance.radius = radius;
  54809. return instance;
  54810. }
  54811. // tube creation
  54812. path3D = new BABYLON.Path3D(path);
  54813. var newPathArray = new Array();
  54814. cap = (cap < 0 || cap > 3) ? 0 : cap;
  54815. pathArray = tubePathArray(path, path3D, newPathArray, radius, tessellation, radiusFunction, cap, options.arc);
  54816. var tube = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closePath: true, closeArray: false, updatable: updatable, sideOrientation: sideOrientation, invertUV: invertUV, frontUVs: options.frontUVs, backUVs: options.backUVs }, scene);
  54817. tube.pathArray = pathArray;
  54818. tube.path3D = path3D;
  54819. tube.tessellation = tessellation;
  54820. tube.cap = cap;
  54821. tube.arc = options.arc;
  54822. tube.radius = radius;
  54823. return tube;
  54824. };
  54825. /**
  54826. * Creates a polyhedron mesh.
  54827. *
  54828. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#polyhedron
  54829. * 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
  54830. * to choose the wanted type.
  54831. * The parameter `size` (positive float, default 1) sets the polygon size.
  54832. * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value).
  54833. * 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`.
  54834. * 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
  54835. * 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)`).
  54836. * 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
  54837. * 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.
  54838. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  54839. * 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).
  54840. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  54841. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  54842. */
  54843. MeshBuilder.CreatePolyhedron = function (name, options, scene) {
  54844. var polyhedron = new BABYLON.Mesh(name, scene);
  54845. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  54846. polyhedron._originalBuilderSideOrientation = options.sideOrientation;
  54847. var vertexData = BABYLON.VertexData.CreatePolyhedron(options);
  54848. vertexData.applyToMesh(polyhedron, options.updatable);
  54849. return polyhedron;
  54850. };
  54851. /**
  54852. * Creates a decal mesh.
  54853. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#decals
  54854. * 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.
  54855. * The parameter `position` (Vector3, default `(0, 0, 0)`) sets the position of the decal in World coordinates.
  54856. * The parameter `normal` (Vector3, default `Vector3.Up`) sets the normal of the mesh where the decal is applied onto in World coordinates.
  54857. * The parameter `size` (Vector3, default `(1, 1, 1)`) sets the decal scaling.
  54858. * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal.
  54859. */
  54860. MeshBuilder.CreateDecal = function (name, sourceMesh, options) {
  54861. var indices = sourceMesh.getIndices();
  54862. var positions = sourceMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  54863. var normals = sourceMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  54864. var position = options.position || BABYLON.Vector3.Zero();
  54865. var normal = options.normal || BABYLON.Vector3.Up();
  54866. var size = options.size || BABYLON.Vector3.One();
  54867. var angle = options.angle || 0;
  54868. // Getting correct rotation
  54869. if (!normal) {
  54870. var target = new BABYLON.Vector3(0, 0, 1);
  54871. var camera = sourceMesh.getScene().activeCamera;
  54872. var cameraWorldTarget = BABYLON.Vector3.TransformCoordinates(target, camera.getWorldMatrix());
  54873. normal = camera.globalPosition.subtract(cameraWorldTarget);
  54874. }
  54875. var yaw = -Math.atan2(normal.z, normal.x) - Math.PI / 2;
  54876. var len = Math.sqrt(normal.x * normal.x + normal.z * normal.z);
  54877. var pitch = Math.atan2(normal.y, len);
  54878. // Matrix
  54879. var decalWorldMatrix = BABYLON.Matrix.RotationYawPitchRoll(yaw, pitch, angle).multiply(BABYLON.Matrix.Translation(position.x, position.y, position.z));
  54880. var inverseDecalWorldMatrix = BABYLON.Matrix.Invert(decalWorldMatrix);
  54881. var meshWorldMatrix = sourceMesh.getWorldMatrix();
  54882. var transformMatrix = meshWorldMatrix.multiply(inverseDecalWorldMatrix);
  54883. var vertexData = new BABYLON.VertexData();
  54884. vertexData.indices = [];
  54885. vertexData.positions = [];
  54886. vertexData.normals = [];
  54887. vertexData.uvs = [];
  54888. var currentVertexDataIndex = 0;
  54889. var extractDecalVector3 = function (indexId) {
  54890. var result = new BABYLON.PositionNormalVertex();
  54891. if (!indices || !positions || !normals) {
  54892. return result;
  54893. }
  54894. var vertexId = indices[indexId];
  54895. result.position = new BABYLON.Vector3(positions[vertexId * 3], positions[vertexId * 3 + 1], positions[vertexId * 3 + 2]);
  54896. // Send vector to decal local world
  54897. result.position = BABYLON.Vector3.TransformCoordinates(result.position, transformMatrix);
  54898. // Get normal
  54899. result.normal = new BABYLON.Vector3(normals[vertexId * 3], normals[vertexId * 3 + 1], normals[vertexId * 3 + 2]);
  54900. result.normal = BABYLON.Vector3.TransformNormal(result.normal, transformMatrix);
  54901. return result;
  54902. }; // Inspired by https://github.com/mrdoob/three.js/blob/eee231960882f6f3b6113405f524956145148146/examples/js/geometries/DecalGeometry.js
  54903. var clip = function (vertices, axis) {
  54904. if (vertices.length === 0) {
  54905. return vertices;
  54906. }
  54907. var clipSize = 0.5 * Math.abs(BABYLON.Vector3.Dot(size, axis));
  54908. var clipVertices = function (v0, v1) {
  54909. var clipFactor = BABYLON.Vector3.GetClipFactor(v0.position, v1.position, axis, clipSize);
  54910. return new BABYLON.PositionNormalVertex(BABYLON.Vector3.Lerp(v0.position, v1.position, clipFactor), BABYLON.Vector3.Lerp(v0.normal, v1.normal, clipFactor));
  54911. };
  54912. var result = new Array();
  54913. for (var index = 0; index < vertices.length; index += 3) {
  54914. var v1Out;
  54915. var v2Out;
  54916. var v3Out;
  54917. var total = 0;
  54918. var nV1 = null;
  54919. var nV2 = null;
  54920. var nV3 = null;
  54921. var nV4 = null;
  54922. var d1 = BABYLON.Vector3.Dot(vertices[index].position, axis) - clipSize;
  54923. var d2 = BABYLON.Vector3.Dot(vertices[index + 1].position, axis) - clipSize;
  54924. var d3 = BABYLON.Vector3.Dot(vertices[index + 2].position, axis) - clipSize;
  54925. v1Out = d1 > 0;
  54926. v2Out = d2 > 0;
  54927. v3Out = d3 > 0;
  54928. total = (v1Out ? 1 : 0) + (v2Out ? 1 : 0) + (v3Out ? 1 : 0);
  54929. switch (total) {
  54930. case 0:
  54931. result.push(vertices[index]);
  54932. result.push(vertices[index + 1]);
  54933. result.push(vertices[index + 2]);
  54934. break;
  54935. case 1:
  54936. if (v1Out) {
  54937. nV1 = vertices[index + 1];
  54938. nV2 = vertices[index + 2];
  54939. nV3 = clipVertices(vertices[index], nV1);
  54940. nV4 = clipVertices(vertices[index], nV2);
  54941. }
  54942. if (v2Out) {
  54943. nV1 = vertices[index];
  54944. nV2 = vertices[index + 2];
  54945. nV3 = clipVertices(vertices[index + 1], nV1);
  54946. nV4 = clipVertices(vertices[index + 1], nV2);
  54947. result.push(nV3);
  54948. result.push(nV2.clone());
  54949. result.push(nV1.clone());
  54950. result.push(nV2.clone());
  54951. result.push(nV3.clone());
  54952. result.push(nV4);
  54953. break;
  54954. }
  54955. if (v3Out) {
  54956. nV1 = vertices[index];
  54957. nV2 = vertices[index + 1];
  54958. nV3 = clipVertices(vertices[index + 2], nV1);
  54959. nV4 = clipVertices(vertices[index + 2], nV2);
  54960. }
  54961. if (nV1 && nV2 && nV3 && nV4) {
  54962. result.push(nV1.clone());
  54963. result.push(nV2.clone());
  54964. result.push(nV3);
  54965. result.push(nV4);
  54966. result.push(nV3.clone());
  54967. result.push(nV2.clone());
  54968. }
  54969. break;
  54970. case 2:
  54971. if (!v1Out) {
  54972. nV1 = vertices[index].clone();
  54973. nV2 = clipVertices(nV1, vertices[index + 1]);
  54974. nV3 = clipVertices(nV1, vertices[index + 2]);
  54975. result.push(nV1);
  54976. result.push(nV2);
  54977. result.push(nV3);
  54978. }
  54979. if (!v2Out) {
  54980. nV1 = vertices[index + 1].clone();
  54981. nV2 = clipVertices(nV1, vertices[index + 2]);
  54982. nV3 = clipVertices(nV1, vertices[index]);
  54983. result.push(nV1);
  54984. result.push(nV2);
  54985. result.push(nV3);
  54986. }
  54987. if (!v3Out) {
  54988. nV1 = vertices[index + 2].clone();
  54989. nV2 = clipVertices(nV1, vertices[index]);
  54990. nV3 = clipVertices(nV1, vertices[index + 1]);
  54991. result.push(nV1);
  54992. result.push(nV2);
  54993. result.push(nV3);
  54994. }
  54995. break;
  54996. case 3:
  54997. break;
  54998. }
  54999. }
  55000. return result;
  55001. };
  55002. for (var index = 0; index < indices.length; index += 3) {
  55003. var faceVertices = new Array();
  55004. faceVertices.push(extractDecalVector3(index));
  55005. faceVertices.push(extractDecalVector3(index + 1));
  55006. faceVertices.push(extractDecalVector3(index + 2));
  55007. // Clip
  55008. faceVertices = clip(faceVertices, new BABYLON.Vector3(1, 0, 0));
  55009. faceVertices = clip(faceVertices, new BABYLON.Vector3(-1, 0, 0));
  55010. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 1, 0));
  55011. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, -1, 0));
  55012. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, 1));
  55013. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, -1));
  55014. if (faceVertices.length === 0) {
  55015. continue;
  55016. }
  55017. // Add UVs and get back to world
  55018. for (var vIndex = 0; vIndex < faceVertices.length; vIndex++) {
  55019. var vertex = faceVertices[vIndex];
  55020. //TODO check for Int32Array | Uint32Array | Uint16Array
  55021. vertexData.indices.push(currentVertexDataIndex);
  55022. vertex.position.toArray(vertexData.positions, currentVertexDataIndex * 3);
  55023. vertex.normal.toArray(vertexData.normals, currentVertexDataIndex * 3);
  55024. vertexData.uvs.push(0.5 + vertex.position.x / size.x);
  55025. vertexData.uvs.push(0.5 + vertex.position.y / size.y);
  55026. currentVertexDataIndex++;
  55027. }
  55028. }
  55029. // Return mesh
  55030. var decal = new BABYLON.Mesh(name, sourceMesh.getScene());
  55031. vertexData.applyToMesh(decal);
  55032. decal.position = position.clone();
  55033. decal.rotation = new BABYLON.Vector3(pitch, yaw, angle);
  55034. return decal;
  55035. };
  55036. // Privates
  55037. MeshBuilder._ExtrudeShapeGeneric = function (name, shape, curve, scale, rotation, scaleFunction, rotateFunction, rbCA, rbCP, cap, custom, scene, updtbl, side, instance, invertUV, frontUVs, backUVs) {
  55038. // extrusion geometry
  55039. var extrusionPathArray = function (shape, curve, path3D, shapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom) {
  55040. var tangents = path3D.getTangents();
  55041. var normals = path3D.getNormals();
  55042. var binormals = path3D.getBinormals();
  55043. var distances = path3D.getDistances();
  55044. var angle = 0;
  55045. var returnScale = function () { return scale !== null ? scale : 1; };
  55046. var returnRotation = function () { return rotation !== null ? rotation : 0; };
  55047. var rotate = custom && rotateFunction ? rotateFunction : returnRotation;
  55048. var scl = custom && scaleFunction ? scaleFunction : returnScale;
  55049. var index = (cap === BABYLON.Mesh.NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  55050. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  55051. for (var i = 0; i < curve.length; i++) {
  55052. var shapePath = new Array();
  55053. var angleStep = rotate(i, distances[i]);
  55054. var scaleRatio = scl(i, distances[i]);
  55055. for (var p = 0; p < shape.length; p++) {
  55056. BABYLON.Matrix.RotationAxisToRef(tangents[i], angle, rotationMatrix);
  55057. var planed = ((tangents[i].scale(shape[p].z)).add(normals[i].scale(shape[p].x)).add(binormals[i].scale(shape[p].y)));
  55058. var rotated = shapePath[p] ? shapePath[p] : BABYLON.Vector3.Zero();
  55059. BABYLON.Vector3.TransformCoordinatesToRef(planed, rotationMatrix, rotated);
  55060. rotated.scaleInPlace(scaleRatio).addInPlace(curve[i]);
  55061. shapePath[p] = rotated;
  55062. }
  55063. shapePaths[index] = shapePath;
  55064. angle += angleStep;
  55065. index++;
  55066. }
  55067. // cap
  55068. var capPath = function (shapePath) {
  55069. var pointCap = Array();
  55070. var barycenter = BABYLON.Vector3.Zero();
  55071. var i;
  55072. for (i = 0; i < shapePath.length; i++) {
  55073. barycenter.addInPlace(shapePath[i]);
  55074. }
  55075. barycenter.scaleInPlace(1.0 / shapePath.length);
  55076. for (i = 0; i < shapePath.length; i++) {
  55077. pointCap.push(barycenter);
  55078. }
  55079. return pointCap;
  55080. };
  55081. switch (cap) {
  55082. case BABYLON.Mesh.NO_CAP:
  55083. break;
  55084. case BABYLON.Mesh.CAP_START:
  55085. shapePaths[0] = capPath(shapePaths[2]);
  55086. shapePaths[1] = shapePaths[2];
  55087. break;
  55088. case BABYLON.Mesh.CAP_END:
  55089. shapePaths[index] = shapePaths[index - 1];
  55090. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  55091. break;
  55092. case BABYLON.Mesh.CAP_ALL:
  55093. shapePaths[0] = capPath(shapePaths[2]);
  55094. shapePaths[1] = shapePaths[2];
  55095. shapePaths[index] = shapePaths[index - 1];
  55096. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  55097. break;
  55098. default:
  55099. break;
  55100. }
  55101. return shapePaths;
  55102. };
  55103. var path3D;
  55104. var pathArray;
  55105. if (instance) {
  55106. path3D = (instance.path3D).update(curve);
  55107. pathArray = extrusionPathArray(shape, curve, instance.path3D, instance.pathArray, scale, rotation, scaleFunction, rotateFunction, instance.cap, custom);
  55108. instance = BABYLON.Mesh.CreateRibbon("", pathArray, false, false, 0, scene || undefined, false, 0, instance);
  55109. return instance;
  55110. }
  55111. // extruded shape creation
  55112. path3D = new BABYLON.Path3D(curve);
  55113. var newShapePaths = new Array();
  55114. cap = (cap < 0 || cap > 3) ? 0 : cap;
  55115. pathArray = extrusionPathArray(shape, curve, path3D, newShapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom);
  55116. var extrudedGeneric = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closeArray: rbCA, closePath: rbCP, updatable: updtbl, sideOrientation: side, invertUV: invertUV, frontUVs: frontUVs || undefined, backUVs: backUVs || undefined }, scene);
  55117. extrudedGeneric.pathArray = pathArray;
  55118. extrudedGeneric.path3D = path3D;
  55119. extrudedGeneric.cap = cap;
  55120. return extrudedGeneric;
  55121. };
  55122. return MeshBuilder;
  55123. }());
  55124. BABYLON.MeshBuilder = MeshBuilder;
  55125. })(BABYLON || (BABYLON = {}));
  55126. //# sourceMappingURL=babylon.meshBuilder.js.map
  55127. var BABYLON;
  55128. (function (BABYLON) {
  55129. var AudioEngine = /** @class */ (function () {
  55130. function AudioEngine() {
  55131. this._audioContext = null;
  55132. this._audioContextInitialized = false;
  55133. this.canUseWebAudio = false;
  55134. this.WarnedWebAudioUnsupported = false;
  55135. this.unlocked = false;
  55136. this.isMP3supported = false;
  55137. this.isOGGsupported = false;
  55138. if (typeof window.AudioContext !== 'undefined' || typeof window.webkitAudioContext !== 'undefined') {
  55139. window.AudioContext = window.AudioContext || window.webkitAudioContext;
  55140. this.canUseWebAudio = true;
  55141. }
  55142. var audioElem = document.createElement('audio');
  55143. try {
  55144. if (audioElem && !!audioElem.canPlayType && audioElem.canPlayType('audio/mpeg; codecs="mp3"').replace(/^no$/, '')) {
  55145. this.isMP3supported = true;
  55146. }
  55147. }
  55148. catch (e) {
  55149. // protect error during capability check.
  55150. }
  55151. try {
  55152. if (audioElem && !!audioElem.canPlayType && audioElem.canPlayType('audio/ogg; codecs="vorbis"').replace(/^no$/, '')) {
  55153. this.isOGGsupported = true;
  55154. }
  55155. }
  55156. catch (e) {
  55157. // protect error during capability check.
  55158. }
  55159. if (/iPad|iPhone|iPod/.test(navigator.platform)) {
  55160. this._unlockiOSaudio();
  55161. }
  55162. else {
  55163. this.unlocked = true;
  55164. }
  55165. }
  55166. Object.defineProperty(AudioEngine.prototype, "audioContext", {
  55167. get: function () {
  55168. if (!this._audioContextInitialized) {
  55169. this._initializeAudioContext();
  55170. }
  55171. return this._audioContext;
  55172. },
  55173. enumerable: true,
  55174. configurable: true
  55175. });
  55176. AudioEngine.prototype._unlockiOSaudio = function () {
  55177. var _this = this;
  55178. var unlockaudio = function () {
  55179. if (!_this.audioContext) {
  55180. return;
  55181. }
  55182. var buffer = _this.audioContext.createBuffer(1, 1, 22050);
  55183. var source = _this.audioContext.createBufferSource();
  55184. source.buffer = buffer;
  55185. source.connect(_this.audioContext.destination);
  55186. source.start(0);
  55187. setTimeout(function () {
  55188. if ((source.playbackState === source.PLAYING_STATE || source.playbackState === source.FINISHED_STATE)) {
  55189. _this.unlocked = true;
  55190. window.removeEventListener('touchend', unlockaudio, false);
  55191. if (_this.onAudioUnlocked) {
  55192. _this.onAudioUnlocked();
  55193. }
  55194. }
  55195. }, 0);
  55196. };
  55197. window.addEventListener('touchend', unlockaudio, false);
  55198. };
  55199. AudioEngine.prototype._initializeAudioContext = function () {
  55200. try {
  55201. if (this.canUseWebAudio) {
  55202. this._audioContext = new AudioContext();
  55203. // create a global volume gain node
  55204. this.masterGain = this._audioContext.createGain();
  55205. this.masterGain.gain.value = 1;
  55206. this.masterGain.connect(this._audioContext.destination);
  55207. this._audioContextInitialized = true;
  55208. }
  55209. }
  55210. catch (e) {
  55211. this.canUseWebAudio = false;
  55212. BABYLON.Tools.Error("Web Audio: " + e.message);
  55213. }
  55214. };
  55215. AudioEngine.prototype.dispose = function () {
  55216. if (this.canUseWebAudio && this._audioContextInitialized) {
  55217. if (this._connectedAnalyser && this._audioContext) {
  55218. this._connectedAnalyser.stopDebugCanvas();
  55219. this._connectedAnalyser.dispose();
  55220. this.masterGain.disconnect();
  55221. this.masterGain.connect(this._audioContext.destination);
  55222. this._connectedAnalyser = null;
  55223. }
  55224. this.masterGain.gain.value = 1;
  55225. }
  55226. this.WarnedWebAudioUnsupported = false;
  55227. };
  55228. AudioEngine.prototype.getGlobalVolume = function () {
  55229. if (this.canUseWebAudio && this._audioContextInitialized) {
  55230. return this.masterGain.gain.value;
  55231. }
  55232. else {
  55233. return -1;
  55234. }
  55235. };
  55236. AudioEngine.prototype.setGlobalVolume = function (newVolume) {
  55237. if (this.canUseWebAudio && this._audioContextInitialized) {
  55238. this.masterGain.gain.value = newVolume;
  55239. }
  55240. };
  55241. AudioEngine.prototype.connectToAnalyser = function (analyser) {
  55242. if (this._connectedAnalyser) {
  55243. this._connectedAnalyser.stopDebugCanvas();
  55244. }
  55245. if (this.canUseWebAudio && this._audioContextInitialized && this._audioContext) {
  55246. this._connectedAnalyser = analyser;
  55247. this.masterGain.disconnect();
  55248. this._connectedAnalyser.connectAudioNodes(this.masterGain, this._audioContext.destination);
  55249. }
  55250. };
  55251. return AudioEngine;
  55252. }());
  55253. BABYLON.AudioEngine = AudioEngine;
  55254. })(BABYLON || (BABYLON = {}));
  55255. //# sourceMappingURL=babylon.audioEngine.js.map
  55256. var BABYLON;
  55257. (function (BABYLON) {
  55258. var Sound = /** @class */ (function () {
  55259. /**
  55260. * Create a sound and attach it to a scene
  55261. * @param name Name of your sound
  55262. * @param urlOrArrayBuffer Url to the sound to load async or ArrayBuffer
  55263. * @param readyToPlayCallback Provide a callback function if you'd like to load your code once the sound is ready to be played
  55264. * @param options Objects to provide with the current available options: autoplay, loop, volume, spatialSound, maxDistance, rolloffFactor, refDistance, distanceModel, panningModel, streaming
  55265. */
  55266. function Sound(name, urlOrArrayBuffer, scene, readyToPlayCallback, options) {
  55267. if (readyToPlayCallback === void 0) { readyToPlayCallback = null; }
  55268. var _this = this;
  55269. this.autoplay = false;
  55270. this.loop = false;
  55271. this.useCustomAttenuation = false;
  55272. this.spatialSound = false;
  55273. this.refDistance = 1;
  55274. this.rolloffFactor = 1;
  55275. this.maxDistance = 100;
  55276. this.distanceModel = "linear";
  55277. this._panningModel = "equalpower";
  55278. this._playbackRate = 1;
  55279. this._streaming = false;
  55280. this._startTime = 0;
  55281. this._startOffset = 0;
  55282. this._position = BABYLON.Vector3.Zero();
  55283. this._localDirection = new BABYLON.Vector3(1, 0, 0);
  55284. this._volume = 1;
  55285. this._isReadyToPlay = false;
  55286. this.isPlaying = false;
  55287. this.isPaused = false;
  55288. this._isDirectional = false;
  55289. // Used if you'd like to create a directional sound.
  55290. // If not set, the sound will be omnidirectional
  55291. this._coneInnerAngle = 360;
  55292. this._coneOuterAngle = 360;
  55293. this._coneOuterGain = 0;
  55294. this._isOutputConnected = false;
  55295. this._urlType = "Unknown";
  55296. this.name = name;
  55297. this._scene = scene;
  55298. this._readyToPlayCallback = readyToPlayCallback;
  55299. // Default custom attenuation function is a linear attenuation
  55300. this._customAttenuationFunction = function (currentVolume, currentDistance, maxDistance, refDistance, rolloffFactor) {
  55301. if (currentDistance < maxDistance) {
  55302. return currentVolume * (1 - currentDistance / maxDistance);
  55303. }
  55304. else {
  55305. return 0;
  55306. }
  55307. };
  55308. if (options) {
  55309. this.autoplay = options.autoplay || false;
  55310. this.loop = options.loop || false;
  55311. // if volume === 0, we need another way to check this option
  55312. if (options.volume !== undefined) {
  55313. this._volume = options.volume;
  55314. }
  55315. this.spatialSound = options.spatialSound || false;
  55316. this.maxDistance = options.maxDistance || 100;
  55317. this.useCustomAttenuation = options.useCustomAttenuation || false;
  55318. this.rolloffFactor = options.rolloffFactor || 1;
  55319. this.refDistance = options.refDistance || 1;
  55320. this.distanceModel = options.distanceModel || "linear";
  55321. this._playbackRate = options.playbackRate || 1;
  55322. this._streaming = options.streaming || false;
  55323. }
  55324. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  55325. this._soundGain = BABYLON.Engine.audioEngine.audioContext.createGain();
  55326. this._soundGain.gain.value = this._volume;
  55327. this._inputAudioNode = this._soundGain;
  55328. this._ouputAudioNode = this._soundGain;
  55329. if (this.spatialSound) {
  55330. this._createSpatialParameters();
  55331. }
  55332. this._scene.mainSoundTrack.AddSound(this);
  55333. var validParameter = true;
  55334. // if no parameter is passed, you need to call setAudioBuffer yourself to prepare the sound
  55335. if (urlOrArrayBuffer) {
  55336. if (typeof (urlOrArrayBuffer) === "string")
  55337. this._urlType = "String";
  55338. if (Array.isArray(urlOrArrayBuffer))
  55339. this._urlType = "Array";
  55340. if (urlOrArrayBuffer instanceof ArrayBuffer)
  55341. this._urlType = "ArrayBuffer";
  55342. var urls = [];
  55343. var codecSupportedFound = false;
  55344. switch (this._urlType) {
  55345. case "ArrayBuffer":
  55346. if (urlOrArrayBuffer.byteLength > 0) {
  55347. codecSupportedFound = true;
  55348. this._soundLoaded(urlOrArrayBuffer);
  55349. }
  55350. break;
  55351. case "String":
  55352. urls.push(urlOrArrayBuffer);
  55353. case "Array":
  55354. if (urls.length === 0)
  55355. urls = urlOrArrayBuffer;
  55356. // If we found a supported format, we load it immediately and stop the loop
  55357. for (var i = 0; i < urls.length; i++) {
  55358. var url = urls[i];
  55359. if (url.indexOf(".mp3", url.length - 4) !== -1 && BABYLON.Engine.audioEngine.isMP3supported) {
  55360. codecSupportedFound = true;
  55361. }
  55362. if (url.indexOf(".ogg", url.length - 4) !== -1 && BABYLON.Engine.audioEngine.isOGGsupported) {
  55363. codecSupportedFound = true;
  55364. }
  55365. if (url.indexOf(".wav", url.length - 4) !== -1) {
  55366. codecSupportedFound = true;
  55367. }
  55368. if (url.indexOf("blob:") !== -1) {
  55369. codecSupportedFound = true;
  55370. }
  55371. if (codecSupportedFound) {
  55372. // Loading sound using XHR2
  55373. if (!this._streaming) {
  55374. this._scene._loadFile(url, function (data) { _this._soundLoaded(data); }, undefined, true, true);
  55375. }
  55376. else {
  55377. this._htmlAudioElement = new Audio(url);
  55378. this._htmlAudioElement.controls = false;
  55379. this._htmlAudioElement.loop = this.loop;
  55380. BABYLON.Tools.SetCorsBehavior(url, this._htmlAudioElement);
  55381. this._htmlAudioElement.preload = "auto";
  55382. this._htmlAudioElement.addEventListener("canplaythrough", function () {
  55383. _this._isReadyToPlay = true;
  55384. if (_this.autoplay) {
  55385. _this.play();
  55386. }
  55387. if (_this._readyToPlayCallback) {
  55388. _this._readyToPlayCallback();
  55389. }
  55390. });
  55391. document.body.appendChild(this._htmlAudioElement);
  55392. }
  55393. break;
  55394. }
  55395. }
  55396. break;
  55397. default:
  55398. validParameter = false;
  55399. break;
  55400. }
  55401. if (!validParameter) {
  55402. BABYLON.Tools.Error("Parameter must be a URL to the sound, an Array of URLs (.mp3 & .ogg) or an ArrayBuffer of the sound.");
  55403. }
  55404. else {
  55405. if (!codecSupportedFound) {
  55406. this._isReadyToPlay = true;
  55407. // Simulating a ready to play event to avoid breaking code path
  55408. if (this._readyToPlayCallback) {
  55409. window.setTimeout(function () {
  55410. if (_this._readyToPlayCallback) {
  55411. _this._readyToPlayCallback();
  55412. }
  55413. }, 1000);
  55414. }
  55415. }
  55416. }
  55417. }
  55418. }
  55419. else {
  55420. // Adding an empty sound to avoid breaking audio calls for non Web Audio browsers
  55421. this._scene.mainSoundTrack.AddSound(this);
  55422. if (!BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported) {
  55423. BABYLON.Tools.Error("Web Audio is not supported by your browser.");
  55424. BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported = true;
  55425. }
  55426. // Simulating a ready to play event to avoid breaking code for non web audio browsers
  55427. if (this._readyToPlayCallback) {
  55428. window.setTimeout(function () {
  55429. if (_this._readyToPlayCallback) {
  55430. _this._readyToPlayCallback();
  55431. }
  55432. }, 1000);
  55433. }
  55434. }
  55435. }
  55436. Sound.prototype.dispose = function () {
  55437. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isReadyToPlay) {
  55438. if (this.isPlaying) {
  55439. this.stop();
  55440. }
  55441. this._isReadyToPlay = false;
  55442. if (this.soundTrackId === -1) {
  55443. this._scene.mainSoundTrack.RemoveSound(this);
  55444. }
  55445. else {
  55446. this._scene.soundTracks[this.soundTrackId].RemoveSound(this);
  55447. }
  55448. if (this._soundGain) {
  55449. this._soundGain.disconnect();
  55450. this._soundGain = null;
  55451. }
  55452. if (this._soundPanner) {
  55453. this._soundPanner.disconnect();
  55454. this._soundPanner = null;
  55455. }
  55456. if (this._soundSource) {
  55457. this._soundSource.disconnect();
  55458. this._soundSource = null;
  55459. }
  55460. this._audioBuffer = null;
  55461. if (this._htmlAudioElement) {
  55462. this._htmlAudioElement.pause();
  55463. this._htmlAudioElement.src = "";
  55464. document.body.removeChild(this._htmlAudioElement);
  55465. }
  55466. if (this._connectedMesh && this._registerFunc) {
  55467. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  55468. this._connectedMesh = null;
  55469. }
  55470. }
  55471. };
  55472. Sound.prototype.isReady = function () {
  55473. return this._isReadyToPlay;
  55474. };
  55475. Sound.prototype._soundLoaded = function (audioData) {
  55476. var _this = this;
  55477. if (!BABYLON.Engine.audioEngine.audioContext) {
  55478. return;
  55479. }
  55480. BABYLON.Engine.audioEngine.audioContext.decodeAudioData(audioData, function (buffer) {
  55481. _this._audioBuffer = buffer;
  55482. _this._isReadyToPlay = true;
  55483. if (_this.autoplay) {
  55484. _this.play();
  55485. }
  55486. if (_this._readyToPlayCallback) {
  55487. _this._readyToPlayCallback();
  55488. }
  55489. }, function (err) { BABYLON.Tools.Error("Error while decoding audio data for: " + _this.name + " / Error: " + err); });
  55490. };
  55491. Sound.prototype.setAudioBuffer = function (audioBuffer) {
  55492. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  55493. this._audioBuffer = audioBuffer;
  55494. this._isReadyToPlay = true;
  55495. }
  55496. };
  55497. Sound.prototype.updateOptions = function (options) {
  55498. if (options) {
  55499. this.loop = options.loop || this.loop;
  55500. this.maxDistance = options.maxDistance || this.maxDistance;
  55501. this.useCustomAttenuation = options.useCustomAttenuation || this.useCustomAttenuation;
  55502. this.rolloffFactor = options.rolloffFactor || this.rolloffFactor;
  55503. this.refDistance = options.refDistance || this.refDistance;
  55504. this.distanceModel = options.distanceModel || this.distanceModel;
  55505. this._playbackRate = options.playbackRate || this._playbackRate;
  55506. this._updateSpatialParameters();
  55507. if (this.isPlaying) {
  55508. if (this._streaming) {
  55509. this._htmlAudioElement.playbackRate = this._playbackRate;
  55510. }
  55511. else {
  55512. if (this._soundSource) {
  55513. this._soundSource.playbackRate.value = this._playbackRate;
  55514. }
  55515. }
  55516. }
  55517. }
  55518. };
  55519. Sound.prototype._createSpatialParameters = function () {
  55520. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  55521. if (this._scene.headphone) {
  55522. this._panningModel = "HRTF";
  55523. }
  55524. this._soundPanner = BABYLON.Engine.audioEngine.audioContext.createPanner();
  55525. this._updateSpatialParameters();
  55526. this._soundPanner.connect(this._ouputAudioNode);
  55527. this._inputAudioNode = this._soundPanner;
  55528. }
  55529. };
  55530. Sound.prototype._updateSpatialParameters = function () {
  55531. if (this.spatialSound && this._soundPanner) {
  55532. if (this.useCustomAttenuation) {
  55533. // Tricks to disable in a way embedded Web Audio attenuation
  55534. this._soundPanner.distanceModel = "linear";
  55535. this._soundPanner.maxDistance = Number.MAX_VALUE;
  55536. this._soundPanner.refDistance = 1;
  55537. this._soundPanner.rolloffFactor = 1;
  55538. this._soundPanner.panningModel = this._panningModel;
  55539. }
  55540. else {
  55541. this._soundPanner.distanceModel = this.distanceModel;
  55542. this._soundPanner.maxDistance = this.maxDistance;
  55543. this._soundPanner.refDistance = this.refDistance;
  55544. this._soundPanner.rolloffFactor = this.rolloffFactor;
  55545. this._soundPanner.panningModel = this._panningModel;
  55546. }
  55547. }
  55548. };
  55549. Sound.prototype.switchPanningModelToHRTF = function () {
  55550. this._panningModel = "HRTF";
  55551. this._switchPanningModel();
  55552. };
  55553. Sound.prototype.switchPanningModelToEqualPower = function () {
  55554. this._panningModel = "equalpower";
  55555. this._switchPanningModel();
  55556. };
  55557. Sound.prototype._switchPanningModel = function () {
  55558. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound && this._soundPanner) {
  55559. this._soundPanner.panningModel = this._panningModel;
  55560. }
  55561. };
  55562. Sound.prototype.connectToSoundTrackAudioNode = function (soundTrackAudioNode) {
  55563. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  55564. if (this._isOutputConnected) {
  55565. this._ouputAudioNode.disconnect();
  55566. }
  55567. this._ouputAudioNode.connect(soundTrackAudioNode);
  55568. this._isOutputConnected = true;
  55569. }
  55570. };
  55571. /**
  55572. * Transform this sound into a directional source
  55573. * @param coneInnerAngle Size of the inner cone in degree
  55574. * @param coneOuterAngle Size of the outer cone in degree
  55575. * @param coneOuterGain Volume of the sound outside the outer cone (between 0.0 and 1.0)
  55576. */
  55577. Sound.prototype.setDirectionalCone = function (coneInnerAngle, coneOuterAngle, coneOuterGain) {
  55578. if (coneOuterAngle < coneInnerAngle) {
  55579. BABYLON.Tools.Error("setDirectionalCone(): outer angle of the cone must be superior or equal to the inner angle.");
  55580. return;
  55581. }
  55582. this._coneInnerAngle = coneInnerAngle;
  55583. this._coneOuterAngle = coneOuterAngle;
  55584. this._coneOuterGain = coneOuterGain;
  55585. this._isDirectional = true;
  55586. if (this.isPlaying && this.loop) {
  55587. this.stop();
  55588. this.play();
  55589. }
  55590. };
  55591. Sound.prototype.setPosition = function (newPosition) {
  55592. this._position = newPosition;
  55593. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound && this._soundPanner) {
  55594. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  55595. }
  55596. };
  55597. Sound.prototype.setLocalDirectionToMesh = function (newLocalDirection) {
  55598. this._localDirection = newLocalDirection;
  55599. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.isPlaying) {
  55600. this._updateDirection();
  55601. }
  55602. };
  55603. Sound.prototype._updateDirection = function () {
  55604. if (!this._connectedMesh || !this._soundPanner) {
  55605. return;
  55606. }
  55607. var mat = this._connectedMesh.getWorldMatrix();
  55608. var direction = BABYLON.Vector3.TransformNormal(this._localDirection, mat);
  55609. direction.normalize();
  55610. this._soundPanner.setOrientation(direction.x, direction.y, direction.z);
  55611. };
  55612. Sound.prototype.updateDistanceFromListener = function () {
  55613. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.useCustomAttenuation && this._soundGain && this._scene.activeCamera) {
  55614. var distance = this._connectedMesh.getDistanceToCamera(this._scene.activeCamera);
  55615. this._soundGain.gain.value = this._customAttenuationFunction(this._volume, distance, this.maxDistance, this.refDistance, this.rolloffFactor);
  55616. }
  55617. };
  55618. Sound.prototype.setAttenuationFunction = function (callback) {
  55619. this._customAttenuationFunction = callback;
  55620. };
  55621. /**
  55622. * Play the sound
  55623. * @param time (optional) Start the sound after X seconds. Start immediately (0) by default.
  55624. * @param offset (optional) Start the sound setting it at a specific time
  55625. */
  55626. Sound.prototype.play = function (time, offset) {
  55627. var _this = this;
  55628. if (this._isReadyToPlay && this._scene.audioEnabled && BABYLON.Engine.audioEngine.audioContext) {
  55629. try {
  55630. if (this._startOffset < 0) {
  55631. time = -this._startOffset;
  55632. this._startOffset = 0;
  55633. }
  55634. var startTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  55635. if (!this._soundSource || !this._streamingSource) {
  55636. if (this.spatialSound && this._soundPanner) {
  55637. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  55638. if (this._isDirectional) {
  55639. this._soundPanner.coneInnerAngle = this._coneInnerAngle;
  55640. this._soundPanner.coneOuterAngle = this._coneOuterAngle;
  55641. this._soundPanner.coneOuterGain = this._coneOuterGain;
  55642. if (this._connectedMesh) {
  55643. this._updateDirection();
  55644. }
  55645. else {
  55646. this._soundPanner.setOrientation(this._localDirection.x, this._localDirection.y, this._localDirection.z);
  55647. }
  55648. }
  55649. }
  55650. }
  55651. if (this._streaming) {
  55652. if (!this._streamingSource) {
  55653. this._streamingSource = BABYLON.Engine.audioEngine.audioContext.createMediaElementSource(this._htmlAudioElement);
  55654. this._htmlAudioElement.onended = function () { _this._onended(); };
  55655. this._htmlAudioElement.playbackRate = this._playbackRate;
  55656. }
  55657. this._streamingSource.disconnect();
  55658. this._streamingSource.connect(this._inputAudioNode);
  55659. this._htmlAudioElement.play();
  55660. }
  55661. else {
  55662. this._soundSource = BABYLON.Engine.audioEngine.audioContext.createBufferSource();
  55663. this._soundSource.buffer = this._audioBuffer;
  55664. this._soundSource.connect(this._inputAudioNode);
  55665. this._soundSource.loop = this.loop;
  55666. this._soundSource.playbackRate.value = this._playbackRate;
  55667. this._soundSource.onended = function () { _this._onended(); };
  55668. if (this._soundSource.buffer) {
  55669. this._soundSource.start(startTime, this.isPaused ? this._startOffset % this._soundSource.buffer.duration : offset ? offset : 0);
  55670. }
  55671. }
  55672. this._startTime = startTime;
  55673. this.isPlaying = true;
  55674. this.isPaused = false;
  55675. }
  55676. catch (ex) {
  55677. BABYLON.Tools.Error("Error while trying to play audio: " + this.name + ", " + ex.message);
  55678. }
  55679. }
  55680. };
  55681. Sound.prototype._onended = function () {
  55682. this.isPlaying = false;
  55683. if (this.onended) {
  55684. this.onended();
  55685. }
  55686. };
  55687. /**
  55688. * Stop the sound
  55689. * @param time (optional) Stop the sound after X seconds. Stop immediately (0) by default.
  55690. */
  55691. Sound.prototype.stop = function (time) {
  55692. if (this.isPlaying) {
  55693. if (this._streaming) {
  55694. this._htmlAudioElement.pause();
  55695. // Test needed for Firefox or it will generate an Invalid State Error
  55696. if (this._htmlAudioElement.currentTime > 0) {
  55697. this._htmlAudioElement.currentTime = 0;
  55698. }
  55699. }
  55700. else if (BABYLON.Engine.audioEngine.audioContext && this._soundSource) {
  55701. var stopTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  55702. this._soundSource.stop(stopTime);
  55703. this._soundSource.onended = function () { };
  55704. if (!this.isPaused) {
  55705. this._startOffset = 0;
  55706. }
  55707. }
  55708. this.isPlaying = false;
  55709. }
  55710. };
  55711. Sound.prototype.pause = function () {
  55712. if (this.isPlaying) {
  55713. this.isPaused = true;
  55714. if (this._streaming) {
  55715. this._htmlAudioElement.pause();
  55716. }
  55717. else if (BABYLON.Engine.audioEngine.audioContext) {
  55718. this.stop(0);
  55719. this._startOffset += BABYLON.Engine.audioEngine.audioContext.currentTime - this._startTime;
  55720. }
  55721. }
  55722. };
  55723. Sound.prototype.setVolume = function (newVolume, time) {
  55724. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._soundGain) {
  55725. if (time && BABYLON.Engine.audioEngine.audioContext) {
  55726. this._soundGain.gain.cancelScheduledValues(BABYLON.Engine.audioEngine.audioContext.currentTime);
  55727. this._soundGain.gain.setValueAtTime(this._soundGain.gain.value, BABYLON.Engine.audioEngine.audioContext.currentTime);
  55728. this._soundGain.gain.linearRampToValueAtTime(newVolume, BABYLON.Engine.audioEngine.audioContext.currentTime + time);
  55729. }
  55730. else {
  55731. this._soundGain.gain.value = newVolume;
  55732. }
  55733. }
  55734. this._volume = newVolume;
  55735. };
  55736. Sound.prototype.setPlaybackRate = function (newPlaybackRate) {
  55737. this._playbackRate = newPlaybackRate;
  55738. if (this.isPlaying) {
  55739. if (this._streaming) {
  55740. this._htmlAudioElement.playbackRate = this._playbackRate;
  55741. }
  55742. else if (this._soundSource) {
  55743. this._soundSource.playbackRate.value = this._playbackRate;
  55744. }
  55745. }
  55746. };
  55747. Sound.prototype.getVolume = function () {
  55748. return this._volume;
  55749. };
  55750. Sound.prototype.attachToMesh = function (meshToConnectTo) {
  55751. var _this = this;
  55752. if (this._connectedMesh && this._registerFunc) {
  55753. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  55754. this._registerFunc = null;
  55755. }
  55756. this._connectedMesh = meshToConnectTo;
  55757. if (!this.spatialSound) {
  55758. this.spatialSound = true;
  55759. this._createSpatialParameters();
  55760. if (this.isPlaying && this.loop) {
  55761. this.stop();
  55762. this.play();
  55763. }
  55764. }
  55765. this._onRegisterAfterWorldMatrixUpdate(this._connectedMesh);
  55766. this._registerFunc = function (connectedMesh) { return _this._onRegisterAfterWorldMatrixUpdate(connectedMesh); };
  55767. meshToConnectTo.registerAfterWorldMatrixUpdate(this._registerFunc);
  55768. };
  55769. Sound.prototype.detachFromMesh = function () {
  55770. if (this._connectedMesh && this._registerFunc) {
  55771. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  55772. this._registerFunc = null;
  55773. this._connectedMesh = null;
  55774. }
  55775. };
  55776. Sound.prototype._onRegisterAfterWorldMatrixUpdate = function (node) {
  55777. if (!node.getBoundingInfo) {
  55778. return;
  55779. }
  55780. var mesh = node;
  55781. var boundingInfo = mesh.getBoundingInfo();
  55782. this.setPosition(boundingInfo.boundingSphere.centerWorld);
  55783. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isDirectional && this.isPlaying) {
  55784. this._updateDirection();
  55785. }
  55786. };
  55787. Sound.prototype.clone = function () {
  55788. var _this = this;
  55789. if (!this._streaming) {
  55790. var setBufferAndRun = function () {
  55791. if (_this._isReadyToPlay) {
  55792. clonedSound._audioBuffer = _this.getAudioBuffer();
  55793. clonedSound._isReadyToPlay = true;
  55794. if (clonedSound.autoplay) {
  55795. clonedSound.play();
  55796. }
  55797. }
  55798. else {
  55799. window.setTimeout(setBufferAndRun, 300);
  55800. }
  55801. };
  55802. var currentOptions = {
  55803. autoplay: this.autoplay, loop: this.loop,
  55804. volume: this._volume, spatialSound: this.spatialSound, maxDistance: this.maxDistance,
  55805. useCustomAttenuation: this.useCustomAttenuation, rolloffFactor: this.rolloffFactor,
  55806. refDistance: this.refDistance, distanceModel: this.distanceModel
  55807. };
  55808. var clonedSound = new Sound(this.name + "_cloned", new ArrayBuffer(0), this._scene, null, currentOptions);
  55809. if (this.useCustomAttenuation) {
  55810. clonedSound.setAttenuationFunction(this._customAttenuationFunction);
  55811. }
  55812. clonedSound.setPosition(this._position);
  55813. clonedSound.setPlaybackRate(this._playbackRate);
  55814. setBufferAndRun();
  55815. return clonedSound;
  55816. }
  55817. else {
  55818. return null;
  55819. }
  55820. };
  55821. Sound.prototype.getAudioBuffer = function () {
  55822. return this._audioBuffer;
  55823. };
  55824. Sound.prototype.serialize = function () {
  55825. var serializationObject = {
  55826. name: this.name,
  55827. url: this.name,
  55828. autoplay: this.autoplay,
  55829. loop: this.loop,
  55830. volume: this._volume,
  55831. spatialSound: this.spatialSound,
  55832. maxDistance: this.maxDistance,
  55833. rolloffFactor: this.rolloffFactor,
  55834. refDistance: this.refDistance,
  55835. distanceModel: this.distanceModel,
  55836. playbackRate: this._playbackRate,
  55837. panningModel: this._panningModel,
  55838. soundTrackId: this.soundTrackId
  55839. };
  55840. if (this.spatialSound) {
  55841. if (this._connectedMesh)
  55842. serializationObject.connectedMeshId = this._connectedMesh.id;
  55843. serializationObject.position = this._position.asArray();
  55844. serializationObject.refDistance = this.refDistance;
  55845. serializationObject.distanceModel = this.distanceModel;
  55846. serializationObject.isDirectional = this._isDirectional;
  55847. serializationObject.localDirectionToMesh = this._localDirection.asArray();
  55848. serializationObject.coneInnerAngle = this._coneInnerAngle;
  55849. serializationObject.coneOuterAngle = this._coneOuterAngle;
  55850. serializationObject.coneOuterGain = this._coneOuterGain;
  55851. }
  55852. return serializationObject;
  55853. };
  55854. Sound.Parse = function (parsedSound, scene, rootUrl, sourceSound) {
  55855. var soundName = parsedSound.name;
  55856. var soundUrl;
  55857. if (parsedSound.url) {
  55858. soundUrl = rootUrl + parsedSound.url;
  55859. }
  55860. else {
  55861. soundUrl = rootUrl + soundName;
  55862. }
  55863. var options = {
  55864. autoplay: parsedSound.autoplay, loop: parsedSound.loop, volume: parsedSound.volume,
  55865. spatialSound: parsedSound.spatialSound, maxDistance: parsedSound.maxDistance,
  55866. rolloffFactor: parsedSound.rolloffFactor,
  55867. refDistance: parsedSound.refDistance,
  55868. distanceModel: parsedSound.distanceModel,
  55869. playbackRate: parsedSound.playbackRate
  55870. };
  55871. var newSound;
  55872. if (!sourceSound) {
  55873. newSound = new Sound(soundName, soundUrl, scene, function () { scene._removePendingData(newSound); }, options);
  55874. scene._addPendingData(newSound);
  55875. }
  55876. else {
  55877. var setBufferAndRun = function () {
  55878. if (sourceSound._isReadyToPlay) {
  55879. newSound._audioBuffer = sourceSound.getAudioBuffer();
  55880. newSound._isReadyToPlay = true;
  55881. if (newSound.autoplay) {
  55882. newSound.play();
  55883. }
  55884. }
  55885. else {
  55886. window.setTimeout(setBufferAndRun, 300);
  55887. }
  55888. };
  55889. newSound = new Sound(soundName, new ArrayBuffer(0), scene, null, options);
  55890. setBufferAndRun();
  55891. }
  55892. if (parsedSound.position) {
  55893. var soundPosition = BABYLON.Vector3.FromArray(parsedSound.position);
  55894. newSound.setPosition(soundPosition);
  55895. }
  55896. if (parsedSound.isDirectional) {
  55897. newSound.setDirectionalCone(parsedSound.coneInnerAngle || 360, parsedSound.coneOuterAngle || 360, parsedSound.coneOuterGain || 0);
  55898. if (parsedSound.localDirectionToMesh) {
  55899. var localDirectionToMesh = BABYLON.Vector3.FromArray(parsedSound.localDirectionToMesh);
  55900. newSound.setLocalDirectionToMesh(localDirectionToMesh);
  55901. }
  55902. }
  55903. if (parsedSound.connectedMeshId) {
  55904. var connectedMesh = scene.getMeshByID(parsedSound.connectedMeshId);
  55905. if (connectedMesh) {
  55906. newSound.attachToMesh(connectedMesh);
  55907. }
  55908. }
  55909. return newSound;
  55910. };
  55911. return Sound;
  55912. }());
  55913. BABYLON.Sound = Sound;
  55914. })(BABYLON || (BABYLON = {}));
  55915. //# sourceMappingURL=babylon.sound.js.map
  55916. var BABYLON;
  55917. (function (BABYLON) {
  55918. var SoundTrack = /** @class */ (function () {
  55919. function SoundTrack(scene, options) {
  55920. this.id = -1;
  55921. this._isMainTrack = false;
  55922. this._isInitialized = false;
  55923. this._scene = scene;
  55924. this.soundCollection = new Array();
  55925. this._options = options;
  55926. if (!this._isMainTrack) {
  55927. this._scene.soundTracks.push(this);
  55928. this.id = this._scene.soundTracks.length - 1;
  55929. }
  55930. }
  55931. SoundTrack.prototype._initializeSoundTrackAudioGraph = function () {
  55932. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  55933. this._outputAudioNode = BABYLON.Engine.audioEngine.audioContext.createGain();
  55934. this._outputAudioNode.connect(BABYLON.Engine.audioEngine.masterGain);
  55935. if (this._options) {
  55936. if (this._options.volume) {
  55937. this._outputAudioNode.gain.value = this._options.volume;
  55938. }
  55939. if (this._options.mainTrack) {
  55940. this._isMainTrack = this._options.mainTrack;
  55941. }
  55942. }
  55943. this._isInitialized = true;
  55944. }
  55945. };
  55946. SoundTrack.prototype.dispose = function () {
  55947. if (BABYLON.Engine.audioEngine && BABYLON.Engine.audioEngine.canUseWebAudio) {
  55948. if (this._connectedAnalyser) {
  55949. this._connectedAnalyser.stopDebugCanvas();
  55950. }
  55951. while (this.soundCollection.length) {
  55952. this.soundCollection[0].dispose();
  55953. }
  55954. if (this._outputAudioNode) {
  55955. this._outputAudioNode.disconnect();
  55956. }
  55957. this._outputAudioNode = null;
  55958. }
  55959. };
  55960. SoundTrack.prototype.AddSound = function (sound) {
  55961. if (!this._isInitialized) {
  55962. this._initializeSoundTrackAudioGraph();
  55963. }
  55964. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  55965. sound.connectToSoundTrackAudioNode(this._outputAudioNode);
  55966. }
  55967. if (sound.soundTrackId) {
  55968. if (sound.soundTrackId === -1) {
  55969. this._scene.mainSoundTrack.RemoveSound(sound);
  55970. }
  55971. else {
  55972. this._scene.soundTracks[sound.soundTrackId].RemoveSound(sound);
  55973. }
  55974. }
  55975. this.soundCollection.push(sound);
  55976. sound.soundTrackId = this.id;
  55977. };
  55978. SoundTrack.prototype.RemoveSound = function (sound) {
  55979. var index = this.soundCollection.indexOf(sound);
  55980. if (index !== -1) {
  55981. this.soundCollection.splice(index, 1);
  55982. }
  55983. };
  55984. SoundTrack.prototype.setVolume = function (newVolume) {
  55985. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  55986. this._outputAudioNode.gain.value = newVolume;
  55987. }
  55988. };
  55989. SoundTrack.prototype.switchPanningModelToHRTF = function () {
  55990. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  55991. for (var i = 0; i < this.soundCollection.length; i++) {
  55992. this.soundCollection[i].switchPanningModelToHRTF();
  55993. }
  55994. }
  55995. };
  55996. SoundTrack.prototype.switchPanningModelToEqualPower = function () {
  55997. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  55998. for (var i = 0; i < this.soundCollection.length; i++) {
  55999. this.soundCollection[i].switchPanningModelToEqualPower();
  56000. }
  56001. }
  56002. };
  56003. SoundTrack.prototype.connectToAnalyser = function (analyser) {
  56004. if (this._connectedAnalyser) {
  56005. this._connectedAnalyser.stopDebugCanvas();
  56006. }
  56007. this._connectedAnalyser = analyser;
  56008. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  56009. this._outputAudioNode.disconnect();
  56010. this._connectedAnalyser.connectAudioNodes(this._outputAudioNode, BABYLON.Engine.audioEngine.masterGain);
  56011. }
  56012. };
  56013. return SoundTrack;
  56014. }());
  56015. BABYLON.SoundTrack = SoundTrack;
  56016. })(BABYLON || (BABYLON = {}));
  56017. //# sourceMappingURL=babylon.soundtrack.js.map
  56018. var BABYLON;
  56019. (function (BABYLON) {
  56020. var Analyser = /** @class */ (function () {
  56021. function Analyser(scene) {
  56022. this.SMOOTHING = 0.75;
  56023. this.FFT_SIZE = 512;
  56024. this.BARGRAPHAMPLITUDE = 256;
  56025. this.DEBUGCANVASPOS = { x: 20, y: 20 };
  56026. this.DEBUGCANVASSIZE = { width: 320, height: 200 };
  56027. this._scene = scene;
  56028. this._audioEngine = BABYLON.Engine.audioEngine;
  56029. if (this._audioEngine.canUseWebAudio && this._audioEngine.audioContext) {
  56030. this._webAudioAnalyser = this._audioEngine.audioContext.createAnalyser();
  56031. this._webAudioAnalyser.minDecibels = -140;
  56032. this._webAudioAnalyser.maxDecibels = 0;
  56033. this._byteFreqs = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  56034. this._byteTime = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  56035. this._floatFreqs = new Float32Array(this._webAudioAnalyser.frequencyBinCount);
  56036. }
  56037. }
  56038. Analyser.prototype.getFrequencyBinCount = function () {
  56039. if (this._audioEngine.canUseWebAudio) {
  56040. return this._webAudioAnalyser.frequencyBinCount;
  56041. }
  56042. else {
  56043. return 0;
  56044. }
  56045. };
  56046. Analyser.prototype.getByteFrequencyData = function () {
  56047. if (this._audioEngine.canUseWebAudio) {
  56048. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  56049. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  56050. this._webAudioAnalyser.getByteFrequencyData(this._byteFreqs);
  56051. }
  56052. return this._byteFreqs;
  56053. };
  56054. Analyser.prototype.getByteTimeDomainData = function () {
  56055. if (this._audioEngine.canUseWebAudio) {
  56056. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  56057. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  56058. this._webAudioAnalyser.getByteTimeDomainData(this._byteTime);
  56059. }
  56060. return this._byteTime;
  56061. };
  56062. Analyser.prototype.getFloatFrequencyData = function () {
  56063. if (this._audioEngine.canUseWebAudio) {
  56064. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  56065. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  56066. this._webAudioAnalyser.getFloatFrequencyData(this._floatFreqs);
  56067. }
  56068. return this._floatFreqs;
  56069. };
  56070. Analyser.prototype.drawDebugCanvas = function () {
  56071. var _this = this;
  56072. if (this._audioEngine.canUseWebAudio) {
  56073. if (!this._debugCanvas) {
  56074. this._debugCanvas = document.createElement("canvas");
  56075. this._debugCanvas.width = this.DEBUGCANVASSIZE.width;
  56076. this._debugCanvas.height = this.DEBUGCANVASSIZE.height;
  56077. this._debugCanvas.style.position = "absolute";
  56078. this._debugCanvas.style.top = this.DEBUGCANVASPOS.y + "px";
  56079. this._debugCanvas.style.left = this.DEBUGCANVASPOS.x + "px";
  56080. this._debugCanvasContext = this._debugCanvas.getContext("2d");
  56081. document.body.appendChild(this._debugCanvas);
  56082. this._registerFunc = function () {
  56083. _this.drawDebugCanvas();
  56084. };
  56085. this._scene.registerBeforeRender(this._registerFunc);
  56086. }
  56087. if (this._registerFunc && this._debugCanvasContext) {
  56088. var workingArray = this.getByteFrequencyData();
  56089. this._debugCanvasContext.fillStyle = 'rgb(0, 0, 0)';
  56090. this._debugCanvasContext.fillRect(0, 0, this.DEBUGCANVASSIZE.width, this.DEBUGCANVASSIZE.height);
  56091. // Draw the frequency domain chart.
  56092. for (var i = 0; i < this.getFrequencyBinCount(); i++) {
  56093. var value = workingArray[i];
  56094. var percent = value / this.BARGRAPHAMPLITUDE;
  56095. var height = this.DEBUGCANVASSIZE.height * percent;
  56096. var offset = this.DEBUGCANVASSIZE.height - height - 1;
  56097. var barWidth = this.DEBUGCANVASSIZE.width / this.getFrequencyBinCount();
  56098. var hue = i / this.getFrequencyBinCount() * 360;
  56099. this._debugCanvasContext.fillStyle = 'hsl(' + hue + ', 100%, 50%)';
  56100. this._debugCanvasContext.fillRect(i * barWidth, offset, barWidth, height);
  56101. }
  56102. }
  56103. }
  56104. };
  56105. Analyser.prototype.stopDebugCanvas = function () {
  56106. if (this._debugCanvas) {
  56107. if (this._registerFunc) {
  56108. this._scene.unregisterBeforeRender(this._registerFunc);
  56109. this._registerFunc = null;
  56110. }
  56111. document.body.removeChild(this._debugCanvas);
  56112. this._debugCanvas = null;
  56113. this._debugCanvasContext = null;
  56114. }
  56115. };
  56116. Analyser.prototype.connectAudioNodes = function (inputAudioNode, outputAudioNode) {
  56117. if (this._audioEngine.canUseWebAudio) {
  56118. inputAudioNode.connect(this._webAudioAnalyser);
  56119. this._webAudioAnalyser.connect(outputAudioNode);
  56120. }
  56121. };
  56122. Analyser.prototype.dispose = function () {
  56123. if (this._audioEngine.canUseWebAudio) {
  56124. this._webAudioAnalyser.disconnect();
  56125. }
  56126. };
  56127. return Analyser;
  56128. }());
  56129. BABYLON.Analyser = Analyser;
  56130. })(BABYLON || (BABYLON = {}));
  56131. //# sourceMappingURL=babylon.analyser.js.map
  56132. var BABYLON;
  56133. (function (BABYLON) {
  56134. var CubeTexture = /** @class */ (function (_super) {
  56135. __extends(CubeTexture, _super);
  56136. function CubeTexture(rootUrl, scene, extensions, noMipmap, files, onLoad, onError, format, prefiltered, forcedExtension) {
  56137. if (extensions === void 0) { extensions = null; }
  56138. if (noMipmap === void 0) { noMipmap = false; }
  56139. if (files === void 0) { files = null; }
  56140. if (onLoad === void 0) { onLoad = null; }
  56141. if (onError === void 0) { onError = null; }
  56142. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  56143. if (prefiltered === void 0) { prefiltered = false; }
  56144. if (forcedExtension === void 0) { forcedExtension = null; }
  56145. var _this = _super.call(this, scene) || this;
  56146. _this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  56147. /**
  56148. * Gets or sets the center of the bounding box associated with the cube texture
  56149. * It must define where the camera used to render the texture was set
  56150. */
  56151. _this.boundingBoxPosition = BABYLON.Vector3.Zero();
  56152. _this.name = rootUrl;
  56153. _this.url = rootUrl;
  56154. _this._noMipmap = noMipmap;
  56155. _this.hasAlpha = false;
  56156. _this._format = format;
  56157. _this._prefiltered = prefiltered;
  56158. _this.isCube = true;
  56159. _this._textureMatrix = BABYLON.Matrix.Identity();
  56160. if (prefiltered) {
  56161. _this.gammaSpace = false;
  56162. }
  56163. if (!rootUrl && !files) {
  56164. return _this;
  56165. }
  56166. _this._texture = _this._getFromCache(rootUrl, noMipmap);
  56167. var lastDot = rootUrl.lastIndexOf(".");
  56168. var extension = forcedExtension ? forcedExtension : (lastDot > -1 ? rootUrl.substring(lastDot).toLowerCase() : "");
  56169. var isDDS = (extension === ".dds");
  56170. if (!files) {
  56171. if (!isDDS && !extensions) {
  56172. extensions = ["_px.jpg", "_py.jpg", "_pz.jpg", "_nx.jpg", "_ny.jpg", "_nz.jpg"];
  56173. }
  56174. files = [];
  56175. if (extensions) {
  56176. for (var index = 0; index < extensions.length; index++) {
  56177. files.push(rootUrl + extensions[index]);
  56178. }
  56179. }
  56180. }
  56181. _this._files = files;
  56182. if (!_this._texture) {
  56183. if (!scene.useDelayedTextureLoading) {
  56184. if (prefiltered) {
  56185. _this._texture = scene.getEngine().createPrefilteredCubeTexture(rootUrl, scene, _this.lodGenerationScale, _this.lodGenerationOffset, onLoad, onError, format, forcedExtension);
  56186. }
  56187. else {
  56188. _this._texture = scene.getEngine().createCubeTexture(rootUrl, scene, files, noMipmap, onLoad, onError, _this._format, forcedExtension);
  56189. }
  56190. }
  56191. else {
  56192. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  56193. }
  56194. }
  56195. else if (onLoad) {
  56196. if (_this._texture.isReady) {
  56197. BABYLON.Tools.SetImmediate(function () { return onLoad(); });
  56198. }
  56199. else {
  56200. _this._texture.onLoadedObservable.add(onLoad);
  56201. }
  56202. }
  56203. return _this;
  56204. }
  56205. Object.defineProperty(CubeTexture.prototype, "boundingBoxSize", {
  56206. get: function () {
  56207. return this._boundingBoxSize;
  56208. },
  56209. /**
  56210. * Gets or sets the size of the bounding box associated with the cube texture
  56211. * When defined, the cubemap will switch to local mode
  56212. * @see https://community.arm.com/graphics/b/blog/posts/reflections-based-on-local-cubemaps-in-unity
  56213. * @example https://www.babylonjs-playground.com/#RNASML
  56214. */
  56215. set: function (value) {
  56216. if (this._boundingBoxSize && this._boundingBoxSize.equals(value)) {
  56217. return;
  56218. }
  56219. this._boundingBoxSize = value;
  56220. var scene = this.getScene();
  56221. if (scene) {
  56222. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  56223. }
  56224. },
  56225. enumerable: true,
  56226. configurable: true
  56227. });
  56228. CubeTexture.CreateFromImages = function (files, scene, noMipmap) {
  56229. return new CubeTexture("", scene, null, noMipmap, files);
  56230. };
  56231. CubeTexture.CreateFromPrefilteredData = function (url, scene, forcedExtension) {
  56232. if (forcedExtension === void 0) { forcedExtension = null; }
  56233. return new CubeTexture(url, scene, null, false, null, null, null, undefined, true, forcedExtension);
  56234. };
  56235. // Methods
  56236. CubeTexture.prototype.delayLoad = function () {
  56237. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  56238. return;
  56239. }
  56240. var scene = this.getScene();
  56241. if (!scene) {
  56242. return;
  56243. }
  56244. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  56245. this._texture = this._getFromCache(this.url, this._noMipmap);
  56246. if (!this._texture) {
  56247. if (this._prefiltered) {
  56248. this._texture = scene.getEngine().createPrefilteredCubeTexture(this.url, scene, this.lodGenerationScale, this.lodGenerationOffset, undefined, undefined, this._format);
  56249. }
  56250. else {
  56251. this._texture = scene.getEngine().createCubeTexture(this.url, scene, this._files, this._noMipmap, undefined, undefined, this._format);
  56252. }
  56253. }
  56254. };
  56255. CubeTexture.prototype.getReflectionTextureMatrix = function () {
  56256. return this._textureMatrix;
  56257. };
  56258. CubeTexture.prototype.setReflectionTextureMatrix = function (value) {
  56259. this._textureMatrix = value;
  56260. };
  56261. CubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  56262. var texture = BABYLON.SerializationHelper.Parse(function () {
  56263. return new CubeTexture(rootUrl + parsedTexture.name, scene, parsedTexture.extensions);
  56264. }, parsedTexture, scene);
  56265. // Animations
  56266. if (parsedTexture.animations) {
  56267. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  56268. var parsedAnimation = parsedTexture.animations[animationIndex];
  56269. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  56270. }
  56271. }
  56272. return texture;
  56273. };
  56274. CubeTexture.prototype.clone = function () {
  56275. var _this = this;
  56276. return BABYLON.SerializationHelper.Clone(function () {
  56277. var scene = _this.getScene();
  56278. if (!scene) {
  56279. return _this;
  56280. }
  56281. return new CubeTexture(_this.url, scene, _this._extensions, _this._noMipmap, _this._files);
  56282. }, this);
  56283. };
  56284. return CubeTexture;
  56285. }(BABYLON.BaseTexture));
  56286. BABYLON.CubeTexture = CubeTexture;
  56287. })(BABYLON || (BABYLON = {}));
  56288. //# sourceMappingURL=babylon.cubeTexture.js.map
  56289. var BABYLON;
  56290. (function (BABYLON) {
  56291. var RenderTargetTexture = /** @class */ (function (_super) {
  56292. __extends(RenderTargetTexture, _super);
  56293. function RenderTargetTexture(name, size, scene, generateMipMaps, doNotChangeAspectRatio, type, isCube, samplingMode, generateDepthBuffer, generateStencilBuffer, isMulti) {
  56294. if (doNotChangeAspectRatio === void 0) { doNotChangeAspectRatio = true; }
  56295. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  56296. if (isCube === void 0) { isCube = false; }
  56297. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  56298. if (generateDepthBuffer === void 0) { generateDepthBuffer = true; }
  56299. if (generateStencilBuffer === void 0) { generateStencilBuffer = false; }
  56300. if (isMulti === void 0) { isMulti = false; }
  56301. var _this = _super.call(this, null, scene, !generateMipMaps) || this;
  56302. _this.isCube = isCube;
  56303. /**
  56304. * Use this list to define the list of mesh you want to render.
  56305. */
  56306. _this.renderList = new Array();
  56307. _this.renderParticles = true;
  56308. _this.renderSprites = false;
  56309. _this.coordinatesMode = BABYLON.Texture.PROJECTION_MODE;
  56310. _this.ignoreCameraViewport = false;
  56311. // Events
  56312. /**
  56313. * An event triggered when the texture is unbind.
  56314. * @type {BABYLON.Observable}
  56315. */
  56316. _this.onBeforeBindObservable = new BABYLON.Observable();
  56317. /**
  56318. * An event triggered when the texture is unbind.
  56319. * @type {BABYLON.Observable}
  56320. */
  56321. _this.onAfterUnbindObservable = new BABYLON.Observable();
  56322. /**
  56323. * An event triggered before rendering the texture
  56324. * @type {BABYLON.Observable}
  56325. */
  56326. _this.onBeforeRenderObservable = new BABYLON.Observable();
  56327. /**
  56328. * An event triggered after rendering the texture
  56329. * @type {BABYLON.Observable}
  56330. */
  56331. _this.onAfterRenderObservable = new BABYLON.Observable();
  56332. /**
  56333. * An event triggered after the texture clear
  56334. * @type {BABYLON.Observable}
  56335. */
  56336. _this.onClearObservable = new BABYLON.Observable();
  56337. _this._currentRefreshId = -1;
  56338. _this._refreshRate = 1;
  56339. _this._samples = 1;
  56340. /**
  56341. * Gets or sets the center of the bounding box associated with the texture (when in cube mode)
  56342. * It must define where the camera used to render the texture is set
  56343. */
  56344. _this.boundingBoxPosition = BABYLON.Vector3.Zero();
  56345. scene = _this.getScene();
  56346. if (!scene) {
  56347. return _this;
  56348. }
  56349. _this._engine = scene.getEngine();
  56350. _this.name = name;
  56351. _this.isRenderTarget = true;
  56352. _this._initialSizeParameter = size;
  56353. _this._processSizeParameter(size);
  56354. _this._resizeObserver = _this.getScene().getEngine().onResizeObservable.add(function () {
  56355. });
  56356. _this._generateMipMaps = generateMipMaps ? true : false;
  56357. _this._doNotChangeAspectRatio = doNotChangeAspectRatio;
  56358. // Rendering groups
  56359. _this._renderingManager = new BABYLON.RenderingManager(scene);
  56360. if (isMulti) {
  56361. return _this;
  56362. }
  56363. _this._renderTargetOptions = {
  56364. generateMipMaps: generateMipMaps,
  56365. type: type,
  56366. samplingMode: samplingMode,
  56367. generateDepthBuffer: generateDepthBuffer,
  56368. generateStencilBuffer: generateStencilBuffer
  56369. };
  56370. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  56371. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  56372. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  56373. }
  56374. if (isCube) {
  56375. _this._texture = scene.getEngine().createRenderTargetCubeTexture(_this.getRenderSize(), _this._renderTargetOptions);
  56376. _this.coordinatesMode = BABYLON.Texture.INVCUBIC_MODE;
  56377. _this._textureMatrix = BABYLON.Matrix.Identity();
  56378. }
  56379. else {
  56380. _this._texture = scene.getEngine().createRenderTargetTexture(_this._size, _this._renderTargetOptions);
  56381. }
  56382. return _this;
  56383. }
  56384. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONCE", {
  56385. get: function () {
  56386. return RenderTargetTexture._REFRESHRATE_RENDER_ONCE;
  56387. },
  56388. enumerable: true,
  56389. configurable: true
  56390. });
  56391. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYFRAME", {
  56392. get: function () {
  56393. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME;
  56394. },
  56395. enumerable: true,
  56396. configurable: true
  56397. });
  56398. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYTWOFRAMES", {
  56399. get: function () {
  56400. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES;
  56401. },
  56402. enumerable: true,
  56403. configurable: true
  56404. });
  56405. Object.defineProperty(RenderTargetTexture.prototype, "onAfterUnbind", {
  56406. set: function (callback) {
  56407. if (this._onAfterUnbindObserver) {
  56408. this.onAfterUnbindObservable.remove(this._onAfterUnbindObserver);
  56409. }
  56410. this._onAfterUnbindObserver = this.onAfterUnbindObservable.add(callback);
  56411. },
  56412. enumerable: true,
  56413. configurable: true
  56414. });
  56415. Object.defineProperty(RenderTargetTexture.prototype, "onBeforeRender", {
  56416. set: function (callback) {
  56417. if (this._onBeforeRenderObserver) {
  56418. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  56419. }
  56420. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  56421. },
  56422. enumerable: true,
  56423. configurable: true
  56424. });
  56425. Object.defineProperty(RenderTargetTexture.prototype, "onAfterRender", {
  56426. set: function (callback) {
  56427. if (this._onAfterRenderObserver) {
  56428. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  56429. }
  56430. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  56431. },
  56432. enumerable: true,
  56433. configurable: true
  56434. });
  56435. Object.defineProperty(RenderTargetTexture.prototype, "onClear", {
  56436. set: function (callback) {
  56437. if (this._onClearObserver) {
  56438. this.onClearObservable.remove(this._onClearObserver);
  56439. }
  56440. this._onClearObserver = this.onClearObservable.add(callback);
  56441. },
  56442. enumerable: true,
  56443. configurable: true
  56444. });
  56445. Object.defineProperty(RenderTargetTexture.prototype, "renderTargetOptions", {
  56446. get: function () {
  56447. return this._renderTargetOptions;
  56448. },
  56449. enumerable: true,
  56450. configurable: true
  56451. });
  56452. RenderTargetTexture.prototype._onRatioRescale = function () {
  56453. if (this._sizeRatio) {
  56454. this.resize(this._initialSizeParameter);
  56455. }
  56456. };
  56457. Object.defineProperty(RenderTargetTexture.prototype, "boundingBoxSize", {
  56458. get: function () {
  56459. return this._boundingBoxSize;
  56460. },
  56461. /**
  56462. * Gets or sets the size of the bounding box associated with the texture (when in cube mode)
  56463. * When defined, the cubemap will switch to local mode
  56464. * @see https://community.arm.com/graphics/b/blog/posts/reflections-based-on-local-cubemaps-in-unity
  56465. * @example https://www.babylonjs-playground.com/#RNASML
  56466. */
  56467. set: function (value) {
  56468. if (this._boundingBoxSize && this._boundingBoxSize.equals(value)) {
  56469. return;
  56470. }
  56471. this._boundingBoxSize = value;
  56472. var scene = this.getScene();
  56473. if (scene) {
  56474. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  56475. }
  56476. },
  56477. enumerable: true,
  56478. configurable: true
  56479. });
  56480. RenderTargetTexture.prototype._processSizeParameter = function (size) {
  56481. if (size.ratio) {
  56482. this._sizeRatio = size.ratio;
  56483. this._size = {
  56484. width: this._bestReflectionRenderTargetDimension(this._engine.getRenderWidth(), this._sizeRatio),
  56485. height: this._bestReflectionRenderTargetDimension(this._engine.getRenderHeight(), this._sizeRatio)
  56486. };
  56487. }
  56488. else {
  56489. this._size = size;
  56490. }
  56491. };
  56492. Object.defineProperty(RenderTargetTexture.prototype, "samples", {
  56493. get: function () {
  56494. return this._samples;
  56495. },
  56496. set: function (value) {
  56497. if (this._samples === value) {
  56498. return;
  56499. }
  56500. var scene = this.getScene();
  56501. if (!scene) {
  56502. return;
  56503. }
  56504. this._samples = scene.getEngine().updateRenderTargetTextureSampleCount(this._texture, value);
  56505. },
  56506. enumerable: true,
  56507. configurable: true
  56508. });
  56509. RenderTargetTexture.prototype.resetRefreshCounter = function () {
  56510. this._currentRefreshId = -1;
  56511. };
  56512. Object.defineProperty(RenderTargetTexture.prototype, "refreshRate", {
  56513. get: function () {
  56514. return this._refreshRate;
  56515. },
  56516. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  56517. set: function (value) {
  56518. this._refreshRate = value;
  56519. this.resetRefreshCounter();
  56520. },
  56521. enumerable: true,
  56522. configurable: true
  56523. });
  56524. RenderTargetTexture.prototype.addPostProcess = function (postProcess) {
  56525. if (!this._postProcessManager) {
  56526. var scene = this.getScene();
  56527. if (!scene) {
  56528. return;
  56529. }
  56530. this._postProcessManager = new BABYLON.PostProcessManager(scene);
  56531. this._postProcesses = new Array();
  56532. }
  56533. this._postProcesses.push(postProcess);
  56534. this._postProcesses[0].autoClear = false;
  56535. };
  56536. RenderTargetTexture.prototype.clearPostProcesses = function (dispose) {
  56537. if (!this._postProcesses) {
  56538. return;
  56539. }
  56540. if (dispose) {
  56541. for (var _i = 0, _a = this._postProcesses; _i < _a.length; _i++) {
  56542. var postProcess = _a[_i];
  56543. postProcess.dispose();
  56544. }
  56545. }
  56546. this._postProcesses = [];
  56547. };
  56548. RenderTargetTexture.prototype.removePostProcess = function (postProcess) {
  56549. if (!this._postProcesses) {
  56550. return;
  56551. }
  56552. var index = this._postProcesses.indexOf(postProcess);
  56553. if (index === -1) {
  56554. return;
  56555. }
  56556. this._postProcesses.splice(index, 1);
  56557. if (this._postProcesses.length > 0) {
  56558. this._postProcesses[0].autoClear = false;
  56559. }
  56560. };
  56561. RenderTargetTexture.prototype._shouldRender = function () {
  56562. if (this._currentRefreshId === -1) {
  56563. this._currentRefreshId = 1;
  56564. return true;
  56565. }
  56566. if (this.refreshRate === this._currentRefreshId) {
  56567. this._currentRefreshId = 1;
  56568. return true;
  56569. }
  56570. this._currentRefreshId++;
  56571. return false;
  56572. };
  56573. RenderTargetTexture.prototype.getRenderSize = function () {
  56574. if (this._size.width) {
  56575. return this._size.width;
  56576. }
  56577. return this._size;
  56578. };
  56579. RenderTargetTexture.prototype.getRenderWidth = function () {
  56580. if (this._size.width) {
  56581. return this._size.width;
  56582. }
  56583. return this._size;
  56584. };
  56585. RenderTargetTexture.prototype.getRenderHeight = function () {
  56586. if (this._size.width) {
  56587. return this._size.height;
  56588. }
  56589. return this._size;
  56590. };
  56591. Object.defineProperty(RenderTargetTexture.prototype, "canRescale", {
  56592. get: function () {
  56593. return true;
  56594. },
  56595. enumerable: true,
  56596. configurable: true
  56597. });
  56598. RenderTargetTexture.prototype.scale = function (ratio) {
  56599. var newSize = this.getRenderSize() * ratio;
  56600. this.resize(newSize);
  56601. };
  56602. RenderTargetTexture.prototype.getReflectionTextureMatrix = function () {
  56603. if (this.isCube) {
  56604. return this._textureMatrix;
  56605. }
  56606. return _super.prototype.getReflectionTextureMatrix.call(this);
  56607. };
  56608. RenderTargetTexture.prototype.resize = function (size) {
  56609. this.releaseInternalTexture();
  56610. var scene = this.getScene();
  56611. if (!scene) {
  56612. return;
  56613. }
  56614. this._processSizeParameter(size);
  56615. if (this.isCube) {
  56616. this._texture = scene.getEngine().createRenderTargetCubeTexture(this.getRenderSize(), this._renderTargetOptions);
  56617. }
  56618. else {
  56619. this._texture = scene.getEngine().createRenderTargetTexture(this._size, this._renderTargetOptions);
  56620. }
  56621. };
  56622. RenderTargetTexture.prototype.render = function (useCameraPostProcess, dumpForDebug) {
  56623. if (useCameraPostProcess === void 0) { useCameraPostProcess = false; }
  56624. if (dumpForDebug === void 0) { dumpForDebug = false; }
  56625. var scene = this.getScene();
  56626. if (!scene) {
  56627. return;
  56628. }
  56629. var engine = scene.getEngine();
  56630. if (this.useCameraPostProcesses !== undefined) {
  56631. useCameraPostProcess = this.useCameraPostProcesses;
  56632. }
  56633. if (this._waitingRenderList) {
  56634. this.renderList = [];
  56635. for (var index = 0; index < this._waitingRenderList.length; index++) {
  56636. var id = this._waitingRenderList[index];
  56637. var mesh_1 = scene.getMeshByID(id);
  56638. if (mesh_1) {
  56639. this.renderList.push(mesh_1);
  56640. }
  56641. }
  56642. delete this._waitingRenderList;
  56643. }
  56644. // Is predicate defined?
  56645. if (this.renderListPredicate) {
  56646. if (this.renderList) {
  56647. this.renderList.splice(0); // Clear previous renderList
  56648. }
  56649. else {
  56650. this.renderList = [];
  56651. }
  56652. var scene = this.getScene();
  56653. if (!scene) {
  56654. return;
  56655. }
  56656. var sceneMeshes = scene.meshes;
  56657. for (var index = 0; index < sceneMeshes.length; index++) {
  56658. var mesh = sceneMeshes[index];
  56659. if (this.renderListPredicate(mesh)) {
  56660. this.renderList.push(mesh);
  56661. }
  56662. }
  56663. }
  56664. this.onBeforeBindObservable.notifyObservers(this);
  56665. // Set custom projection.
  56666. // Needs to be before binding to prevent changing the aspect ratio.
  56667. var camera;
  56668. if (this.activeCamera) {
  56669. camera = this.activeCamera;
  56670. engine.setViewport(this.activeCamera.viewport, this.getRenderWidth(), this.getRenderHeight());
  56671. if (this.activeCamera !== scene.activeCamera) {
  56672. scene.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(true));
  56673. }
  56674. }
  56675. else {
  56676. camera = scene.activeCamera;
  56677. if (camera) {
  56678. engine.setViewport(camera.viewport, this.getRenderWidth(), this.getRenderHeight());
  56679. }
  56680. }
  56681. // Prepare renderingManager
  56682. this._renderingManager.reset();
  56683. var currentRenderList = this.renderList ? this.renderList : scene.getActiveMeshes().data;
  56684. var currentRenderListLength = this.renderList ? this.renderList.length : scene.getActiveMeshes().length;
  56685. var sceneRenderId = scene.getRenderId();
  56686. for (var meshIndex = 0; meshIndex < currentRenderListLength; meshIndex++) {
  56687. var mesh = currentRenderList[meshIndex];
  56688. if (mesh) {
  56689. if (!mesh.isReady()) {
  56690. // Reset _currentRefreshId
  56691. this.resetRefreshCounter();
  56692. continue;
  56693. }
  56694. mesh._preActivateForIntermediateRendering(sceneRenderId);
  56695. var isMasked = void 0;
  56696. if (!this.renderList && camera) {
  56697. isMasked = ((mesh.layerMask & camera.layerMask) === 0);
  56698. }
  56699. else {
  56700. isMasked = false;
  56701. }
  56702. if (mesh.isEnabled() && mesh.isVisible && mesh.subMeshes && !isMasked) {
  56703. mesh._activate(sceneRenderId);
  56704. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  56705. var subMesh = mesh.subMeshes[subIndex];
  56706. scene._activeIndices.addCount(subMesh.indexCount, false);
  56707. this._renderingManager.dispatch(subMesh, mesh);
  56708. }
  56709. }
  56710. }
  56711. }
  56712. for (var particleIndex = 0; particleIndex < scene.particleSystems.length; particleIndex++) {
  56713. var particleSystem = scene.particleSystems[particleIndex];
  56714. var emitter = particleSystem.emitter;
  56715. if (!particleSystem.isStarted() || !emitter || !emitter.position || !emitter.isEnabled()) {
  56716. continue;
  56717. }
  56718. if (currentRenderList.indexOf(emitter) >= 0) {
  56719. this._renderingManager.dispatchParticles(particleSystem);
  56720. }
  56721. }
  56722. if (this.isCube) {
  56723. for (var face = 0; face < 6; face++) {
  56724. this.renderToTarget(face, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
  56725. scene.incrementRenderId();
  56726. scene.resetCachedMaterial();
  56727. }
  56728. }
  56729. else {
  56730. this.renderToTarget(0, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
  56731. }
  56732. this.onAfterUnbindObservable.notifyObservers(this);
  56733. if (scene.activeCamera) {
  56734. if (this.activeCamera && this.activeCamera !== scene.activeCamera) {
  56735. scene.setTransformMatrix(scene.activeCamera.getViewMatrix(), scene.activeCamera.getProjectionMatrix(true));
  56736. }
  56737. engine.setViewport(scene.activeCamera.viewport);
  56738. }
  56739. scene.resetCachedMaterial();
  56740. };
  56741. RenderTargetTexture.prototype._bestReflectionRenderTargetDimension = function (renderDimension, scale) {
  56742. var minimum = 128;
  56743. var x = renderDimension * scale;
  56744. var curved = BABYLON.Tools.NearestPOT(x + (minimum * minimum / (minimum + x)));
  56745. // Ensure we don't exceed the render dimension (while staying POT)
  56746. return Math.min(BABYLON.Tools.FloorPOT(renderDimension), curved);
  56747. };
  56748. RenderTargetTexture.prototype.unbindFrameBuffer = function (engine, faceIndex) {
  56749. var _this = this;
  56750. if (!this._texture) {
  56751. return;
  56752. }
  56753. engine.unBindFramebuffer(this._texture, this.isCube, function () {
  56754. _this.onAfterRenderObservable.notifyObservers(faceIndex);
  56755. });
  56756. };
  56757. RenderTargetTexture.prototype.renderToTarget = function (faceIndex, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug) {
  56758. var scene = this.getScene();
  56759. if (!scene) {
  56760. return;
  56761. }
  56762. var engine = scene.getEngine();
  56763. if (!this._texture) {
  56764. return;
  56765. }
  56766. // Bind
  56767. if (this._postProcessManager) {
  56768. this._postProcessManager._prepareFrame(this._texture, this._postProcesses);
  56769. }
  56770. else if (!useCameraPostProcess || !scene.postProcessManager._prepareFrame(this._texture)) {
  56771. if (this._texture) {
  56772. engine.bindFramebuffer(this._texture, this.isCube ? faceIndex : undefined, undefined, undefined, this.ignoreCameraViewport);
  56773. }
  56774. }
  56775. this.onBeforeRenderObservable.notifyObservers(faceIndex);
  56776. // Clear
  56777. if (this.onClearObservable.hasObservers()) {
  56778. this.onClearObservable.notifyObservers(engine);
  56779. }
  56780. else {
  56781. engine.clear(this.clearColor || scene.clearColor, true, true, true);
  56782. }
  56783. if (!this._doNotChangeAspectRatio) {
  56784. scene.updateTransformMatrix(true);
  56785. }
  56786. // Render
  56787. this._renderingManager.render(this.customRenderFunction, currentRenderList, this.renderParticles, this.renderSprites);
  56788. if (this._postProcessManager) {
  56789. this._postProcessManager._finalizeFrame(false, this._texture, faceIndex, this._postProcesses, this.ignoreCameraViewport);
  56790. }
  56791. else if (useCameraPostProcess) {
  56792. scene.postProcessManager._finalizeFrame(false, this._texture, faceIndex);
  56793. }
  56794. if (!this._doNotChangeAspectRatio) {
  56795. scene.updateTransformMatrix(true);
  56796. }
  56797. // Dump ?
  56798. if (dumpForDebug) {
  56799. BABYLON.Tools.DumpFramebuffer(this.getRenderWidth(), this.getRenderHeight(), engine);
  56800. }
  56801. // Unbind
  56802. if (!this.isCube || faceIndex === 5) {
  56803. if (this.isCube) {
  56804. if (faceIndex === 5) {
  56805. engine.generateMipMapsForCubemap(this._texture);
  56806. }
  56807. }
  56808. this.unbindFrameBuffer(engine, faceIndex);
  56809. }
  56810. else {
  56811. this.onAfterRenderObservable.notifyObservers(faceIndex);
  56812. }
  56813. };
  56814. /**
  56815. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  56816. * This allowed control for front to back rendering or reversly depending of the special needs.
  56817. *
  56818. * @param renderingGroupId The rendering group id corresponding to its index
  56819. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  56820. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  56821. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  56822. */
  56823. RenderTargetTexture.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  56824. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  56825. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  56826. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  56827. this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
  56828. };
  56829. /**
  56830. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  56831. *
  56832. * @param renderingGroupId The rendering group id corresponding to its index
  56833. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  56834. */
  56835. RenderTargetTexture.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil) {
  56836. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil);
  56837. };
  56838. RenderTargetTexture.prototype.clone = function () {
  56839. var textureSize = this.getSize();
  56840. 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);
  56841. // Base texture
  56842. newTexture.hasAlpha = this.hasAlpha;
  56843. newTexture.level = this.level;
  56844. // RenderTarget Texture
  56845. newTexture.coordinatesMode = this.coordinatesMode;
  56846. if (this.renderList) {
  56847. newTexture.renderList = this.renderList.slice(0);
  56848. }
  56849. return newTexture;
  56850. };
  56851. RenderTargetTexture.prototype.serialize = function () {
  56852. if (!this.name) {
  56853. return null;
  56854. }
  56855. var serializationObject = _super.prototype.serialize.call(this);
  56856. serializationObject.renderTargetSize = this.getRenderSize();
  56857. serializationObject.renderList = [];
  56858. if (this.renderList) {
  56859. for (var index = 0; index < this.renderList.length; index++) {
  56860. serializationObject.renderList.push(this.renderList[index].id);
  56861. }
  56862. }
  56863. return serializationObject;
  56864. };
  56865. // This will remove the attached framebuffer objects. The texture will not be able to be used as render target anymore
  56866. RenderTargetTexture.prototype.disposeFramebufferObjects = function () {
  56867. var objBuffer = this.getInternalTexture();
  56868. var scene = this.getScene();
  56869. if (objBuffer && scene) {
  56870. scene.getEngine()._releaseFramebufferObjects(objBuffer);
  56871. }
  56872. };
  56873. RenderTargetTexture.prototype.dispose = function () {
  56874. if (this._postProcessManager) {
  56875. this._postProcessManager.dispose();
  56876. this._postProcessManager = null;
  56877. }
  56878. this.clearPostProcesses(true);
  56879. if (this._resizeObserver) {
  56880. this.getScene().getEngine().onResizeObservable.remove(this._resizeObserver);
  56881. this._resizeObserver = null;
  56882. }
  56883. this.renderList = null;
  56884. // Remove from custom render targets
  56885. var scene = this.getScene();
  56886. if (!scene) {
  56887. return;
  56888. }
  56889. var index = scene.customRenderTargets.indexOf(this);
  56890. if (index >= 0) {
  56891. scene.customRenderTargets.splice(index, 1);
  56892. }
  56893. for (var _i = 0, _a = scene.cameras; _i < _a.length; _i++) {
  56894. var camera = _a[_i];
  56895. index = camera.customRenderTargets.indexOf(this);
  56896. if (index >= 0) {
  56897. camera.customRenderTargets.splice(index, 1);
  56898. }
  56899. }
  56900. _super.prototype.dispose.call(this);
  56901. };
  56902. RenderTargetTexture.prototype._rebuild = function () {
  56903. if (this.refreshRate === RenderTargetTexture.REFRESHRATE_RENDER_ONCE) {
  56904. this.refreshRate = RenderTargetTexture.REFRESHRATE_RENDER_ONCE;
  56905. }
  56906. if (this._postProcessManager) {
  56907. this._postProcessManager._rebuild();
  56908. }
  56909. };
  56910. RenderTargetTexture._REFRESHRATE_RENDER_ONCE = 0;
  56911. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME = 1;
  56912. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES = 2;
  56913. return RenderTargetTexture;
  56914. }(BABYLON.Texture));
  56915. BABYLON.RenderTargetTexture = RenderTargetTexture;
  56916. })(BABYLON || (BABYLON = {}));
  56917. //# sourceMappingURL=babylon.renderTargetTexture.js.map
  56918. var BABYLON;
  56919. (function (BABYLON) {
  56920. ;
  56921. var MultiRenderTarget = /** @class */ (function (_super) {
  56922. __extends(MultiRenderTarget, _super);
  56923. function MultiRenderTarget(name, size, count, scene, options) {
  56924. var _this = this;
  56925. var generateMipMaps = options && options.generateMipMaps ? options.generateMipMaps : false;
  56926. var generateDepthTexture = options && options.generateDepthTexture ? options.generateDepthTexture : false;
  56927. var doNotChangeAspectRatio = !options || options.doNotChangeAspectRatio === undefined ? true : options.doNotChangeAspectRatio;
  56928. _this = _super.call(this, name, size, scene, generateMipMaps, doNotChangeAspectRatio) || this;
  56929. _this._engine = scene.getEngine();
  56930. if (!_this.isSupported) {
  56931. _this.dispose();
  56932. return;
  56933. }
  56934. var types = [];
  56935. var samplingModes = [];
  56936. for (var i = 0; i < count; i++) {
  56937. if (options && options.types && options.types[i] !== undefined) {
  56938. types.push(options.types[i]);
  56939. }
  56940. else {
  56941. types.push(options && options.defaultType ? options.defaultType : BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  56942. }
  56943. if (options && options.samplingModes && options.samplingModes[i] !== undefined) {
  56944. samplingModes.push(options.samplingModes[i]);
  56945. }
  56946. else {
  56947. samplingModes.push(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  56948. }
  56949. }
  56950. var generateDepthBuffer = !options || options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  56951. var generateStencilBuffer = !options || options.generateStencilBuffer === undefined ? false : options.generateStencilBuffer;
  56952. _this._size = size;
  56953. _this._multiRenderTargetOptions = {
  56954. samplingModes: samplingModes,
  56955. generateMipMaps: generateMipMaps,
  56956. generateDepthBuffer: generateDepthBuffer,
  56957. generateStencilBuffer: generateStencilBuffer,
  56958. generateDepthTexture: generateDepthTexture,
  56959. types: types,
  56960. textureCount: count
  56961. };
  56962. _this._createInternalTextures();
  56963. _this._createTextures();
  56964. return _this;
  56965. }
  56966. Object.defineProperty(MultiRenderTarget.prototype, "isSupported", {
  56967. get: function () {
  56968. return this._engine.webGLVersion > 1 || this._engine.getCaps().drawBuffersExtension;
  56969. },
  56970. enumerable: true,
  56971. configurable: true
  56972. });
  56973. Object.defineProperty(MultiRenderTarget.prototype, "textures", {
  56974. get: function () {
  56975. return this._textures;
  56976. },
  56977. enumerable: true,
  56978. configurable: true
  56979. });
  56980. Object.defineProperty(MultiRenderTarget.prototype, "depthTexture", {
  56981. get: function () {
  56982. return this._textures[this._textures.length - 1];
  56983. },
  56984. enumerable: true,
  56985. configurable: true
  56986. });
  56987. Object.defineProperty(MultiRenderTarget.prototype, "wrapU", {
  56988. set: function (wrap) {
  56989. if (this._textures) {
  56990. for (var i = 0; i < this._textures.length; i++) {
  56991. this._textures[i].wrapU = wrap;
  56992. }
  56993. }
  56994. },
  56995. enumerable: true,
  56996. configurable: true
  56997. });
  56998. Object.defineProperty(MultiRenderTarget.prototype, "wrapV", {
  56999. set: function (wrap) {
  57000. if (this._textures) {
  57001. for (var i = 0; i < this._textures.length; i++) {
  57002. this._textures[i].wrapV = wrap;
  57003. }
  57004. }
  57005. },
  57006. enumerable: true,
  57007. configurable: true
  57008. });
  57009. MultiRenderTarget.prototype._rebuild = function () {
  57010. this.releaseInternalTextures();
  57011. this._createInternalTextures();
  57012. for (var i = 0; i < this._internalTextures.length; i++) {
  57013. var texture = this._textures[i];
  57014. texture._texture = this._internalTextures[i];
  57015. }
  57016. // Keeps references to frame buffer and stencil/depth buffer
  57017. this._texture = this._internalTextures[0];
  57018. };
  57019. MultiRenderTarget.prototype._createInternalTextures = function () {
  57020. this._internalTextures = this._engine.createMultipleRenderTarget(this._size, this._multiRenderTargetOptions);
  57021. };
  57022. MultiRenderTarget.prototype._createTextures = function () {
  57023. this._textures = [];
  57024. for (var i = 0; i < this._internalTextures.length; i++) {
  57025. var texture = new BABYLON.Texture(null, this.getScene());
  57026. texture._texture = this._internalTextures[i];
  57027. this._textures.push(texture);
  57028. }
  57029. // Keeps references to frame buffer and stencil/depth buffer
  57030. this._texture = this._internalTextures[0];
  57031. };
  57032. Object.defineProperty(MultiRenderTarget.prototype, "samples", {
  57033. get: function () {
  57034. return this._samples;
  57035. },
  57036. set: function (value) {
  57037. if (this._samples === value) {
  57038. return;
  57039. }
  57040. this._samples = this._engine.updateMultipleRenderTargetTextureSampleCount(this._internalTextures, value);
  57041. },
  57042. enumerable: true,
  57043. configurable: true
  57044. });
  57045. MultiRenderTarget.prototype.resize = function (size) {
  57046. this.releaseInternalTextures();
  57047. this._internalTextures = this._engine.createMultipleRenderTarget(size, this._multiRenderTargetOptions);
  57048. this._createInternalTextures();
  57049. };
  57050. MultiRenderTarget.prototype.unbindFrameBuffer = function (engine, faceIndex) {
  57051. var _this = this;
  57052. engine.unBindMultiColorAttachmentFramebuffer(this._internalTextures, this.isCube, function () {
  57053. _this.onAfterRenderObservable.notifyObservers(faceIndex);
  57054. });
  57055. };
  57056. MultiRenderTarget.prototype.dispose = function () {
  57057. this.releaseInternalTextures();
  57058. _super.prototype.dispose.call(this);
  57059. };
  57060. MultiRenderTarget.prototype.releaseInternalTextures = function () {
  57061. if (!this._internalTextures) {
  57062. return;
  57063. }
  57064. for (var i = this._internalTextures.length - 1; i >= 0; i--) {
  57065. if (this._internalTextures[i] !== undefined) {
  57066. this._internalTextures[i].dispose();
  57067. this._internalTextures.splice(i, 1);
  57068. }
  57069. }
  57070. };
  57071. return MultiRenderTarget;
  57072. }(BABYLON.RenderTargetTexture));
  57073. BABYLON.MultiRenderTarget = MultiRenderTarget;
  57074. })(BABYLON || (BABYLON = {}));
  57075. //# sourceMappingURL=babylon.multiRenderTarget.js.map
  57076. var BABYLON;
  57077. (function (BABYLON) {
  57078. var MirrorTexture = /** @class */ (function (_super) {
  57079. __extends(MirrorTexture, _super);
  57080. function MirrorTexture(name, size, scene, generateMipMaps, type, samplingMode, generateDepthBuffer) {
  57081. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  57082. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  57083. if (generateDepthBuffer === void 0) { generateDepthBuffer = true; }
  57084. var _this = _super.call(this, name, size, scene, generateMipMaps, true, type, false, samplingMode, generateDepthBuffer) || this;
  57085. _this.mirrorPlane = new BABYLON.Plane(0, 1, 0, 1);
  57086. _this._transformMatrix = BABYLON.Matrix.Zero();
  57087. _this._mirrorMatrix = BABYLON.Matrix.Zero();
  57088. _this._adaptiveBlurKernel = 0;
  57089. _this._blurKernelX = 0;
  57090. _this._blurKernelY = 0;
  57091. _this._blurRatio = 1.0;
  57092. _this.ignoreCameraViewport = true;
  57093. _this.onBeforeRenderObservable.add(function () {
  57094. BABYLON.Matrix.ReflectionToRef(_this.mirrorPlane, _this._mirrorMatrix);
  57095. _this._savedViewMatrix = scene.getViewMatrix();
  57096. _this._mirrorMatrix.multiplyToRef(_this._savedViewMatrix, _this._transformMatrix);
  57097. scene.setTransformMatrix(_this._transformMatrix, scene.getProjectionMatrix());
  57098. scene.clipPlane = _this.mirrorPlane;
  57099. scene.getEngine().cullBackFaces = false;
  57100. scene._mirroredCameraPosition = BABYLON.Vector3.TransformCoordinates(scene.activeCamera.globalPosition, _this._mirrorMatrix);
  57101. });
  57102. _this.onAfterRenderObservable.add(function () {
  57103. scene.setTransformMatrix(_this._savedViewMatrix, scene.getProjectionMatrix());
  57104. scene.getEngine().cullBackFaces = true;
  57105. scene._mirroredCameraPosition = null;
  57106. delete scene.clipPlane;
  57107. });
  57108. return _this;
  57109. }
  57110. Object.defineProperty(MirrorTexture.prototype, "blurRatio", {
  57111. get: function () {
  57112. return this._blurRatio;
  57113. },
  57114. set: function (value) {
  57115. if (this._blurRatio === value) {
  57116. return;
  57117. }
  57118. this._blurRatio = value;
  57119. this._preparePostProcesses();
  57120. },
  57121. enumerable: true,
  57122. configurable: true
  57123. });
  57124. Object.defineProperty(MirrorTexture.prototype, "adaptiveBlurKernel", {
  57125. set: function (value) {
  57126. this._adaptiveBlurKernel = value;
  57127. this._autoComputeBlurKernel();
  57128. },
  57129. enumerable: true,
  57130. configurable: true
  57131. });
  57132. Object.defineProperty(MirrorTexture.prototype, "blurKernel", {
  57133. set: function (value) {
  57134. this.blurKernelX = value;
  57135. this.blurKernelY = value;
  57136. },
  57137. enumerable: true,
  57138. configurable: true
  57139. });
  57140. Object.defineProperty(MirrorTexture.prototype, "blurKernelX", {
  57141. get: function () {
  57142. return this._blurKernelX;
  57143. },
  57144. set: function (value) {
  57145. if (this._blurKernelX === value) {
  57146. return;
  57147. }
  57148. this._blurKernelX = value;
  57149. this._preparePostProcesses();
  57150. },
  57151. enumerable: true,
  57152. configurable: true
  57153. });
  57154. Object.defineProperty(MirrorTexture.prototype, "blurKernelY", {
  57155. get: function () {
  57156. return this._blurKernelY;
  57157. },
  57158. set: function (value) {
  57159. if (this._blurKernelY === value) {
  57160. return;
  57161. }
  57162. this._blurKernelY = value;
  57163. this._preparePostProcesses();
  57164. },
  57165. enumerable: true,
  57166. configurable: true
  57167. });
  57168. MirrorTexture.prototype._autoComputeBlurKernel = function () {
  57169. var engine = this.getScene().getEngine();
  57170. var dw = this.getRenderWidth() / engine.getRenderWidth();
  57171. var dh = this.getRenderHeight() / engine.getRenderHeight();
  57172. this.blurKernelX = this._adaptiveBlurKernel * dw;
  57173. this.blurKernelY = this._adaptiveBlurKernel * dh;
  57174. };
  57175. MirrorTexture.prototype._onRatioRescale = function () {
  57176. if (this._sizeRatio) {
  57177. this.resize(this._initialSizeParameter);
  57178. if (!this._adaptiveBlurKernel) {
  57179. this._preparePostProcesses();
  57180. }
  57181. }
  57182. if (this._adaptiveBlurKernel) {
  57183. this._autoComputeBlurKernel();
  57184. }
  57185. };
  57186. MirrorTexture.prototype._preparePostProcesses = function () {
  57187. this.clearPostProcesses(true);
  57188. if (this._blurKernelX && this._blurKernelY) {
  57189. var engine = this.getScene().getEngine();
  57190. var textureType = engine.getCaps().textureFloatRender ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  57191. 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);
  57192. this._blurX.autoClear = false;
  57193. if (this._blurRatio === 1 && this.samples < 2 && this._texture) {
  57194. this._blurX.inputTexture = this._texture;
  57195. }
  57196. else {
  57197. this._blurX.alwaysForcePOT = true;
  57198. }
  57199. 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);
  57200. this._blurY.autoClear = false;
  57201. this._blurY.alwaysForcePOT = this._blurRatio !== 1;
  57202. this.addPostProcess(this._blurX);
  57203. this.addPostProcess(this._blurY);
  57204. }
  57205. else {
  57206. if (this._blurY) {
  57207. this.removePostProcess(this._blurY);
  57208. this._blurY.dispose();
  57209. this._blurY = null;
  57210. }
  57211. if (this._blurX) {
  57212. this.removePostProcess(this._blurX);
  57213. this._blurX.dispose();
  57214. this._blurX = null;
  57215. }
  57216. }
  57217. };
  57218. MirrorTexture.prototype.clone = function () {
  57219. var scene = this.getScene();
  57220. if (!scene) {
  57221. return this;
  57222. }
  57223. var textureSize = this.getSize();
  57224. var newTexture = new MirrorTexture(this.name, textureSize.width, scene, this._renderTargetOptions.generateMipMaps, this._renderTargetOptions.type, this._renderTargetOptions.samplingMode, this._renderTargetOptions.generateDepthBuffer);
  57225. // Base texture
  57226. newTexture.hasAlpha = this.hasAlpha;
  57227. newTexture.level = this.level;
  57228. // Mirror Texture
  57229. newTexture.mirrorPlane = this.mirrorPlane.clone();
  57230. if (this.renderList) {
  57231. newTexture.renderList = this.renderList.slice(0);
  57232. }
  57233. return newTexture;
  57234. };
  57235. MirrorTexture.prototype.serialize = function () {
  57236. if (!this.name) {
  57237. return null;
  57238. }
  57239. var serializationObject = _super.prototype.serialize.call(this);
  57240. serializationObject.mirrorPlane = this.mirrorPlane.asArray();
  57241. return serializationObject;
  57242. };
  57243. return MirrorTexture;
  57244. }(BABYLON.RenderTargetTexture));
  57245. BABYLON.MirrorTexture = MirrorTexture;
  57246. })(BABYLON || (BABYLON = {}));
  57247. //# sourceMappingURL=babylon.mirrorTexture.js.map
  57248. var BABYLON;
  57249. (function (BABYLON) {
  57250. /**
  57251. * Creates a refraction texture used by refraction channel of the standard material.
  57252. * @param name the texture name
  57253. * @param size size of the underlying texture
  57254. * @param scene root scene
  57255. */
  57256. var RefractionTexture = /** @class */ (function (_super) {
  57257. __extends(RefractionTexture, _super);
  57258. function RefractionTexture(name, size, scene, generateMipMaps) {
  57259. var _this = _super.call(this, name, size, scene, generateMipMaps, true) || this;
  57260. _this.refractionPlane = new BABYLON.Plane(0, 1, 0, 1);
  57261. _this.depth = 2.0;
  57262. _this.onBeforeRenderObservable.add(function () {
  57263. scene.clipPlane = _this.refractionPlane;
  57264. });
  57265. _this.onAfterRenderObservable.add(function () {
  57266. delete scene.clipPlane;
  57267. });
  57268. return _this;
  57269. }
  57270. RefractionTexture.prototype.clone = function () {
  57271. var scene = this.getScene();
  57272. if (!scene) {
  57273. return this;
  57274. }
  57275. var textureSize = this.getSize();
  57276. var newTexture = new RefractionTexture(this.name, textureSize.width, scene, this._generateMipMaps);
  57277. // Base texture
  57278. newTexture.hasAlpha = this.hasAlpha;
  57279. newTexture.level = this.level;
  57280. // Refraction Texture
  57281. newTexture.refractionPlane = this.refractionPlane.clone();
  57282. if (this.renderList) {
  57283. newTexture.renderList = this.renderList.slice(0);
  57284. }
  57285. newTexture.depth = this.depth;
  57286. return newTexture;
  57287. };
  57288. RefractionTexture.prototype.serialize = function () {
  57289. if (!this.name) {
  57290. return null;
  57291. }
  57292. var serializationObject = _super.prototype.serialize.call(this);
  57293. serializationObject.mirrorPlane = this.refractionPlane.asArray();
  57294. serializationObject.depth = this.depth;
  57295. return serializationObject;
  57296. };
  57297. return RefractionTexture;
  57298. }(BABYLON.RenderTargetTexture));
  57299. BABYLON.RefractionTexture = RefractionTexture;
  57300. })(BABYLON || (BABYLON = {}));
  57301. //# sourceMappingURL=babylon.refractionTexture.js.map
  57302. var BABYLON;
  57303. (function (BABYLON) {
  57304. var DynamicTexture = /** @class */ (function (_super) {
  57305. __extends(DynamicTexture, _super);
  57306. function DynamicTexture(name, options, scene, generateMipMaps, samplingMode, format) {
  57307. if (scene === void 0) { scene = null; }
  57308. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  57309. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  57310. var _this = _super.call(this, null, scene, !generateMipMaps, undefined, samplingMode, undefined, undefined, undefined, undefined, format) || this;
  57311. _this.name = name;
  57312. _this._engine = _this.getScene().getEngine();
  57313. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  57314. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  57315. _this._generateMipMaps = generateMipMaps;
  57316. if (options.getContext) {
  57317. _this._canvas = options;
  57318. _this._texture = _this._engine.createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  57319. }
  57320. else {
  57321. _this._canvas = document.createElement("canvas");
  57322. if (options.width) {
  57323. _this._texture = _this._engine.createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  57324. }
  57325. else {
  57326. _this._texture = _this._engine.createDynamicTexture(options, options, generateMipMaps, samplingMode);
  57327. }
  57328. }
  57329. var textureSize = _this.getSize();
  57330. _this._canvas.width = textureSize.width;
  57331. _this._canvas.height = textureSize.height;
  57332. _this._context = _this._canvas.getContext("2d");
  57333. return _this;
  57334. }
  57335. Object.defineProperty(DynamicTexture.prototype, "canRescale", {
  57336. get: function () {
  57337. return true;
  57338. },
  57339. enumerable: true,
  57340. configurable: true
  57341. });
  57342. DynamicTexture.prototype._recreate = function (textureSize) {
  57343. this._canvas.width = textureSize.width;
  57344. this._canvas.height = textureSize.height;
  57345. this.releaseInternalTexture();
  57346. this._texture = this._engine.createDynamicTexture(textureSize.width, textureSize.height, this._generateMipMaps, this._samplingMode);
  57347. };
  57348. DynamicTexture.prototype.scale = function (ratio) {
  57349. var textureSize = this.getSize();
  57350. textureSize.width *= ratio;
  57351. textureSize.height *= ratio;
  57352. this._recreate(textureSize);
  57353. };
  57354. DynamicTexture.prototype.scaleTo = function (width, height) {
  57355. var textureSize = this.getSize();
  57356. textureSize.width = width;
  57357. textureSize.height = height;
  57358. this._recreate(textureSize);
  57359. };
  57360. DynamicTexture.prototype.getContext = function () {
  57361. return this._context;
  57362. };
  57363. DynamicTexture.prototype.clear = function () {
  57364. var size = this.getSize();
  57365. this._context.fillRect(0, 0, size.width, size.height);
  57366. };
  57367. DynamicTexture.prototype.update = function (invertY) {
  57368. this._engine.updateDynamicTexture(this._texture, this._canvas, invertY === undefined ? true : invertY, undefined, this._format || undefined);
  57369. };
  57370. DynamicTexture.prototype.drawText = function (text, x, y, font, color, clearColor, invertY, update) {
  57371. if (update === void 0) { update = true; }
  57372. var size = this.getSize();
  57373. if (clearColor) {
  57374. this._context.fillStyle = clearColor;
  57375. this._context.fillRect(0, 0, size.width, size.height);
  57376. }
  57377. this._context.font = font;
  57378. if (x === null || x === undefined) {
  57379. var textSize = this._context.measureText(text);
  57380. x = (size.width - textSize.width) / 2;
  57381. }
  57382. if (y === null || y === undefined) {
  57383. var fontSize = parseInt((font.replace(/\D/g, '')));
  57384. ;
  57385. y = (size.height / 2) + (fontSize / 3.65);
  57386. }
  57387. this._context.fillStyle = color;
  57388. this._context.fillText(text, x, y);
  57389. if (update) {
  57390. this.update(invertY);
  57391. }
  57392. };
  57393. DynamicTexture.prototype.clone = function () {
  57394. var scene = this.getScene();
  57395. if (!scene) {
  57396. return this;
  57397. }
  57398. var textureSize = this.getSize();
  57399. var newTexture = new DynamicTexture(this.name, textureSize, scene, this._generateMipMaps);
  57400. // Base texture
  57401. newTexture.hasAlpha = this.hasAlpha;
  57402. newTexture.level = this.level;
  57403. // Dynamic Texture
  57404. newTexture.wrapU = this.wrapU;
  57405. newTexture.wrapV = this.wrapV;
  57406. return newTexture;
  57407. };
  57408. DynamicTexture.prototype._rebuild = function () {
  57409. this.update();
  57410. };
  57411. return DynamicTexture;
  57412. }(BABYLON.Texture));
  57413. BABYLON.DynamicTexture = DynamicTexture;
  57414. })(BABYLON || (BABYLON = {}));
  57415. //# sourceMappingURL=babylon.dynamicTexture.js.map
  57416. var BABYLON;
  57417. (function (BABYLON) {
  57418. var VideoTexture = /** @class */ (function (_super) {
  57419. __extends(VideoTexture, _super);
  57420. /**
  57421. * Creates a video texture.
  57422. * Sample : https://doc.babylonjs.com/how_to/video_texture
  57423. * @param {string | null} name optional name, will detect from video source, if not defined
  57424. * @param {(string | string[] | HTMLVideoElement)} src can be used to provide an url, array of urls or an already setup HTML video element.
  57425. * @param {BABYLON.Scene} scene is obviously the current scene.
  57426. * @param {boolean} generateMipMaps can be used to turn on mipmaps (Can be expensive for videoTextures because they are often updated).
  57427. * @param {boolean} invertY is false by default but can be used to invert video on Y axis
  57428. * @param {number} samplingMode controls the sampling method and is set to TRILINEAR_SAMPLINGMODE by default
  57429. * @param {VideoTextureSettings} [settings] allows finer control over video usage
  57430. */
  57431. function VideoTexture(name, src, scene, generateMipMaps, invertY, samplingMode, settings) {
  57432. if (generateMipMaps === void 0) { generateMipMaps = false; }
  57433. if (invertY === void 0) { invertY = false; }
  57434. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  57435. if (settings === void 0) { settings = {
  57436. autoPlay: true,
  57437. loop: true,
  57438. autoUpdateTexture: true,
  57439. }; }
  57440. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  57441. _this._createInternalTexture = function () {
  57442. if (_this._texture != null) {
  57443. return;
  57444. }
  57445. if (!_this._engine.needPOTTextures ||
  57446. (BABYLON.Tools.IsExponentOfTwo(_this.video.videoWidth) && BABYLON.Tools.IsExponentOfTwo(_this.video.videoHeight))) {
  57447. _this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  57448. _this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  57449. }
  57450. else {
  57451. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  57452. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  57453. _this._generateMipMaps = false;
  57454. }
  57455. _this._texture = _this._engine.createDynamicTexture(_this.video.videoWidth, _this.video.videoHeight, _this._generateMipMaps, _this._samplingMode);
  57456. _this._texture.isReady = true;
  57457. _this._updateInternalTexture();
  57458. };
  57459. _this.reset = function () {
  57460. if (_this._texture == null) {
  57461. return;
  57462. }
  57463. _this._texture.dispose();
  57464. _this._texture = null;
  57465. };
  57466. _this._updateInternalTexture = function (e) {
  57467. if (_this._texture == null || !_this._texture.isReady) {
  57468. return;
  57469. }
  57470. if (_this.video.readyState < _this.video.HAVE_CURRENT_DATA) {
  57471. return;
  57472. }
  57473. _this._engine.updateVideoTexture(_this._texture, _this.video, _this._invertY);
  57474. };
  57475. _this._engine = _this.getScene().getEngine();
  57476. _this._generateMipMaps = generateMipMaps;
  57477. _this._samplingMode = samplingMode;
  57478. _this.autoUpdateTexture = settings.autoUpdateTexture;
  57479. _this.name = name || _this._getName(src);
  57480. _this.video = _this._getVideo(src);
  57481. if (settings.autoPlay !== undefined) {
  57482. _this.video.autoplay = settings.autoPlay;
  57483. }
  57484. if (settings.loop !== undefined) {
  57485. _this.video.loop = settings.loop;
  57486. }
  57487. _this.video.addEventListener("canplay", _this._createInternalTexture);
  57488. _this.video.addEventListener("paused", _this._updateInternalTexture);
  57489. _this.video.addEventListener("seeked", _this._updateInternalTexture);
  57490. _this.video.addEventListener("emptied", _this.reset);
  57491. if (_this.video.readyState >= _this.video.HAVE_CURRENT_DATA) {
  57492. _this._createInternalTexture();
  57493. }
  57494. return _this;
  57495. }
  57496. VideoTexture.prototype._getName = function (src) {
  57497. if (src instanceof HTMLVideoElement) {
  57498. return src.currentSrc;
  57499. }
  57500. if (typeof src === "object") {
  57501. return src.toString();
  57502. }
  57503. return src;
  57504. };
  57505. ;
  57506. VideoTexture.prototype._getVideo = function (src) {
  57507. if (src instanceof HTMLVideoElement) {
  57508. BABYLON.Tools.SetCorsBehavior(src.currentSrc, src);
  57509. return src;
  57510. }
  57511. var video = document.createElement("video");
  57512. if (typeof src === "string") {
  57513. BABYLON.Tools.SetCorsBehavior(src, video);
  57514. video.src = src;
  57515. }
  57516. else {
  57517. BABYLON.Tools.SetCorsBehavior(src[0], video);
  57518. src.forEach(function (url) {
  57519. var source = document.createElement("source");
  57520. source.src = url;
  57521. video.appendChild(source);
  57522. });
  57523. }
  57524. return video;
  57525. };
  57526. ;
  57527. /**
  57528. * Internal method to initiate `update`.
  57529. */
  57530. VideoTexture.prototype._rebuild = function () {
  57531. this.update();
  57532. };
  57533. /**
  57534. * Update Texture in the `auto` mode. Does not do anything if `settings.autoUpdateTexture` is false.
  57535. */
  57536. VideoTexture.prototype.update = function () {
  57537. if (!this.autoUpdateTexture) {
  57538. // Expecting user to call `updateTexture` manually
  57539. return;
  57540. }
  57541. this.updateTexture(true);
  57542. };
  57543. /**
  57544. * Update Texture in `manual` mode. Does not do anything if not visible or paused.
  57545. * @param isVisible Visibility state, detected by user using `scene.getActiveMeshes()` or othervise.
  57546. */
  57547. VideoTexture.prototype.updateTexture = function (isVisible) {
  57548. if (!isVisible) {
  57549. return;
  57550. }
  57551. if (this.video.paused) {
  57552. return;
  57553. }
  57554. this._updateInternalTexture();
  57555. };
  57556. /**
  57557. * Change video content. Changing video instance or setting multiple urls (as in constructor) is not supported.
  57558. * @param url New url.
  57559. */
  57560. VideoTexture.prototype.updateURL = function (url) {
  57561. this.video.src = url;
  57562. };
  57563. VideoTexture.prototype.dispose = function () {
  57564. _super.prototype.dispose.call(this);
  57565. this.video.removeEventListener("canplay", this._createInternalTexture);
  57566. this.video.removeEventListener("paused", this._updateInternalTexture);
  57567. this.video.removeEventListener("seeked", this._updateInternalTexture);
  57568. this.video.removeEventListener("emptied", this.reset);
  57569. };
  57570. VideoTexture.CreateFromWebCam = function (scene, onReady, constraints) {
  57571. var video = document.createElement("video");
  57572. var constraintsDeviceId;
  57573. if (constraints && constraints.deviceId) {
  57574. constraintsDeviceId = {
  57575. exact: constraints.deviceId,
  57576. };
  57577. }
  57578. navigator.getUserMedia =
  57579. navigator.getUserMedia ||
  57580. navigator.webkitGetUserMedia ||
  57581. navigator.mozGetUserMedia ||
  57582. navigator.msGetUserMedia;
  57583. window.URL = window.URL || window.webkitURL || window.mozURL || window.msURL;
  57584. if (navigator.getUserMedia) {
  57585. navigator.getUserMedia({
  57586. video: {
  57587. deviceId: constraintsDeviceId,
  57588. width: {
  57589. min: (constraints && constraints.minWidth) || 256,
  57590. max: (constraints && constraints.maxWidth) || 640,
  57591. },
  57592. height: {
  57593. min: (constraints && constraints.minHeight) || 256,
  57594. max: (constraints && constraints.maxHeight) || 480,
  57595. },
  57596. },
  57597. }, function (stream) {
  57598. if (video.mozSrcObject !== undefined) {
  57599. // hack for Firefox < 19
  57600. video.mozSrcObject = stream;
  57601. }
  57602. else {
  57603. video.src = (window.URL && window.URL.createObjectURL(stream)) || stream;
  57604. }
  57605. video.play();
  57606. if (onReady) {
  57607. onReady(new VideoTexture("video", video, scene, true, true));
  57608. }
  57609. }, function (e) {
  57610. BABYLON.Tools.Error(e.name);
  57611. });
  57612. }
  57613. };
  57614. return VideoTexture;
  57615. }(BABYLON.Texture));
  57616. BABYLON.VideoTexture = VideoTexture;
  57617. })(BABYLON || (BABYLON = {}));
  57618. //# sourceMappingURL=babylon.videoTexture.js.map
  57619. var BABYLON;
  57620. (function (BABYLON) {
  57621. var RawTexture = /** @class */ (function (_super) {
  57622. __extends(RawTexture, _super);
  57623. function RawTexture(data, width, height, format, scene, generateMipMaps, invertY, samplingMode, type) {
  57624. if (generateMipMaps === void 0) { generateMipMaps = true; }
  57625. if (invertY === void 0) { invertY = false; }
  57626. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  57627. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  57628. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  57629. _this.format = format;
  57630. _this._engine = scene.getEngine();
  57631. _this._texture = scene.getEngine().createRawTexture(data, width, height, format, generateMipMaps, invertY, samplingMode, null, type);
  57632. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  57633. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  57634. return _this;
  57635. }
  57636. RawTexture.prototype.update = function (data) {
  57637. this._engine.updateRawTexture(this._texture, data, this._texture.format, this._texture.invertY, undefined, this._texture.type);
  57638. };
  57639. // Statics
  57640. RawTexture.CreateLuminanceTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  57641. if (generateMipMaps === void 0) { generateMipMaps = true; }
  57642. if (invertY === void 0) { invertY = false; }
  57643. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  57644. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE, scene, generateMipMaps, invertY, samplingMode);
  57645. };
  57646. RawTexture.CreateLuminanceAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  57647. if (generateMipMaps === void 0) { generateMipMaps = true; }
  57648. if (invertY === void 0) { invertY = false; }
  57649. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  57650. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  57651. };
  57652. RawTexture.CreateAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  57653. if (generateMipMaps === void 0) { generateMipMaps = true; }
  57654. if (invertY === void 0) { invertY = false; }
  57655. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  57656. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  57657. };
  57658. RawTexture.CreateRGBTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode, type) {
  57659. if (generateMipMaps === void 0) { generateMipMaps = true; }
  57660. if (invertY === void 0) { invertY = false; }
  57661. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  57662. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  57663. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGB, scene, generateMipMaps, invertY, samplingMode, type);
  57664. };
  57665. RawTexture.CreateRGBATexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode, type) {
  57666. if (generateMipMaps === void 0) { generateMipMaps = true; }
  57667. if (invertY === void 0) { invertY = false; }
  57668. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  57669. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  57670. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGBA, scene, generateMipMaps, invertY, samplingMode, type);
  57671. };
  57672. return RawTexture;
  57673. }(BABYLON.Texture));
  57674. BABYLON.RawTexture = RawTexture;
  57675. })(BABYLON || (BABYLON = {}));
  57676. //# sourceMappingURL=babylon.rawTexture.js.map
  57677. var BABYLON;
  57678. (function (BABYLON) {
  57679. /**
  57680. * PostProcess can be used to apply a shader to a texture after it has been rendered
  57681. * See https://doc.babylonjs.com/how_to/how_to_use_postprocesses
  57682. */
  57683. var PostProcess = /** @class */ (function () {
  57684. /**
  57685. * Creates a new instance of @see PostProcess
  57686. * @param name The name of the PostProcess.
  57687. * @param fragmentUrl The url of the fragment shader to be used.
  57688. * @param parameters Array of the names of uniform non-sampler2D variables that will be passed to the shader.
  57689. * @param samplers Array of the names of uniform sampler2D variables that will be passed to the shader.
  57690. * @param options The required width/height ratio to downsize to before computing the render pass. (Use 1.0 for full size)
  57691. * @param camera The camera to apply the render pass to.
  57692. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  57693. * @param engine The engine which the post process will be applied. (default: current engine)
  57694. * @param reusable If the post process can be reused on the same frame. (default: false)
  57695. * @param defines String of defines that will be set when running the fragment shader. (default: null)
  57696. * @param textureType Type of textures used when performing the post process. (default: 0)
  57697. * @param vertexUrl The url of the vertex shader to be used. (default: "postprocess")
  57698. * @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
  57699. * @param blockCompilation If the shader should not be compiled imediatly. (default: false)
  57700. */
  57701. function PostProcess(/** Name of the PostProcess. */ name, fragmentUrl, parameters, samplers, options, camera, samplingMode, engine, reusable, defines, textureType, vertexUrl, indexParameters, blockCompilation) {
  57702. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE; }
  57703. if (defines === void 0) { defines = null; }
  57704. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  57705. if (vertexUrl === void 0) { vertexUrl = "postprocess"; }
  57706. if (blockCompilation === void 0) { blockCompilation = false; }
  57707. this.name = name;
  57708. /**
  57709. * Width of the texture to apply the post process on
  57710. */
  57711. this.width = -1;
  57712. /**
  57713. * Height of the texture to apply the post process on
  57714. */
  57715. this.height = -1;
  57716. /**
  57717. * If the buffer needs to be cleared before applying the post process. (default: true)
  57718. * Should be set to false if shader will overwrite all previous pixels.
  57719. */
  57720. this.autoClear = true;
  57721. /**
  57722. * Type of alpha mode to use when performing the post process (default: Engine.ALPHA_DISABLE)
  57723. */
  57724. this.alphaMode = BABYLON.Engine.ALPHA_DISABLE;
  57725. /**
  57726. * Animations to be used for the post processing
  57727. */
  57728. this.animations = new Array();
  57729. /**
  57730. * Enable Pixel Perfect mode where texture is not scaled to be power of 2.
  57731. * Can only be used on a single postprocess or on the last one of a chain. (default: false)
  57732. */
  57733. this.enablePixelPerfectMode = false;
  57734. /**
  57735. * Scale mode for the post process (default: Engine.SCALEMODE_FLOOR)
  57736. */
  57737. this.scaleMode = BABYLON.Engine.SCALEMODE_FLOOR;
  57738. /**
  57739. * Force textures to be a power of two (default: false)
  57740. */
  57741. this.alwaysForcePOT = false;
  57742. /**
  57743. * Number of sample textures (default: 1)
  57744. */
  57745. this.samples = 1;
  57746. /**
  57747. * Modify the scale of the post process to be the same as the viewport (default: false)
  57748. */
  57749. this.adaptScaleToCurrentViewport = false;
  57750. this._reusable = false;
  57751. /**
  57752. * Smart array of input and output textures for the post process.
  57753. */
  57754. this._textures = new BABYLON.SmartArray(2);
  57755. /**
  57756. * The index in _textures that corresponds to the output texture.
  57757. */
  57758. this._currentRenderTextureInd = 0;
  57759. this._scaleRatio = new BABYLON.Vector2(1, 1);
  57760. this._texelSize = BABYLON.Vector2.Zero();
  57761. // Events
  57762. /**
  57763. * An event triggered when the postprocess is activated.
  57764. * @type {BABYLON.Observable}
  57765. */
  57766. this.onActivateObservable = new BABYLON.Observable();
  57767. /**
  57768. * An event triggered when the postprocess changes its size.
  57769. * @type {BABYLON.Observable}
  57770. */
  57771. this.onSizeChangedObservable = new BABYLON.Observable();
  57772. /**
  57773. * An event triggered when the postprocess applies its effect.
  57774. * @type {BABYLON.Observable}
  57775. */
  57776. this.onApplyObservable = new BABYLON.Observable();
  57777. /**
  57778. * An event triggered before rendering the postprocess
  57779. * @type {BABYLON.Observable}
  57780. */
  57781. this.onBeforeRenderObservable = new BABYLON.Observable();
  57782. /**
  57783. * An event triggered after rendering the postprocess
  57784. * @type {BABYLON.Observable}
  57785. */
  57786. this.onAfterRenderObservable = new BABYLON.Observable();
  57787. if (camera != null) {
  57788. this._camera = camera;
  57789. this._scene = camera.getScene();
  57790. camera.attachPostProcess(this);
  57791. this._engine = this._scene.getEngine();
  57792. this._scene.postProcesses.push(this);
  57793. }
  57794. else if (engine) {
  57795. this._engine = engine;
  57796. this._engine.postProcesses.push(this);
  57797. }
  57798. this._options = options;
  57799. this.renderTargetSamplingMode = samplingMode ? samplingMode : BABYLON.Texture.NEAREST_SAMPLINGMODE;
  57800. this._reusable = reusable || false;
  57801. this._textureType = textureType;
  57802. this._samplers = samplers || [];
  57803. this._samplers.push("textureSampler");
  57804. this._fragmentUrl = fragmentUrl;
  57805. this._vertexUrl = vertexUrl;
  57806. this._parameters = parameters || [];
  57807. this._parameters.push("scale");
  57808. this._indexParameters = indexParameters;
  57809. if (!blockCompilation) {
  57810. this.updateEffect(defines);
  57811. }
  57812. }
  57813. Object.defineProperty(PostProcess.prototype, "onActivate", {
  57814. /**
  57815. * A function that is added to the onActivateObservable
  57816. */
  57817. set: function (callback) {
  57818. if (this._onActivateObserver) {
  57819. this.onActivateObservable.remove(this._onActivateObserver);
  57820. }
  57821. if (callback) {
  57822. this._onActivateObserver = this.onActivateObservable.add(callback);
  57823. }
  57824. },
  57825. enumerable: true,
  57826. configurable: true
  57827. });
  57828. Object.defineProperty(PostProcess.prototype, "onSizeChanged", {
  57829. /**
  57830. * A function that is added to the onSizeChangedObservable
  57831. */
  57832. set: function (callback) {
  57833. if (this._onSizeChangedObserver) {
  57834. this.onSizeChangedObservable.remove(this._onSizeChangedObserver);
  57835. }
  57836. this._onSizeChangedObserver = this.onSizeChangedObservable.add(callback);
  57837. },
  57838. enumerable: true,
  57839. configurable: true
  57840. });
  57841. Object.defineProperty(PostProcess.prototype, "onApply", {
  57842. /**
  57843. * A function that is added to the onApplyObservable
  57844. */
  57845. set: function (callback) {
  57846. if (this._onApplyObserver) {
  57847. this.onApplyObservable.remove(this._onApplyObserver);
  57848. }
  57849. this._onApplyObserver = this.onApplyObservable.add(callback);
  57850. },
  57851. enumerable: true,
  57852. configurable: true
  57853. });
  57854. Object.defineProperty(PostProcess.prototype, "onBeforeRender", {
  57855. /**
  57856. * A function that is added to the onBeforeRenderObservable
  57857. */
  57858. set: function (callback) {
  57859. if (this._onBeforeRenderObserver) {
  57860. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  57861. }
  57862. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  57863. },
  57864. enumerable: true,
  57865. configurable: true
  57866. });
  57867. Object.defineProperty(PostProcess.prototype, "onAfterRender", {
  57868. /**
  57869. * A function that is added to the onAfterRenderObservable
  57870. */
  57871. set: function (callback) {
  57872. if (this._onAfterRenderObserver) {
  57873. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  57874. }
  57875. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  57876. },
  57877. enumerable: true,
  57878. configurable: true
  57879. });
  57880. Object.defineProperty(PostProcess.prototype, "inputTexture", {
  57881. /**
  57882. * 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
  57883. * render it's output into this texture and this texture will be used as textureSampler in the fragment shader of this post process.
  57884. */
  57885. get: function () {
  57886. return this._textures.data[this._currentRenderTextureInd];
  57887. },
  57888. set: function (value) {
  57889. this._forcedOutputTexture = value;
  57890. },
  57891. enumerable: true,
  57892. configurable: true
  57893. });
  57894. /**
  57895. * Gets the camera which post process is applied to.
  57896. * @returns The camera the post process is applied to.
  57897. */
  57898. PostProcess.prototype.getCamera = function () {
  57899. return this._camera;
  57900. };
  57901. Object.defineProperty(PostProcess.prototype, "texelSize", {
  57902. /**
  57903. * Gets the texel size of the postprocess.
  57904. * See https://en.wikipedia.org/wiki/Texel_(graphics)
  57905. */
  57906. get: function () {
  57907. if (this._shareOutputWithPostProcess) {
  57908. return this._shareOutputWithPostProcess.texelSize;
  57909. }
  57910. if (this._forcedOutputTexture) {
  57911. this._texelSize.copyFromFloats(1.0 / this._forcedOutputTexture.width, 1.0 / this._forcedOutputTexture.height);
  57912. }
  57913. return this._texelSize;
  57914. },
  57915. enumerable: true,
  57916. configurable: true
  57917. });
  57918. /**
  57919. * Gets the engine which this post process belongs to.
  57920. * @returns The engine the post process was enabled with.
  57921. */
  57922. PostProcess.prototype.getEngine = function () {
  57923. return this._engine;
  57924. };
  57925. /**
  57926. * The effect that is created when initializing the post process.
  57927. * @returns The created effect corrisponding the the postprocess.
  57928. */
  57929. PostProcess.prototype.getEffect = function () {
  57930. return this._effect;
  57931. };
  57932. /**
  57933. * To avoid multiple redundant textures for multiple post process, the output the output texture for this post process can be shared with another.
  57934. * @param postProcess The post process to share the output with.
  57935. * @returns This post process.
  57936. */
  57937. PostProcess.prototype.shareOutputWith = function (postProcess) {
  57938. this._disposeTextures();
  57939. this._shareOutputWithPostProcess = postProcess;
  57940. return this;
  57941. };
  57942. /**
  57943. * Updates the effect with the current post process compile time values and recompiles the shader.
  57944. * @param defines Define statements that should be added at the beginning of the shader. (default: null)
  57945. * @param uniforms Set of uniform variables that will be passed to the shader. (default: null)
  57946. * @param samplers Set of Texture2D variables that will be passed to the shader. (default: null)
  57947. * @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
  57948. * @param onCompiled Called when the shader has been compiled.
  57949. * @param onError Called if there is an error when compiling a shader.
  57950. */
  57951. PostProcess.prototype.updateEffect = function (defines, uniforms, samplers, indexParameters, onCompiled, onError) {
  57952. if (defines === void 0) { defines = null; }
  57953. if (uniforms === void 0) { uniforms = null; }
  57954. if (samplers === void 0) { samplers = null; }
  57955. 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);
  57956. };
  57957. /**
  57958. * The post process is reusable if it can be used multiple times within one frame.
  57959. * @returns If the post process is reusable
  57960. */
  57961. PostProcess.prototype.isReusable = function () {
  57962. return this._reusable;
  57963. };
  57964. /** invalidate frameBuffer to hint the postprocess to create a depth buffer */
  57965. PostProcess.prototype.markTextureDirty = function () {
  57966. this.width = -1;
  57967. };
  57968. /**
  57969. * Activates the post process by intializing the textures to be used when executed. Notifies onActivateObservable.
  57970. * 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.
  57971. * @param camera The camera that will be used in the post process. This camera will be used when calling onActivateObservable.
  57972. * @param sourceTexture The source texture to be inspected to get the width and height if not specified in the post process constructor. (default: null)
  57973. * @param forceDepthStencil If true, a depth and stencil buffer will be generated. (default: false)
  57974. */
  57975. PostProcess.prototype.activate = function (camera, sourceTexture, forceDepthStencil) {
  57976. var _this = this;
  57977. if (sourceTexture === void 0) { sourceTexture = null; }
  57978. camera = camera || this._camera;
  57979. var scene = camera.getScene();
  57980. var engine = scene.getEngine();
  57981. var maxSize = engine.getCaps().maxTextureSize;
  57982. var requiredWidth = ((sourceTexture ? sourceTexture.width : this._engine.getRenderWidth(true)) * this._options) | 0;
  57983. var requiredHeight = ((sourceTexture ? sourceTexture.height : this._engine.getRenderHeight(true)) * this._options) | 0;
  57984. var desiredWidth = (this._options.width || requiredWidth);
  57985. var desiredHeight = this._options.height || requiredHeight;
  57986. if (!this._shareOutputWithPostProcess && !this._forcedOutputTexture) {
  57987. if (this.adaptScaleToCurrentViewport) {
  57988. var currentViewport = engine.currentViewport;
  57989. if (currentViewport) {
  57990. desiredWidth *= currentViewport.width;
  57991. desiredHeight *= currentViewport.height;
  57992. }
  57993. }
  57994. if (this.renderTargetSamplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE || this.alwaysForcePOT) {
  57995. if (!this._options.width) {
  57996. desiredWidth = engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(desiredWidth, maxSize, this.scaleMode) : desiredWidth;
  57997. }
  57998. if (!this._options.height) {
  57999. desiredHeight = engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(desiredHeight, maxSize, this.scaleMode) : desiredHeight;
  58000. }
  58001. }
  58002. if (this.width !== desiredWidth || this.height !== desiredHeight) {
  58003. if (this._textures.length > 0) {
  58004. for (var i = 0; i < this._textures.length; i++) {
  58005. this._engine._releaseTexture(this._textures.data[i]);
  58006. }
  58007. this._textures.reset();
  58008. }
  58009. this.width = desiredWidth;
  58010. this.height = desiredHeight;
  58011. var textureSize = { width: this.width, height: this.height };
  58012. var textureOptions = {
  58013. generateMipMaps: false,
  58014. generateDepthBuffer: forceDepthStencil || camera._postProcesses.indexOf(this) === 0,
  58015. generateStencilBuffer: (forceDepthStencil || camera._postProcesses.indexOf(this) === 0) && this._engine.isStencilEnable,
  58016. samplingMode: this.renderTargetSamplingMode,
  58017. type: this._textureType
  58018. };
  58019. this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));
  58020. if (this._reusable) {
  58021. this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));
  58022. }
  58023. this._texelSize.copyFromFloats(1.0 / this.width, 1.0 / this.height);
  58024. this.onSizeChangedObservable.notifyObservers(this);
  58025. }
  58026. this._textures.forEach(function (texture) {
  58027. if (texture.samples !== _this.samples) {
  58028. _this._engine.updateRenderTargetTextureSampleCount(texture, _this.samples);
  58029. }
  58030. });
  58031. }
  58032. var target;
  58033. if (this._shareOutputWithPostProcess) {
  58034. target = this._shareOutputWithPostProcess.inputTexture;
  58035. }
  58036. else if (this._forcedOutputTexture) {
  58037. target = this._forcedOutputTexture;
  58038. this.width = this._forcedOutputTexture.width;
  58039. this.height = this._forcedOutputTexture.height;
  58040. }
  58041. else {
  58042. target = this.inputTexture;
  58043. }
  58044. // Bind the input of this post process to be used as the output of the previous post process.
  58045. if (this.enablePixelPerfectMode) {
  58046. this._scaleRatio.copyFromFloats(requiredWidth / desiredWidth, requiredHeight / desiredHeight);
  58047. this._engine.bindFramebuffer(target, 0, requiredWidth, requiredHeight, true);
  58048. }
  58049. else {
  58050. this._scaleRatio.copyFromFloats(1, 1);
  58051. this._engine.bindFramebuffer(target, 0, undefined, undefined, true);
  58052. }
  58053. this.onActivateObservable.notifyObservers(camera);
  58054. // Clear
  58055. if (this.autoClear && this.alphaMode === BABYLON.Engine.ALPHA_DISABLE) {
  58056. this._engine.clear(this.clearColor ? this.clearColor : scene.clearColor, true, true, true);
  58057. }
  58058. if (this._reusable) {
  58059. this._currentRenderTextureInd = (this._currentRenderTextureInd + 1) % 2;
  58060. }
  58061. };
  58062. Object.defineProperty(PostProcess.prototype, "isSupported", {
  58063. /**
  58064. * If the post process is supported.
  58065. */
  58066. get: function () {
  58067. return this._effect.isSupported;
  58068. },
  58069. enumerable: true,
  58070. configurable: true
  58071. });
  58072. Object.defineProperty(PostProcess.prototype, "aspectRatio", {
  58073. /**
  58074. * The aspect ratio of the output texture.
  58075. */
  58076. get: function () {
  58077. if (this._shareOutputWithPostProcess) {
  58078. return this._shareOutputWithPostProcess.aspectRatio;
  58079. }
  58080. if (this._forcedOutputTexture) {
  58081. return this._forcedOutputTexture.width / this._forcedOutputTexture.height;
  58082. }
  58083. return this.width / this.height;
  58084. },
  58085. enumerable: true,
  58086. configurable: true
  58087. });
  58088. /**
  58089. * Get a value indicating if the post-process is ready to be used
  58090. * @returns true if the post-process is ready (shader is compiled)
  58091. */
  58092. PostProcess.prototype.isReady = function () {
  58093. return this._effect && this._effect.isReady();
  58094. };
  58095. /**
  58096. * Binds all textures and uniforms to the shader, this will be run on every pass.
  58097. * @returns the effect corrisponding to this post process. Null if not compiled or not ready.
  58098. */
  58099. PostProcess.prototype.apply = function () {
  58100. // Check
  58101. if (!this._effect || !this._effect.isReady())
  58102. return null;
  58103. // States
  58104. this._engine.enableEffect(this._effect);
  58105. this._engine.setState(false);
  58106. this._engine.setDepthBuffer(false);
  58107. this._engine.setDepthWrite(false);
  58108. // Alpha
  58109. this._engine.setAlphaMode(this.alphaMode);
  58110. if (this.alphaConstants) {
  58111. this.getEngine().setAlphaConstants(this.alphaConstants.r, this.alphaConstants.g, this.alphaConstants.b, this.alphaConstants.a);
  58112. }
  58113. // Bind the output texture of the preivous post process as the input to this post process.
  58114. var source;
  58115. if (this._shareOutputWithPostProcess) {
  58116. source = this._shareOutputWithPostProcess.inputTexture;
  58117. }
  58118. else if (this._forcedOutputTexture) {
  58119. source = this._forcedOutputTexture;
  58120. }
  58121. else {
  58122. source = this.inputTexture;
  58123. }
  58124. this._effect._bindTexture("textureSampler", source);
  58125. // Parameters
  58126. this._effect.setVector2("scale", this._scaleRatio);
  58127. this.onApplyObservable.notifyObservers(this._effect);
  58128. return this._effect;
  58129. };
  58130. PostProcess.prototype._disposeTextures = function () {
  58131. if (this._shareOutputWithPostProcess || this._forcedOutputTexture) {
  58132. return;
  58133. }
  58134. if (this._textures.length > 0) {
  58135. for (var i = 0; i < this._textures.length; i++) {
  58136. this._engine._releaseTexture(this._textures.data[i]);
  58137. }
  58138. }
  58139. this._textures.dispose();
  58140. };
  58141. /**
  58142. * Disposes the post process.
  58143. * @param camera The camera to dispose the post process on.
  58144. */
  58145. PostProcess.prototype.dispose = function (camera) {
  58146. camera = camera || this._camera;
  58147. this._disposeTextures();
  58148. if (this._scene) {
  58149. var index_1 = this._scene.postProcesses.indexOf(this);
  58150. if (index_1 !== -1) {
  58151. this._scene.postProcesses.splice(index_1, 1);
  58152. }
  58153. }
  58154. else {
  58155. var index_2 = this._engine.postProcesses.indexOf(this);
  58156. if (index_2 !== -1) {
  58157. this._engine.postProcesses.splice(index_2, 1);
  58158. }
  58159. }
  58160. if (!camera) {
  58161. return;
  58162. }
  58163. camera.detachPostProcess(this);
  58164. var index = camera._postProcesses.indexOf(this);
  58165. if (index === 0 && camera._postProcesses.length > 0) {
  58166. this._camera._postProcesses[0].markTextureDirty();
  58167. }
  58168. this.onActivateObservable.clear();
  58169. this.onAfterRenderObservable.clear();
  58170. this.onApplyObservable.clear();
  58171. this.onBeforeRenderObservable.clear();
  58172. this.onSizeChangedObservable.clear();
  58173. };
  58174. return PostProcess;
  58175. }());
  58176. BABYLON.PostProcess = PostProcess;
  58177. })(BABYLON || (BABYLON = {}));
  58178. //# sourceMappingURL=babylon.postProcess.js.map
  58179. var BABYLON;
  58180. (function (BABYLON) {
  58181. var PassPostProcess = /** @class */ (function (_super) {
  58182. __extends(PassPostProcess, _super);
  58183. function PassPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  58184. if (camera === void 0) { camera = null; }
  58185. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  58186. return _super.call(this, name, "pass", null, null, options, camera, samplingMode, engine, reusable, undefined, textureType) || this;
  58187. }
  58188. return PassPostProcess;
  58189. }(BABYLON.PostProcess));
  58190. BABYLON.PassPostProcess = PassPostProcess;
  58191. })(BABYLON || (BABYLON = {}));
  58192. //# sourceMappingURL=babylon.passPostProcess.js.map
  58193. var __assign = (this && this.__assign) || Object.assign || function(t) {
  58194. for (var s, i = 1, n = arguments.length; i < n; i++) {
  58195. s = arguments[i];
  58196. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  58197. t[p] = s[p];
  58198. }
  58199. return t;
  58200. };
  58201. var BABYLON;
  58202. (function (BABYLON) {
  58203. /**
  58204. * Default implementation of @see IShadowGenerator.
  58205. * This is the main object responsible of generating shadows in the framework.
  58206. * Documentation: https://doc.babylonjs.com/babylon101/shadows
  58207. */
  58208. var ShadowGenerator = /** @class */ (function () {
  58209. /**
  58210. * Creates a ShadowGenerator object.
  58211. * A ShadowGenerator is the required tool to use the shadows.
  58212. * Each light casting shadows needs to use its own ShadowGenerator.
  58213. * Documentation : http://doc.babylonjs.com/tutorials/shadows
  58214. * @param mapSize The size of the texture what stores the shadows. Example : 1024.
  58215. * @param light The light object generating the shadows.
  58216. * @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.
  58217. */
  58218. function ShadowGenerator(mapSize, light, useFullFloatFirst) {
  58219. this._bias = 0.00005;
  58220. this._blurBoxOffset = 1;
  58221. this._blurScale = 2;
  58222. this._blurKernel = 1;
  58223. this._useKernelBlur = false;
  58224. this._filter = ShadowGenerator.FILTER_NONE;
  58225. this._darkness = 0;
  58226. this._transparencyShadow = false;
  58227. /**
  58228. * Controls the extent to which the shadows fade out at the edge of the frustum
  58229. * Used only by directionals and spots
  58230. */
  58231. this.frustumEdgeFalloff = 0;
  58232. /**
  58233. * If true the shadow map is generated by rendering the back face of the mesh instead of the front face.
  58234. * This can help with self-shadowing as the geometry making up the back of objects is slightly offset.
  58235. * It might on the other hand introduce peter panning.
  58236. */
  58237. this.forceBackFacesOnly = false;
  58238. this._lightDirection = BABYLON.Vector3.Zero();
  58239. this._viewMatrix = BABYLON.Matrix.Zero();
  58240. this._projectionMatrix = BABYLON.Matrix.Zero();
  58241. this._transformMatrix = BABYLON.Matrix.Zero();
  58242. this._currentFaceIndex = 0;
  58243. this._currentFaceIndexCache = 0;
  58244. this._defaultTextureMatrix = BABYLON.Matrix.Identity();
  58245. this._mapSize = mapSize;
  58246. this._light = light;
  58247. this._scene = light.getScene();
  58248. light._shadowGenerator = this;
  58249. // Texture type fallback from float to int if not supported.
  58250. var caps = this._scene.getEngine().getCaps();
  58251. if (!useFullFloatFirst) {
  58252. if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {
  58253. this._textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  58254. }
  58255. else if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {
  58256. this._textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  58257. }
  58258. else {
  58259. this._textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  58260. }
  58261. }
  58262. else {
  58263. if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {
  58264. this._textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  58265. }
  58266. else if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {
  58267. this._textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  58268. }
  58269. else {
  58270. this._textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  58271. }
  58272. }
  58273. this._initializeGenerator();
  58274. }
  58275. Object.defineProperty(ShadowGenerator, "FILTER_NONE", {
  58276. /**
  58277. * Shadow generator mode None: no filtering applied.
  58278. */
  58279. get: function () {
  58280. return ShadowGenerator._FILTER_NONE;
  58281. },
  58282. enumerable: true,
  58283. configurable: true
  58284. });
  58285. Object.defineProperty(ShadowGenerator, "FILTER_POISSONSAMPLING", {
  58286. /**
  58287. * Shadow generator mode Poisson Sampling: Percentage Closer Filtering.
  58288. * (Multiple Tap around evenly distributed around the pixel are used to evaluate the shadow strength)
  58289. */
  58290. get: function () {
  58291. return ShadowGenerator._FILTER_POISSONSAMPLING;
  58292. },
  58293. enumerable: true,
  58294. configurable: true
  58295. });
  58296. Object.defineProperty(ShadowGenerator, "FILTER_EXPONENTIALSHADOWMAP", {
  58297. /**
  58298. * Shadow generator mode ESM: Exponential Shadow Mapping.
  58299. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  58300. */
  58301. get: function () {
  58302. return ShadowGenerator._FILTER_EXPONENTIALSHADOWMAP;
  58303. },
  58304. enumerable: true,
  58305. configurable: true
  58306. });
  58307. Object.defineProperty(ShadowGenerator, "FILTER_BLUREXPONENTIALSHADOWMAP", {
  58308. /**
  58309. * Shadow generator mode ESM: Blurred Exponential Shadow Mapping.
  58310. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  58311. */
  58312. get: function () {
  58313. return ShadowGenerator._FILTER_BLUREXPONENTIALSHADOWMAP;
  58314. },
  58315. enumerable: true,
  58316. configurable: true
  58317. });
  58318. Object.defineProperty(ShadowGenerator, "FILTER_CLOSEEXPONENTIALSHADOWMAP", {
  58319. /**
  58320. * Shadow generator mode ESM: Exponential Shadow Mapping using the inverse of the exponential preventing
  58321. * edge artifacts on steep falloff.
  58322. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  58323. */
  58324. get: function () {
  58325. return ShadowGenerator._FILTER_CLOSEEXPONENTIALSHADOWMAP;
  58326. },
  58327. enumerable: true,
  58328. configurable: true
  58329. });
  58330. Object.defineProperty(ShadowGenerator, "FILTER_BLURCLOSEEXPONENTIALSHADOWMAP", {
  58331. /**
  58332. * Shadow generator mode ESM: Blurred Exponential Shadow Mapping using the inverse of the exponential preventing
  58333. * edge artifacts on steep falloff.
  58334. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  58335. */
  58336. get: function () {
  58337. return ShadowGenerator._FILTER_BLURCLOSEEXPONENTIALSHADOWMAP;
  58338. },
  58339. enumerable: true,
  58340. configurable: true
  58341. });
  58342. Object.defineProperty(ShadowGenerator.prototype, "bias", {
  58343. /**
  58344. * Gets the bias: offset applied on the depth preventing acnea.
  58345. */
  58346. get: function () {
  58347. return this._bias;
  58348. },
  58349. /**
  58350. * Sets the bias: offset applied on the depth preventing acnea.
  58351. */
  58352. set: function (bias) {
  58353. this._bias = bias;
  58354. },
  58355. enumerable: true,
  58356. configurable: true
  58357. });
  58358. Object.defineProperty(ShadowGenerator.prototype, "blurBoxOffset", {
  58359. /**
  58360. * Gets the blur box offset: offset applied during the blur pass.
  58361. * Only usefull if useKernelBlur = false
  58362. */
  58363. get: function () {
  58364. return this._blurBoxOffset;
  58365. },
  58366. /**
  58367. * Sets the blur box offset: offset applied during the blur pass.
  58368. * Only usefull if useKernelBlur = false
  58369. */
  58370. set: function (value) {
  58371. if (this._blurBoxOffset === value) {
  58372. return;
  58373. }
  58374. this._blurBoxOffset = value;
  58375. this._disposeBlurPostProcesses();
  58376. },
  58377. enumerable: true,
  58378. configurable: true
  58379. });
  58380. Object.defineProperty(ShadowGenerator.prototype, "blurScale", {
  58381. /**
  58382. * Gets the blur scale: scale of the blurred texture compared to the main shadow map.
  58383. * 2 means half of the size.
  58384. */
  58385. get: function () {
  58386. return this._blurScale;
  58387. },
  58388. /**
  58389. * Sets the blur scale: scale of the blurred texture compared to the main shadow map.
  58390. * 2 means half of the size.
  58391. */
  58392. set: function (value) {
  58393. if (this._blurScale === value) {
  58394. return;
  58395. }
  58396. this._blurScale = value;
  58397. this._disposeBlurPostProcesses();
  58398. },
  58399. enumerable: true,
  58400. configurable: true
  58401. });
  58402. Object.defineProperty(ShadowGenerator.prototype, "blurKernel", {
  58403. /**
  58404. * Gets the blur kernel: kernel size of the blur pass.
  58405. * Only usefull if useKernelBlur = true
  58406. */
  58407. get: function () {
  58408. return this._blurKernel;
  58409. },
  58410. /**
  58411. * Sets the blur kernel: kernel size of the blur pass.
  58412. * Only usefull if useKernelBlur = true
  58413. */
  58414. set: function (value) {
  58415. if (this._blurKernel === value) {
  58416. return;
  58417. }
  58418. this._blurKernel = value;
  58419. this._disposeBlurPostProcesses();
  58420. },
  58421. enumerable: true,
  58422. configurable: true
  58423. });
  58424. Object.defineProperty(ShadowGenerator.prototype, "useKernelBlur", {
  58425. /**
  58426. * Gets whether the blur pass is a kernel blur (if true) or box blur.
  58427. * Only usefull in filtered mode (useBlurExponentialShadowMap...)
  58428. */
  58429. get: function () {
  58430. return this._useKernelBlur;
  58431. },
  58432. /**
  58433. * Sets whether the blur pass is a kernel blur (if true) or box blur.
  58434. * Only usefull in filtered mode (useBlurExponentialShadowMap...)
  58435. */
  58436. set: function (value) {
  58437. if (this._useKernelBlur === value) {
  58438. return;
  58439. }
  58440. this._useKernelBlur = value;
  58441. this._disposeBlurPostProcesses();
  58442. },
  58443. enumerable: true,
  58444. configurable: true
  58445. });
  58446. Object.defineProperty(ShadowGenerator.prototype, "depthScale", {
  58447. /**
  58448. * Gets the depth scale used in ESM mode.
  58449. */
  58450. get: function () {
  58451. return this._depthScale !== undefined ? this._depthScale : this._light.getDepthScale();
  58452. },
  58453. /**
  58454. * Sets the depth scale used in ESM mode.
  58455. * This can override the scale stored on the light.
  58456. */
  58457. set: function (value) {
  58458. this._depthScale = value;
  58459. },
  58460. enumerable: true,
  58461. configurable: true
  58462. });
  58463. Object.defineProperty(ShadowGenerator.prototype, "filter", {
  58464. /**
  58465. * Gets the current mode of the shadow generator (normal, PCF, ESM...).
  58466. * The returned value is a number equal to one of the available mode defined in ShadowMap.FILTER_x like _FILTER_NONE
  58467. */
  58468. get: function () {
  58469. return this._filter;
  58470. },
  58471. /**
  58472. * Sets the current mode of the shadow generator (normal, PCF, ESM...).
  58473. * The returned value is a number equal to one of the available mode defined in ShadowMap.FILTER_x like _FILTER_NONE
  58474. */
  58475. set: function (value) {
  58476. // Blurring the cubemap is going to be too expensive. Reverting to unblurred version
  58477. if (this._light.needCube()) {
  58478. if (value === ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP) {
  58479. this.useExponentialShadowMap = true;
  58480. return;
  58481. }
  58482. else if (value === ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP) {
  58483. this.useCloseExponentialShadowMap = true;
  58484. return;
  58485. }
  58486. }
  58487. if (this._filter === value) {
  58488. return;
  58489. }
  58490. this._filter = value;
  58491. this._disposeBlurPostProcesses();
  58492. this._applyFilterValues();
  58493. this._light._markMeshesAsLightDirty();
  58494. },
  58495. enumerable: true,
  58496. configurable: true
  58497. });
  58498. Object.defineProperty(ShadowGenerator.prototype, "usePoissonSampling", {
  58499. /**
  58500. * Gets if the current filter is set to Poisson Sampling aka PCF.
  58501. */
  58502. get: function () {
  58503. return this.filter === ShadowGenerator.FILTER_POISSONSAMPLING;
  58504. },
  58505. /**
  58506. * Sets the current filter to Poisson Sampling aka PCF.
  58507. */
  58508. set: function (value) {
  58509. if (!value && this.filter !== ShadowGenerator.FILTER_POISSONSAMPLING) {
  58510. return;
  58511. }
  58512. this.filter = (value ? ShadowGenerator.FILTER_POISSONSAMPLING : ShadowGenerator.FILTER_NONE);
  58513. },
  58514. enumerable: true,
  58515. configurable: true
  58516. });
  58517. Object.defineProperty(ShadowGenerator.prototype, "useVarianceShadowMap", {
  58518. /**
  58519. * Gets if the current filter is set to VSM.
  58520. * DEPRECATED. Should use useExponentialShadowMap instead.
  58521. */
  58522. get: function () {
  58523. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useExponentialShadowMap instead.");
  58524. return this.useExponentialShadowMap;
  58525. },
  58526. /**
  58527. * Sets the current filter is to VSM.
  58528. * DEPRECATED. Should use useExponentialShadowMap instead.
  58529. */
  58530. set: function (value) {
  58531. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useExponentialShadowMap instead.");
  58532. this.useExponentialShadowMap = value;
  58533. },
  58534. enumerable: true,
  58535. configurable: true
  58536. });
  58537. Object.defineProperty(ShadowGenerator.prototype, "useBlurVarianceShadowMap", {
  58538. /**
  58539. * Gets if the current filter is set to blurred VSM.
  58540. * DEPRECATED. Should use useBlurExponentialShadowMap instead.
  58541. */
  58542. get: function () {
  58543. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useBlurExponentialShadowMap instead.");
  58544. return this.useBlurExponentialShadowMap;
  58545. },
  58546. /**
  58547. * Sets the current filter is to blurred VSM.
  58548. * DEPRECATED. Should use useBlurExponentialShadowMap instead.
  58549. */
  58550. set: function (value) {
  58551. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useBlurExponentialShadowMap instead.");
  58552. this.useBlurExponentialShadowMap = value;
  58553. },
  58554. enumerable: true,
  58555. configurable: true
  58556. });
  58557. Object.defineProperty(ShadowGenerator.prototype, "useExponentialShadowMap", {
  58558. /**
  58559. * Gets if the current filter is set to ESM.
  58560. */
  58561. get: function () {
  58562. return this.filter === ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP;
  58563. },
  58564. /**
  58565. * Sets the current filter is to ESM.
  58566. */
  58567. set: function (value) {
  58568. if (!value && this.filter !== ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP) {
  58569. return;
  58570. }
  58571. this.filter = (value ? ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  58572. },
  58573. enumerable: true,
  58574. configurable: true
  58575. });
  58576. Object.defineProperty(ShadowGenerator.prototype, "useBlurExponentialShadowMap", {
  58577. /**
  58578. * Gets if the current filter is set to filtered ESM.
  58579. */
  58580. get: function () {
  58581. return this.filter === ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP;
  58582. },
  58583. /**
  58584. * Gets if the current filter is set to filtered ESM.
  58585. */
  58586. set: function (value) {
  58587. if (!value && this.filter !== ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP) {
  58588. return;
  58589. }
  58590. this.filter = (value ? ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  58591. },
  58592. enumerable: true,
  58593. configurable: true
  58594. });
  58595. Object.defineProperty(ShadowGenerator.prototype, "useCloseExponentialShadowMap", {
  58596. /**
  58597. * Gets if the current filter is set to "close ESM" (using the inverse of the
  58598. * exponential to prevent steep falloff artifacts).
  58599. */
  58600. get: function () {
  58601. return this.filter === ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP;
  58602. },
  58603. /**
  58604. * Sets the current filter to "close ESM" (using the inverse of the
  58605. * exponential to prevent steep falloff artifacts).
  58606. */
  58607. set: function (value) {
  58608. if (!value && this.filter !== ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP) {
  58609. return;
  58610. }
  58611. this.filter = (value ? ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  58612. },
  58613. enumerable: true,
  58614. configurable: true
  58615. });
  58616. Object.defineProperty(ShadowGenerator.prototype, "useBlurCloseExponentialShadowMap", {
  58617. /**
  58618. * Gets if the current filter is set to filtered "close ESM" (using the inverse of the
  58619. * exponential to prevent steep falloff artifacts).
  58620. */
  58621. get: function () {
  58622. return this.filter === ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP;
  58623. },
  58624. /**
  58625. * Sets the current filter to fileterd "close ESM" (using the inverse of the
  58626. * exponential to prevent steep falloff artifacts).
  58627. */
  58628. set: function (value) {
  58629. if (!value && this.filter !== ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP) {
  58630. return;
  58631. }
  58632. this.filter = (value ? ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  58633. },
  58634. enumerable: true,
  58635. configurable: true
  58636. });
  58637. /**
  58638. * Returns the darkness value (float). This can only decrease the actual darkness of a shadow.
  58639. * 0 means strongest and 1 would means no shadow.
  58640. * @returns the darkness.
  58641. */
  58642. ShadowGenerator.prototype.getDarkness = function () {
  58643. return this._darkness;
  58644. };
  58645. /**
  58646. * Sets the darkness value (float). This can only decrease the actual darkness of a shadow.
  58647. * @param darkness The darkness value 0 means strongest and 1 would means no shadow.
  58648. * @returns the shadow generator allowing fluent coding.
  58649. */
  58650. ShadowGenerator.prototype.setDarkness = function (darkness) {
  58651. if (darkness >= 1.0)
  58652. this._darkness = 1.0;
  58653. else if (darkness <= 0.0)
  58654. this._darkness = 0.0;
  58655. else
  58656. this._darkness = darkness;
  58657. return this;
  58658. };
  58659. /**
  58660. * Sets the ability to have transparent shadow (boolean).
  58661. * @param transparent True if transparent else False
  58662. * @returns the shadow generator allowing fluent coding
  58663. */
  58664. ShadowGenerator.prototype.setTransparencyShadow = function (transparent) {
  58665. this._transparencyShadow = transparent;
  58666. return this;
  58667. };
  58668. /**
  58669. * Gets the main RTT containing the shadow map (usually storing depth from the light point of view).
  58670. * @returns The render target texture if present otherwise, null
  58671. */
  58672. ShadowGenerator.prototype.getShadowMap = function () {
  58673. return this._shadowMap;
  58674. };
  58675. /**
  58676. * Gets the RTT used during rendering (can be a blurred version of the shadow map or the shadow map itself).
  58677. * @returns The render target texture if the shadow map is present otherwise, null
  58678. */
  58679. ShadowGenerator.prototype.getShadowMapForRendering = function () {
  58680. if (this._shadowMap2) {
  58681. return this._shadowMap2;
  58682. }
  58683. return this._shadowMap;
  58684. };
  58685. /**
  58686. * Helper function to add a mesh and its descendants to the list of shadow casters.
  58687. * @param mesh Mesh to add
  58688. * @param includeDescendants boolean indicating if the descendants should be added. Default to true
  58689. * @returns the Shadow Generator itself
  58690. */
  58691. ShadowGenerator.prototype.addShadowCaster = function (mesh, includeDescendants) {
  58692. if (includeDescendants === void 0) { includeDescendants = true; }
  58693. if (!this._shadowMap) {
  58694. return this;
  58695. }
  58696. if (!this._shadowMap.renderList) {
  58697. this._shadowMap.renderList = [];
  58698. }
  58699. this._shadowMap.renderList.push(mesh);
  58700. if (includeDescendants) {
  58701. (_a = this._shadowMap.renderList).push.apply(_a, mesh.getChildMeshes());
  58702. }
  58703. return this;
  58704. var _a;
  58705. };
  58706. /**
  58707. * Helper function to remove a mesh and its descendants from the list of shadow casters
  58708. * @param mesh Mesh to remove
  58709. * @param includeDescendants boolean indicating if the descendants should be removed. Default to true
  58710. * @returns the Shadow Generator itself
  58711. */
  58712. ShadowGenerator.prototype.removeShadowCaster = function (mesh, includeDescendants) {
  58713. if (includeDescendants === void 0) { includeDescendants = true; }
  58714. if (!this._shadowMap || !this._shadowMap.renderList) {
  58715. return this;
  58716. }
  58717. var index = this._shadowMap.renderList.indexOf(mesh);
  58718. if (index !== -1) {
  58719. this._shadowMap.renderList.splice(index, 1);
  58720. }
  58721. if (includeDescendants) {
  58722. for (var _i = 0, _a = mesh.getChildren(); _i < _a.length; _i++) {
  58723. var child = _a[_i];
  58724. this.removeShadowCaster(child);
  58725. }
  58726. }
  58727. return this;
  58728. };
  58729. /**
  58730. * Returns the associated light object.
  58731. * @returns the light generating the shadow
  58732. */
  58733. ShadowGenerator.prototype.getLight = function () {
  58734. return this._light;
  58735. };
  58736. ShadowGenerator.prototype._initializeGenerator = function () {
  58737. this._light._markMeshesAsLightDirty();
  58738. this._initializeShadowMap();
  58739. };
  58740. ShadowGenerator.prototype._initializeShadowMap = function () {
  58741. var _this = this;
  58742. // Render target
  58743. this._shadowMap = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap", this._mapSize, this._scene, false, true, this._textureType, this._light.needCube());
  58744. this._shadowMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  58745. this._shadowMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  58746. this._shadowMap.anisotropicFilteringLevel = 1;
  58747. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  58748. this._shadowMap.renderParticles = false;
  58749. this._shadowMap.ignoreCameraViewport = true;
  58750. // Record Face Index before render.
  58751. this._shadowMap.onBeforeRenderObservable.add(function (faceIndex) {
  58752. _this._currentFaceIndex = faceIndex;
  58753. });
  58754. // Custom render function.
  58755. this._shadowMap.customRenderFunction = this._renderForShadowMap.bind(this);
  58756. // Blur if required afer render.
  58757. this._shadowMap.onAfterUnbindObservable.add(function () {
  58758. if (!_this.useBlurExponentialShadowMap && !_this.useBlurCloseExponentialShadowMap) {
  58759. return;
  58760. }
  58761. var shadowMap = _this.getShadowMapForRendering();
  58762. if (shadowMap) {
  58763. _this._scene.postProcessManager.directRender(_this._blurPostProcesses, shadowMap.getInternalTexture(), true);
  58764. }
  58765. });
  58766. // Clear according to the chosen filter.
  58767. this._shadowMap.onClearObservable.add(function (engine) {
  58768. if (_this.useExponentialShadowMap || _this.useBlurExponentialShadowMap) {
  58769. engine.clear(new BABYLON.Color4(0, 0, 0, 0), true, true, true);
  58770. }
  58771. else {
  58772. engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true, true);
  58773. }
  58774. });
  58775. };
  58776. ShadowGenerator.prototype._initializeBlurRTTAndPostProcesses = function () {
  58777. var _this = this;
  58778. var engine = this._scene.getEngine();
  58779. var targetSize = this._mapSize / this.blurScale;
  58780. if (!this.useKernelBlur || this.blurScale !== 1.0) {
  58781. this._shadowMap2 = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap2", targetSize, this._scene, false, true, this._textureType);
  58782. this._shadowMap2.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  58783. this._shadowMap2.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  58784. this._shadowMap2.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  58785. }
  58786. if (this.useKernelBlur) {
  58787. 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);
  58788. this._kernelBlurXPostprocess.width = targetSize;
  58789. this._kernelBlurXPostprocess.height = targetSize;
  58790. this._kernelBlurXPostprocess.onApplyObservable.add(function (effect) {
  58791. effect.setTexture("textureSampler", _this._shadowMap);
  58792. });
  58793. 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);
  58794. this._kernelBlurXPostprocess.autoClear = false;
  58795. this._kernelBlurYPostprocess.autoClear = false;
  58796. if (this._textureType === BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  58797. this._kernelBlurXPostprocess.packedFloat = true;
  58798. this._kernelBlurYPostprocess.packedFloat = true;
  58799. }
  58800. this._blurPostProcesses = [this._kernelBlurXPostprocess, this._kernelBlurYPostprocess];
  58801. }
  58802. else {
  58803. 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);
  58804. this._boxBlurPostprocess.onApplyObservable.add(function (effect) {
  58805. effect.setFloat2("screenSize", targetSize, targetSize);
  58806. effect.setTexture("textureSampler", _this._shadowMap);
  58807. });
  58808. this._boxBlurPostprocess.autoClear = false;
  58809. this._blurPostProcesses = [this._boxBlurPostprocess];
  58810. }
  58811. };
  58812. ShadowGenerator.prototype._renderForShadowMap = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  58813. var index;
  58814. var engine = this._scene.getEngine();
  58815. if (depthOnlySubMeshes.length) {
  58816. engine.setColorWrite(false);
  58817. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  58818. this._renderSubMeshForShadowMap(depthOnlySubMeshes.data[index]);
  58819. }
  58820. engine.setColorWrite(true);
  58821. }
  58822. for (index = 0; index < opaqueSubMeshes.length; index++) {
  58823. this._renderSubMeshForShadowMap(opaqueSubMeshes.data[index]);
  58824. }
  58825. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  58826. this._renderSubMeshForShadowMap(alphaTestSubMeshes.data[index]);
  58827. }
  58828. if (this._transparencyShadow) {
  58829. for (index = 0; index < transparentSubMeshes.length; index++) {
  58830. this._renderSubMeshForShadowMap(transparentSubMeshes.data[index]);
  58831. }
  58832. }
  58833. };
  58834. ShadowGenerator.prototype._renderSubMeshForShadowMap = function (subMesh) {
  58835. var _this = this;
  58836. var mesh = subMesh.getRenderingMesh();
  58837. var scene = this._scene;
  58838. var engine = scene.getEngine();
  58839. var material = subMesh.getMaterial();
  58840. if (!material) {
  58841. return;
  58842. }
  58843. // Culling
  58844. engine.setState(material.backFaceCulling);
  58845. // Managing instances
  58846. var batch = mesh._getInstancesRenderList(subMesh._id);
  58847. if (batch.mustReturn) {
  58848. return;
  58849. }
  58850. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  58851. if (this.isReady(subMesh, hardwareInstancedRendering)) {
  58852. engine.enableEffect(this._effect);
  58853. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  58854. this._effect.setFloat2("biasAndScale", this.bias, this.depthScale);
  58855. this._effect.setMatrix("viewProjection", this.getTransformMatrix());
  58856. this._effect.setVector3("lightPosition", this.getLight().position);
  58857. if (scene.activeCamera) {
  58858. this._effect.setFloat2("depthValues", this.getLight().getDepthMinZ(scene.activeCamera), this.getLight().getDepthMinZ(scene.activeCamera) + this.getLight().getDepthMaxZ(scene.activeCamera));
  58859. }
  58860. // Alpha test
  58861. if (material && material.needAlphaTesting()) {
  58862. var alphaTexture = material.getAlphaTestTexture();
  58863. if (alphaTexture) {
  58864. this._effect.setTexture("diffuseSampler", alphaTexture);
  58865. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix() || this._defaultTextureMatrix);
  58866. }
  58867. }
  58868. // Bones
  58869. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  58870. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices((mesh)));
  58871. }
  58872. if (this.forceBackFacesOnly) {
  58873. engine.setState(true, 0, false, true);
  58874. }
  58875. // Draw
  58876. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  58877. if (this.forceBackFacesOnly) {
  58878. engine.setState(true, 0, false, false);
  58879. }
  58880. }
  58881. else {
  58882. // Need to reset refresh rate of the shadowMap
  58883. if (this._shadowMap) {
  58884. this._shadowMap.resetRefreshCounter();
  58885. }
  58886. }
  58887. };
  58888. ShadowGenerator.prototype._applyFilterValues = function () {
  58889. if (!this._shadowMap) {
  58890. return;
  58891. }
  58892. if (this.filter === ShadowGenerator.FILTER_NONE) {
  58893. this._shadowMap.updateSamplingMode(BABYLON.Texture.NEAREST_SAMPLINGMODE);
  58894. }
  58895. else {
  58896. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  58897. }
  58898. };
  58899. /**
  58900. * Forces all the attached effect to compile to enable rendering only once ready vs. lazyly compiling effects.
  58901. * @param onCompiled Callback triggered at the and of the effects compilation
  58902. * @param options Sets of optional options forcing the compilation with different modes
  58903. */
  58904. ShadowGenerator.prototype.forceCompilation = function (onCompiled, options) {
  58905. var _this = this;
  58906. var localOptions = __assign({ useInstances: false }, options);
  58907. var shadowMap = this.getShadowMap();
  58908. if (!shadowMap) {
  58909. if (onCompiled) {
  58910. onCompiled(this);
  58911. }
  58912. return;
  58913. }
  58914. var renderList = shadowMap.renderList;
  58915. if (!renderList) {
  58916. if (onCompiled) {
  58917. onCompiled(this);
  58918. }
  58919. return;
  58920. }
  58921. var subMeshes = new Array();
  58922. for (var _i = 0, renderList_1 = renderList; _i < renderList_1.length; _i++) {
  58923. var mesh = renderList_1[_i];
  58924. subMeshes.push.apply(subMeshes, mesh.subMeshes);
  58925. }
  58926. if (subMeshes.length === 0) {
  58927. if (onCompiled) {
  58928. onCompiled(this);
  58929. }
  58930. return;
  58931. }
  58932. var currentIndex = 0;
  58933. var checkReady = function () {
  58934. if (!_this._scene || !_this._scene.getEngine()) {
  58935. return;
  58936. }
  58937. while (_this.isReady(subMeshes[currentIndex], localOptions.useInstances)) {
  58938. currentIndex++;
  58939. if (currentIndex >= subMeshes.length) {
  58940. if (onCompiled) {
  58941. onCompiled(_this);
  58942. }
  58943. return;
  58944. }
  58945. }
  58946. setTimeout(checkReady, 16);
  58947. };
  58948. checkReady();
  58949. };
  58950. /**
  58951. * Forces all the attached effect to compile to enable rendering only once ready vs. lazyly compiling effects.
  58952. * @param options Sets of optional options forcing the compilation with different modes
  58953. * @returns A promise that resolves when the compilation completes
  58954. */
  58955. ShadowGenerator.prototype.forceCompilationAsync = function (options) {
  58956. var _this = this;
  58957. return new Promise(function (resolve) {
  58958. _this.forceCompilation(function () {
  58959. resolve();
  58960. }, options);
  58961. });
  58962. };
  58963. /**
  58964. * Determine wheter the shadow generator is ready or not (mainly all effects and related post processes needs to be ready).
  58965. * @param subMesh The submesh we want to render in the shadow map
  58966. * @param useInstances Defines wether will draw in the map using instances
  58967. * @returns true if ready otherwise, false
  58968. */
  58969. ShadowGenerator.prototype.isReady = function (subMesh, useInstances) {
  58970. var defines = [];
  58971. if (this._textureType !== BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  58972. defines.push("#define FLOAT");
  58973. }
  58974. if (this.useExponentialShadowMap || this.useBlurExponentialShadowMap) {
  58975. defines.push("#define ESM");
  58976. }
  58977. var attribs = [BABYLON.VertexBuffer.PositionKind];
  58978. var mesh = subMesh.getMesh();
  58979. var material = subMesh.getMaterial();
  58980. // Alpha test
  58981. if (material && material.needAlphaTesting()) {
  58982. var alphaTexture = material.getAlphaTestTexture();
  58983. if (alphaTexture) {
  58984. defines.push("#define ALPHATEST");
  58985. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  58986. attribs.push(BABYLON.VertexBuffer.UVKind);
  58987. defines.push("#define UV1");
  58988. }
  58989. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  58990. if (alphaTexture.coordinatesIndex === 1) {
  58991. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  58992. defines.push("#define UV2");
  58993. }
  58994. }
  58995. }
  58996. }
  58997. // Bones
  58998. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  58999. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  59000. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  59001. if (mesh.numBoneInfluencers > 4) {
  59002. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  59003. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  59004. }
  59005. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  59006. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  59007. }
  59008. else {
  59009. defines.push("#define NUM_BONE_INFLUENCERS 0");
  59010. }
  59011. // Instances
  59012. if (useInstances) {
  59013. defines.push("#define INSTANCES");
  59014. attribs.push("world0");
  59015. attribs.push("world1");
  59016. attribs.push("world2");
  59017. attribs.push("world3");
  59018. }
  59019. // Get correct effect
  59020. var join = defines.join("\n");
  59021. if (this._cachedDefines !== join) {
  59022. this._cachedDefines = join;
  59023. this._effect = this._scene.getEngine().createEffect("shadowMap", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "lightPosition", "depthValues", "biasAndScale"], ["diffuseSampler"], join);
  59024. }
  59025. if (!this._effect.isReady()) {
  59026. return false;
  59027. }
  59028. if (this.useBlurExponentialShadowMap || this.useBlurCloseExponentialShadowMap) {
  59029. if (!this._blurPostProcesses || !this._blurPostProcesses.length) {
  59030. this._initializeBlurRTTAndPostProcesses();
  59031. }
  59032. }
  59033. if (this._kernelBlurXPostprocess && !this._kernelBlurXPostprocess.isReady()) {
  59034. return false;
  59035. }
  59036. if (this._kernelBlurYPostprocess && !this._kernelBlurYPostprocess.isReady()) {
  59037. return false;
  59038. }
  59039. if (this._boxBlurPostprocess && !this._boxBlurPostprocess.isReady()) {
  59040. return false;
  59041. }
  59042. return true;
  59043. };
  59044. /**
  59045. * Prepare all the defines in a material relying on a shadow map at the specified light index.
  59046. * @param defines Defines of the material we want to update
  59047. * @param lightIndex Index of the light in the enabled light list of the material
  59048. */
  59049. ShadowGenerator.prototype.prepareDefines = function (defines, lightIndex) {
  59050. var scene = this._scene;
  59051. var light = this._light;
  59052. if (!scene.shadowsEnabled || !light.shadowEnabled) {
  59053. return;
  59054. }
  59055. defines["SHADOW" + lightIndex] = true;
  59056. if (this.usePoissonSampling) {
  59057. defines["SHADOWPCF" + lightIndex] = true;
  59058. }
  59059. else if (this.useExponentialShadowMap || this.useBlurExponentialShadowMap) {
  59060. defines["SHADOWESM" + lightIndex] = true;
  59061. }
  59062. else if (this.useCloseExponentialShadowMap || this.useBlurCloseExponentialShadowMap) {
  59063. defines["SHADOWCLOSEESM" + lightIndex] = true;
  59064. }
  59065. if (light.needCube()) {
  59066. defines["SHADOWCUBE" + lightIndex] = true;
  59067. }
  59068. };
  59069. /**
  59070. * Binds the shadow related information inside of an effect (information like near, far, darkness...
  59071. * defined in the generator but impacting the effect).
  59072. * @param lightIndex Index of the light in the enabled light list of the material owning the effect
  59073. * @param effect The effect we are binfing the information for
  59074. */
  59075. ShadowGenerator.prototype.bindShadowLight = function (lightIndex, effect) {
  59076. var light = this._light;
  59077. var scene = this._scene;
  59078. if (!scene.shadowsEnabled || !light.shadowEnabled) {
  59079. return;
  59080. }
  59081. var camera = scene.activeCamera;
  59082. if (!camera) {
  59083. return;
  59084. }
  59085. var shadowMap = this.getShadowMap();
  59086. if (!shadowMap) {
  59087. return;
  59088. }
  59089. if (!light.needCube()) {
  59090. effect.setMatrix("lightMatrix" + lightIndex, this.getTransformMatrix());
  59091. }
  59092. effect.setTexture("shadowSampler" + lightIndex, this.getShadowMapForRendering());
  59093. light._uniformBuffer.updateFloat4("shadowsInfo", this.getDarkness(), this.blurScale / shadowMap.getSize().width, this.depthScale, this.frustumEdgeFalloff, lightIndex);
  59094. light._uniformBuffer.updateFloat2("depthValues", this.getLight().getDepthMinZ(camera), this.getLight().getDepthMinZ(camera) + this.getLight().getDepthMaxZ(camera), lightIndex);
  59095. };
  59096. /**
  59097. * Gets the transformation matrix used to project the meshes into the map from the light point of view.
  59098. * (eq to shadow prjection matrix * light transform matrix)
  59099. * @returns The transform matrix used to create the shadow map
  59100. */
  59101. ShadowGenerator.prototype.getTransformMatrix = function () {
  59102. var scene = this._scene;
  59103. if (this._currentRenderID === scene.getRenderId() && this._currentFaceIndexCache === this._currentFaceIndex) {
  59104. return this._transformMatrix;
  59105. }
  59106. this._currentRenderID = scene.getRenderId();
  59107. this._currentFaceIndexCache = this._currentFaceIndex;
  59108. var lightPosition = this._light.position;
  59109. if (this._light.computeTransformedInformation()) {
  59110. lightPosition = this._light.transformedPosition;
  59111. }
  59112. BABYLON.Vector3.NormalizeToRef(this._light.getShadowDirection(this._currentFaceIndex), this._lightDirection);
  59113. if (Math.abs(BABYLON.Vector3.Dot(this._lightDirection, BABYLON.Vector3.Up())) === 1.0) {
  59114. this._lightDirection.z = 0.0000000000001; // Required to avoid perfectly perpendicular light
  59115. }
  59116. if (this._light.needProjectionMatrixCompute() || !this._cachedPosition || !this._cachedDirection || !lightPosition.equals(this._cachedPosition) || !this._lightDirection.equals(this._cachedDirection)) {
  59117. this._cachedPosition = lightPosition.clone();
  59118. this._cachedDirection = this._lightDirection.clone();
  59119. BABYLON.Matrix.LookAtLHToRef(lightPosition, lightPosition.add(this._lightDirection), BABYLON.Vector3.Up(), this._viewMatrix);
  59120. var shadowMap = this.getShadowMap();
  59121. if (shadowMap) {
  59122. var renderList = shadowMap.renderList;
  59123. if (renderList) {
  59124. this._light.setShadowProjectionMatrix(this._projectionMatrix, this._viewMatrix, renderList);
  59125. }
  59126. }
  59127. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  59128. }
  59129. return this._transformMatrix;
  59130. };
  59131. /**
  59132. * Recreates the shadow map dependencies like RTT and post processes. This can be used during the switch between
  59133. * Cube and 2D textures for instance.
  59134. */
  59135. ShadowGenerator.prototype.recreateShadowMap = function () {
  59136. var shadowMap = this._shadowMap;
  59137. if (!shadowMap) {
  59138. return;
  59139. }
  59140. // Track render list.
  59141. var renderList = shadowMap.renderList;
  59142. // Clean up existing data.
  59143. this._disposeRTTandPostProcesses();
  59144. // Reinitializes.
  59145. this._initializeGenerator();
  59146. // Reaffect the filter to ensure a correct fallback if necessary.
  59147. this.filter = this.filter;
  59148. // Reaffect the filter.
  59149. this._applyFilterValues();
  59150. // Reaffect Render List.
  59151. this._shadowMap.renderList = renderList;
  59152. };
  59153. ShadowGenerator.prototype._disposeBlurPostProcesses = function () {
  59154. if (this._shadowMap2) {
  59155. this._shadowMap2.dispose();
  59156. this._shadowMap2 = null;
  59157. }
  59158. if (this._boxBlurPostprocess) {
  59159. this._boxBlurPostprocess.dispose();
  59160. this._boxBlurPostprocess = null;
  59161. }
  59162. if (this._kernelBlurXPostprocess) {
  59163. this._kernelBlurXPostprocess.dispose();
  59164. this._kernelBlurXPostprocess = null;
  59165. }
  59166. if (this._kernelBlurYPostprocess) {
  59167. this._kernelBlurYPostprocess.dispose();
  59168. this._kernelBlurYPostprocess = null;
  59169. }
  59170. this._blurPostProcesses = [];
  59171. };
  59172. ShadowGenerator.prototype._disposeRTTandPostProcesses = function () {
  59173. if (this._shadowMap) {
  59174. this._shadowMap.dispose();
  59175. this._shadowMap = null;
  59176. }
  59177. this._disposeBlurPostProcesses();
  59178. };
  59179. /**
  59180. * Disposes the ShadowGenerator.
  59181. * Returns nothing.
  59182. */
  59183. ShadowGenerator.prototype.dispose = function () {
  59184. this._disposeRTTandPostProcesses();
  59185. if (this._light) {
  59186. this._light._shadowGenerator = null;
  59187. this._light._markMeshesAsLightDirty();
  59188. }
  59189. };
  59190. /**
  59191. * Serializes the shadow generator setup to a json object.
  59192. * @returns The serialized JSON object
  59193. */
  59194. ShadowGenerator.prototype.serialize = function () {
  59195. var serializationObject = {};
  59196. var shadowMap = this.getShadowMap();
  59197. if (!shadowMap) {
  59198. return serializationObject;
  59199. }
  59200. serializationObject.lightId = this._light.id;
  59201. serializationObject.mapSize = shadowMap.getRenderSize();
  59202. serializationObject.useExponentialShadowMap = this.useExponentialShadowMap;
  59203. serializationObject.useBlurExponentialShadowMap = this.useBlurExponentialShadowMap;
  59204. serializationObject.useCloseExponentialShadowMap = this.useBlurExponentialShadowMap;
  59205. serializationObject.useBlurCloseExponentialShadowMap = this.useBlurExponentialShadowMap;
  59206. serializationObject.usePoissonSampling = this.usePoissonSampling;
  59207. serializationObject.forceBackFacesOnly = this.forceBackFacesOnly;
  59208. serializationObject.depthScale = this.depthScale;
  59209. serializationObject.darkness = this.getDarkness();
  59210. serializationObject.blurBoxOffset = this.blurBoxOffset;
  59211. serializationObject.blurKernel = this.blurKernel;
  59212. serializationObject.blurScale = this.blurScale;
  59213. serializationObject.useKernelBlur = this.useKernelBlur;
  59214. serializationObject.transparencyShadow = this._transparencyShadow;
  59215. serializationObject.renderList = [];
  59216. if (shadowMap.renderList) {
  59217. for (var meshIndex = 0; meshIndex < shadowMap.renderList.length; meshIndex++) {
  59218. var mesh = shadowMap.renderList[meshIndex];
  59219. serializationObject.renderList.push(mesh.id);
  59220. }
  59221. }
  59222. return serializationObject;
  59223. };
  59224. /**
  59225. * Parses a serialized ShadowGenerator and returns a new ShadowGenerator.
  59226. * @param parsedShadowGenerator The JSON object to parse
  59227. * @param scene The scene to create the shadow map for
  59228. * @returns The parsed shadow generator
  59229. */
  59230. ShadowGenerator.Parse = function (parsedShadowGenerator, scene) {
  59231. //casting to point light, as light is missing the position attr and typescript complains.
  59232. var light = scene.getLightByID(parsedShadowGenerator.lightId);
  59233. var shadowGenerator = new ShadowGenerator(parsedShadowGenerator.mapSize, light);
  59234. var shadowMap = shadowGenerator.getShadowMap();
  59235. for (var meshIndex = 0; meshIndex < parsedShadowGenerator.renderList.length; meshIndex++) {
  59236. var meshes = scene.getMeshesByID(parsedShadowGenerator.renderList[meshIndex]);
  59237. meshes.forEach(function (mesh) {
  59238. if (!shadowMap) {
  59239. return;
  59240. }
  59241. if (!shadowMap.renderList) {
  59242. shadowMap.renderList = [];
  59243. }
  59244. shadowMap.renderList.push(mesh);
  59245. });
  59246. }
  59247. if (parsedShadowGenerator.usePoissonSampling) {
  59248. shadowGenerator.usePoissonSampling = true;
  59249. }
  59250. else if (parsedShadowGenerator.useExponentialShadowMap) {
  59251. shadowGenerator.useExponentialShadowMap = true;
  59252. }
  59253. else if (parsedShadowGenerator.useBlurExponentialShadowMap) {
  59254. shadowGenerator.useBlurExponentialShadowMap = true;
  59255. }
  59256. else if (parsedShadowGenerator.useCloseExponentialShadowMap) {
  59257. shadowGenerator.useCloseExponentialShadowMap = true;
  59258. }
  59259. else if (parsedShadowGenerator.useBlurCloseExponentialShadowMap) {
  59260. shadowGenerator.useBlurCloseExponentialShadowMap = true;
  59261. }
  59262. else if (parsedShadowGenerator.useVarianceShadowMap) {
  59263. shadowGenerator.useExponentialShadowMap = true;
  59264. }
  59265. else if (parsedShadowGenerator.useBlurVarianceShadowMap) {
  59266. shadowGenerator.useBlurExponentialShadowMap = true;
  59267. }
  59268. if (parsedShadowGenerator.depthScale) {
  59269. shadowGenerator.depthScale = parsedShadowGenerator.depthScale;
  59270. }
  59271. if (parsedShadowGenerator.blurScale) {
  59272. shadowGenerator.blurScale = parsedShadowGenerator.blurScale;
  59273. }
  59274. if (parsedShadowGenerator.blurBoxOffset) {
  59275. shadowGenerator.blurBoxOffset = parsedShadowGenerator.blurBoxOffset;
  59276. }
  59277. if (parsedShadowGenerator.useKernelBlur) {
  59278. shadowGenerator.useKernelBlur = parsedShadowGenerator.useKernelBlur;
  59279. }
  59280. if (parsedShadowGenerator.blurKernel) {
  59281. shadowGenerator.blurKernel = parsedShadowGenerator.blurKernel;
  59282. }
  59283. if (parsedShadowGenerator.bias !== undefined) {
  59284. shadowGenerator.bias = parsedShadowGenerator.bias;
  59285. }
  59286. if (parsedShadowGenerator.darkness) {
  59287. shadowGenerator.setDarkness(parsedShadowGenerator.darkness);
  59288. }
  59289. if (parsedShadowGenerator.transparencyShadow) {
  59290. shadowGenerator.setTransparencyShadow(true);
  59291. }
  59292. shadowGenerator.forceBackFacesOnly = parsedShadowGenerator.forceBackFacesOnly;
  59293. return shadowGenerator;
  59294. };
  59295. ShadowGenerator._FILTER_NONE = 0;
  59296. ShadowGenerator._FILTER_EXPONENTIALSHADOWMAP = 1;
  59297. ShadowGenerator._FILTER_POISSONSAMPLING = 2;
  59298. ShadowGenerator._FILTER_BLUREXPONENTIALSHADOWMAP = 3;
  59299. ShadowGenerator._FILTER_CLOSEEXPONENTIALSHADOWMAP = 4;
  59300. ShadowGenerator._FILTER_BLURCLOSEEXPONENTIALSHADOWMAP = 5;
  59301. return ShadowGenerator;
  59302. }());
  59303. BABYLON.ShadowGenerator = ShadowGenerator;
  59304. })(BABYLON || (BABYLON = {}));
  59305. //# sourceMappingURL=babylon.shadowGenerator.js.map
  59306. var BABYLON;
  59307. (function (BABYLON) {
  59308. var DefaultLoadingScreen = /** @class */ (function () {
  59309. function DefaultLoadingScreen(_renderingCanvas, _loadingText, _loadingDivBackgroundColor) {
  59310. if (_loadingText === void 0) { _loadingText = ""; }
  59311. if (_loadingDivBackgroundColor === void 0) { _loadingDivBackgroundColor = "black"; }
  59312. var _this = this;
  59313. this._renderingCanvas = _renderingCanvas;
  59314. this._loadingText = _loadingText;
  59315. this._loadingDivBackgroundColor = _loadingDivBackgroundColor;
  59316. // Resize
  59317. this._resizeLoadingUI = function () {
  59318. var canvasRect = _this._renderingCanvas.getBoundingClientRect();
  59319. var canvasPositioning = window.getComputedStyle(_this._renderingCanvas).position;
  59320. if (!_this._loadingDiv) {
  59321. return;
  59322. }
  59323. _this._loadingDiv.style.position = (canvasPositioning === "fixed") ? "fixed" : "absolute";
  59324. _this._loadingDiv.style.left = canvasRect.left + "px";
  59325. _this._loadingDiv.style.top = canvasRect.top + "px";
  59326. _this._loadingDiv.style.width = canvasRect.width + "px";
  59327. _this._loadingDiv.style.height = canvasRect.height + "px";
  59328. };
  59329. }
  59330. DefaultLoadingScreen.prototype.displayLoadingUI = function () {
  59331. if (this._loadingDiv) {
  59332. // Do not add a loading screen if there is already one
  59333. return;
  59334. }
  59335. this._loadingDiv = document.createElement("div");
  59336. this._loadingDiv.id = "babylonjsLoadingDiv";
  59337. this._loadingDiv.style.opacity = "0";
  59338. this._loadingDiv.style.transition = "opacity 1.5s ease";
  59339. this._loadingDiv.style.pointerEvents = "none";
  59340. // Loading text
  59341. this._loadingTextDiv = document.createElement("div");
  59342. this._loadingTextDiv.style.position = "absolute";
  59343. this._loadingTextDiv.style.left = "0";
  59344. this._loadingTextDiv.style.top = "50%";
  59345. this._loadingTextDiv.style.marginTop = "80px";
  59346. this._loadingTextDiv.style.width = "100%";
  59347. this._loadingTextDiv.style.height = "20px";
  59348. this._loadingTextDiv.style.fontFamily = "Arial";
  59349. this._loadingTextDiv.style.fontSize = "14px";
  59350. this._loadingTextDiv.style.color = "white";
  59351. this._loadingTextDiv.style.textAlign = "center";
  59352. this._loadingTextDiv.innerHTML = "Loading";
  59353. this._loadingDiv.appendChild(this._loadingTextDiv);
  59354. //set the predefined text
  59355. this._loadingTextDiv.innerHTML = this._loadingText;
  59356. // Generating keyframes
  59357. var style = document.createElement('style');
  59358. style.type = 'text/css';
  59359. 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 }";
  59360. style.innerHTML = keyFrames;
  59361. document.getElementsByTagName('head')[0].appendChild(style);
  59362. // Loading img
  59363. var imgBack = new Image();
  59364. 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";
  59365. imgBack.style.position = "absolute";
  59366. imgBack.style.left = "50%";
  59367. imgBack.style.top = "50%";
  59368. imgBack.style.marginLeft = "-60px";
  59369. imgBack.style.marginTop = "-60px";
  59370. imgBack.style.animation = "spin1 2s infinite ease-in-out";
  59371. imgBack.style.webkitAnimation = "spin1 2s infinite ease-in-out";
  59372. imgBack.style.transformOrigin = "50% 50%";
  59373. imgBack.style.webkitTransformOrigin = "50% 50%";
  59374. this._loadingDiv.appendChild(imgBack);
  59375. this._resizeLoadingUI();
  59376. window.addEventListener("resize", this._resizeLoadingUI);
  59377. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  59378. document.body.appendChild(this._loadingDiv);
  59379. this._loadingDiv.style.opacity = "1";
  59380. };
  59381. DefaultLoadingScreen.prototype.hideLoadingUI = function () {
  59382. var _this = this;
  59383. if (!this._loadingDiv) {
  59384. return;
  59385. }
  59386. var onTransitionEnd = function () {
  59387. if (!_this._loadingDiv) {
  59388. return;
  59389. }
  59390. document.body.removeChild(_this._loadingDiv);
  59391. window.removeEventListener("resize", _this._resizeLoadingUI);
  59392. _this._loadingDiv = null;
  59393. };
  59394. this._loadingDiv.style.opacity = "0";
  59395. this._loadingDiv.addEventListener("transitionend", onTransitionEnd);
  59396. };
  59397. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIText", {
  59398. set: function (text) {
  59399. this._loadingText = text;
  59400. if (this._loadingTextDiv) {
  59401. this._loadingTextDiv.innerHTML = this._loadingText;
  59402. }
  59403. },
  59404. enumerable: true,
  59405. configurable: true
  59406. });
  59407. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIBackgroundColor", {
  59408. get: function () {
  59409. return this._loadingDivBackgroundColor;
  59410. },
  59411. set: function (color) {
  59412. this._loadingDivBackgroundColor = color;
  59413. if (!this._loadingDiv) {
  59414. return;
  59415. }
  59416. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  59417. },
  59418. enumerable: true,
  59419. configurable: true
  59420. });
  59421. return DefaultLoadingScreen;
  59422. }());
  59423. BABYLON.DefaultLoadingScreen = DefaultLoadingScreen;
  59424. })(BABYLON || (BABYLON = {}));
  59425. //# sourceMappingURL=babylon.loadingScreen.js.map
  59426. var BABYLON;
  59427. (function (BABYLON) {
  59428. var SceneLoaderProgressEvent = /** @class */ (function () {
  59429. function SceneLoaderProgressEvent(lengthComputable, loaded, total) {
  59430. this.lengthComputable = lengthComputable;
  59431. this.loaded = loaded;
  59432. this.total = total;
  59433. }
  59434. SceneLoaderProgressEvent.FromProgressEvent = function (event) {
  59435. return new SceneLoaderProgressEvent(event.lengthComputable, event.loaded, event.total);
  59436. };
  59437. return SceneLoaderProgressEvent;
  59438. }());
  59439. BABYLON.SceneLoaderProgressEvent = SceneLoaderProgressEvent;
  59440. var SceneLoader = /** @class */ (function () {
  59441. function SceneLoader() {
  59442. }
  59443. Object.defineProperty(SceneLoader, "NO_LOGGING", {
  59444. get: function () {
  59445. return 0;
  59446. },
  59447. enumerable: true,
  59448. configurable: true
  59449. });
  59450. Object.defineProperty(SceneLoader, "MINIMAL_LOGGING", {
  59451. get: function () {
  59452. return 1;
  59453. },
  59454. enumerable: true,
  59455. configurable: true
  59456. });
  59457. Object.defineProperty(SceneLoader, "SUMMARY_LOGGING", {
  59458. get: function () {
  59459. return 2;
  59460. },
  59461. enumerable: true,
  59462. configurable: true
  59463. });
  59464. Object.defineProperty(SceneLoader, "DETAILED_LOGGING", {
  59465. get: function () {
  59466. return 3;
  59467. },
  59468. enumerable: true,
  59469. configurable: true
  59470. });
  59471. Object.defineProperty(SceneLoader, "ForceFullSceneLoadingForIncremental", {
  59472. get: function () {
  59473. return SceneLoader._ForceFullSceneLoadingForIncremental;
  59474. },
  59475. set: function (value) {
  59476. SceneLoader._ForceFullSceneLoadingForIncremental = value;
  59477. },
  59478. enumerable: true,
  59479. configurable: true
  59480. });
  59481. Object.defineProperty(SceneLoader, "ShowLoadingScreen", {
  59482. get: function () {
  59483. return SceneLoader._ShowLoadingScreen;
  59484. },
  59485. set: function (value) {
  59486. SceneLoader._ShowLoadingScreen = value;
  59487. },
  59488. enumerable: true,
  59489. configurable: true
  59490. });
  59491. Object.defineProperty(SceneLoader, "loggingLevel", {
  59492. get: function () {
  59493. return SceneLoader._loggingLevel;
  59494. },
  59495. set: function (value) {
  59496. SceneLoader._loggingLevel = value;
  59497. },
  59498. enumerable: true,
  59499. configurable: true
  59500. });
  59501. Object.defineProperty(SceneLoader, "CleanBoneMatrixWeights", {
  59502. get: function () {
  59503. return SceneLoader._CleanBoneMatrixWeights;
  59504. },
  59505. set: function (value) {
  59506. SceneLoader._CleanBoneMatrixWeights = value;
  59507. },
  59508. enumerable: true,
  59509. configurable: true
  59510. });
  59511. SceneLoader._getDefaultPlugin = function () {
  59512. return SceneLoader._registeredPlugins[".babylon"];
  59513. };
  59514. SceneLoader._getPluginForExtension = function (extension) {
  59515. var registeredPlugin = SceneLoader._registeredPlugins[extension];
  59516. if (registeredPlugin) {
  59517. return registeredPlugin;
  59518. }
  59519. BABYLON.Tools.Warn("Unable to find a plugin to load " + extension + " files. Trying to use .babylon default plugin.");
  59520. return SceneLoader._getDefaultPlugin();
  59521. };
  59522. SceneLoader._getPluginForDirectLoad = function (data) {
  59523. for (var extension in SceneLoader._registeredPlugins) {
  59524. var plugin = SceneLoader._registeredPlugins[extension].plugin;
  59525. if (plugin.canDirectLoad && plugin.canDirectLoad(data)) {
  59526. return SceneLoader._registeredPlugins[extension];
  59527. }
  59528. }
  59529. return SceneLoader._getDefaultPlugin();
  59530. };
  59531. SceneLoader._getPluginForFilename = function (sceneFilename) {
  59532. if (sceneFilename.name) {
  59533. sceneFilename = sceneFilename.name;
  59534. }
  59535. var queryStringPosition = sceneFilename.indexOf("?");
  59536. if (queryStringPosition !== -1) {
  59537. sceneFilename = sceneFilename.substring(0, queryStringPosition);
  59538. }
  59539. var dotPosition = sceneFilename.lastIndexOf(".");
  59540. var extension = sceneFilename.substring(dotPosition, sceneFilename.length).toLowerCase();
  59541. return SceneLoader._getPluginForExtension(extension);
  59542. };
  59543. // use babylon file loader directly if sceneFilename is prefixed with "data:"
  59544. SceneLoader._getDirectLoad = function (sceneFilename) {
  59545. if (sceneFilename.substr && sceneFilename.substr(0, 5) === "data:") {
  59546. return sceneFilename.substr(5);
  59547. }
  59548. return null;
  59549. };
  59550. SceneLoader._loadData = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, onDispose, pluginExtension) {
  59551. var directLoad = SceneLoader._getDirectLoad(sceneFilename);
  59552. var registeredPlugin = pluginExtension ? SceneLoader._getPluginForExtension(pluginExtension) : (directLoad ? SceneLoader._getPluginForDirectLoad(sceneFilename) : SceneLoader._getPluginForFilename(sceneFilename));
  59553. var plugin;
  59554. if (registeredPlugin.plugin.createPlugin) {
  59555. plugin = registeredPlugin.plugin.createPlugin();
  59556. }
  59557. else {
  59558. plugin = registeredPlugin.plugin;
  59559. }
  59560. var useArrayBuffer = registeredPlugin.isBinary;
  59561. var database;
  59562. SceneLoader.OnPluginActivatedObservable.notifyObservers(plugin);
  59563. var dataCallback = function (data, responseURL) {
  59564. if (scene.isDisposed) {
  59565. onError("Scene has been disposed");
  59566. return;
  59567. }
  59568. scene.database = database;
  59569. onSuccess(plugin, data, responseURL);
  59570. };
  59571. var request = null;
  59572. var pluginDisposed = false;
  59573. var onDisposeObservable = plugin.onDisposeObservable;
  59574. if (onDisposeObservable) {
  59575. onDisposeObservable.add(function () {
  59576. pluginDisposed = true;
  59577. if (request) {
  59578. request.abort();
  59579. request = null;
  59580. }
  59581. onDispose();
  59582. });
  59583. }
  59584. var manifestChecked = function () {
  59585. if (pluginDisposed) {
  59586. return;
  59587. }
  59588. var url = rootUrl + sceneFilename;
  59589. request = BABYLON.Tools.LoadFile(url, dataCallback, onProgress ? function (event) {
  59590. onProgress(SceneLoaderProgressEvent.FromProgressEvent(event));
  59591. } : undefined, database, useArrayBuffer, function (request, exception) {
  59592. onError("Failed to load scene." + (exception ? "" : " " + exception.message), exception);
  59593. });
  59594. };
  59595. if (directLoad) {
  59596. dataCallback(directLoad);
  59597. return plugin;
  59598. }
  59599. if (rootUrl.indexOf("file:") === -1) {
  59600. if (scene.getEngine().enableOfflineSupport) {
  59601. // Checking if a manifest file has been set for this scene and if offline mode has been requested
  59602. database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked);
  59603. }
  59604. else {
  59605. manifestChecked();
  59606. }
  59607. }
  59608. else {
  59609. var fileOrString = sceneFilename;
  59610. if (fileOrString.name) {
  59611. request = BABYLON.Tools.ReadFile(fileOrString, dataCallback, onProgress, useArrayBuffer);
  59612. }
  59613. else if (BABYLON.FilesInput.FilesToLoad[sceneFilename]) {
  59614. request = BABYLON.Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[sceneFilename], dataCallback, onProgress, useArrayBuffer);
  59615. }
  59616. else {
  59617. onError("Unable to find file named " + sceneFilename);
  59618. }
  59619. }
  59620. return plugin;
  59621. };
  59622. // Public functions
  59623. SceneLoader.GetPluginForExtension = function (extension) {
  59624. return SceneLoader._getPluginForExtension(extension).plugin;
  59625. };
  59626. SceneLoader.IsPluginForExtensionAvailable = function (extension) {
  59627. return !!SceneLoader._registeredPlugins[extension];
  59628. };
  59629. SceneLoader.RegisterPlugin = function (plugin) {
  59630. if (typeof plugin.extensions === "string") {
  59631. var extension = plugin.extensions;
  59632. SceneLoader._registeredPlugins[extension.toLowerCase()] = {
  59633. plugin: plugin,
  59634. isBinary: false
  59635. };
  59636. }
  59637. else {
  59638. var extensions = plugin.extensions;
  59639. Object.keys(extensions).forEach(function (extension) {
  59640. SceneLoader._registeredPlugins[extension.toLowerCase()] = {
  59641. plugin: plugin,
  59642. isBinary: extensions[extension].isBinary
  59643. };
  59644. });
  59645. }
  59646. };
  59647. /**
  59648. * Import meshes into a scene
  59649. * @param meshNames an array of mesh names, a single mesh name, or empty string for all meshes that filter what meshes are imported
  59650. * @param rootUrl a string that defines the root url for scene and resources
  59651. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  59652. * @param scene the instance of BABYLON.Scene to append to
  59653. * @param onSuccess a callback with a list of imported meshes, particleSystems, and skeletons when import succeeds
  59654. * @param onProgress a callback with a progress event for each file being loaded
  59655. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  59656. * @param pluginExtension the extension used to determine the plugin
  59657. * @returns The loaded plugin
  59658. */
  59659. SceneLoader.ImportMesh = function (meshNames, rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  59660. if (onSuccess === void 0) { onSuccess = null; }
  59661. if (onProgress === void 0) { onProgress = null; }
  59662. if (onError === void 0) { onError = null; }
  59663. if (pluginExtension === void 0) { pluginExtension = null; }
  59664. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  59665. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  59666. return null;
  59667. }
  59668. var loadingToken = {};
  59669. scene._addPendingData(loadingToken);
  59670. var disposeHandler = function () {
  59671. scene._removePendingData(loadingToken);
  59672. };
  59673. var errorHandler = function (message, exception) {
  59674. var errorMessage = "Unable to import meshes from " + rootUrl + sceneFilename + ": " + message;
  59675. if (onError) {
  59676. onError(scene, errorMessage, exception);
  59677. }
  59678. else {
  59679. BABYLON.Tools.Error(errorMessage);
  59680. // should the exception be thrown?
  59681. }
  59682. disposeHandler();
  59683. };
  59684. var progressHandler = onProgress ? function (event) {
  59685. try {
  59686. onProgress(event);
  59687. }
  59688. catch (e) {
  59689. errorHandler("Error in onProgress callback", e);
  59690. }
  59691. } : undefined;
  59692. var successHandler = function (meshes, particleSystems, skeletons) {
  59693. scene.importedMeshesFiles.push(rootUrl + sceneFilename);
  59694. if (onSuccess) {
  59695. try {
  59696. onSuccess(meshes, particleSystems, skeletons);
  59697. }
  59698. catch (e) {
  59699. errorHandler("Error in onSuccess callback", e);
  59700. }
  59701. }
  59702. scene._removePendingData(loadingToken);
  59703. };
  59704. return SceneLoader._loadData(rootUrl, sceneFilename, scene, function (plugin, data, responseURL) {
  59705. if (plugin.rewriteRootURL) {
  59706. rootUrl = plugin.rewriteRootURL(rootUrl, responseURL);
  59707. }
  59708. if (sceneFilename === "") {
  59709. if (sceneFilename === "") {
  59710. rootUrl = BABYLON.Tools.GetFolderPath(rootUrl, true);
  59711. }
  59712. }
  59713. if (plugin.importMesh) {
  59714. var syncedPlugin = plugin;
  59715. var meshes = new Array();
  59716. var particleSystems = new Array();
  59717. var skeletons = new Array();
  59718. if (!syncedPlugin.importMesh(meshNames, scene, data, rootUrl, meshes, particleSystems, skeletons, errorHandler)) {
  59719. return;
  59720. }
  59721. scene.loadingPluginName = plugin.name;
  59722. successHandler(meshes, particleSystems, skeletons);
  59723. }
  59724. else {
  59725. var asyncedPlugin = plugin;
  59726. asyncedPlugin.importMeshAsync(meshNames, scene, data, rootUrl, progressHandler).then(function (result) {
  59727. scene.loadingPluginName = plugin.name;
  59728. successHandler(result.meshes, result.particleSystems, result.skeletons);
  59729. }).catch(function (error) {
  59730. errorHandler(error.message, error);
  59731. });
  59732. }
  59733. }, progressHandler, errorHandler, disposeHandler, pluginExtension);
  59734. };
  59735. /**
  59736. * Import meshes into a scene
  59737. * @param meshNames an array of mesh names, a single mesh name, or empty string for all meshes that filter what meshes are imported
  59738. * @param rootUrl a string that defines the root url for scene and resources
  59739. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  59740. * @param scene the instance of BABYLON.Scene to append to
  59741. * @param onProgress a callback with a progress event for each file being loaded
  59742. * @param pluginExtension the extension used to determine the plugin
  59743. * @returns The loaded list of imported meshes, particleSystems, and skeletons
  59744. */
  59745. SceneLoader.ImportMeshAsync = function (meshNames, rootUrl, sceneFilename, scene, onProgress, pluginExtension) {
  59746. if (onProgress === void 0) { onProgress = null; }
  59747. if (pluginExtension === void 0) { pluginExtension = null; }
  59748. return new Promise(function (resolve, reject) {
  59749. SceneLoader.ImportMesh(meshNames, rootUrl, sceneFilename, scene, function (meshes, particleSystems, skeletons) {
  59750. resolve({
  59751. meshes: meshes,
  59752. particleSystems: particleSystems,
  59753. skeletons: skeletons
  59754. });
  59755. }, onProgress, function (scene, message, exception) {
  59756. reject(exception || new Error(message));
  59757. });
  59758. });
  59759. };
  59760. /**
  59761. * Load a scene
  59762. * @param rootUrl a string that defines the root url for scene and resources
  59763. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  59764. * @param engine is the instance of BABYLON.Engine to use to create the scene
  59765. * @param onSuccess a callback with the scene when import succeeds
  59766. * @param onProgress a callback with a progress event for each file being loaded
  59767. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  59768. * @param pluginExtension the extension used to determine the plugin
  59769. * @returns The loaded plugin
  59770. */
  59771. SceneLoader.Load = function (rootUrl, sceneFilename, engine, onSuccess, onProgress, onError, pluginExtension) {
  59772. if (onSuccess === void 0) { onSuccess = null; }
  59773. if (onProgress === void 0) { onProgress = null; }
  59774. if (onError === void 0) { onError = null; }
  59775. if (pluginExtension === void 0) { pluginExtension = null; }
  59776. return SceneLoader.Append(rootUrl, sceneFilename, new BABYLON.Scene(engine), onSuccess, onProgress, onError, pluginExtension);
  59777. };
  59778. /**
  59779. * Load a scene
  59780. * @param rootUrl a string that defines the root url for scene and resources
  59781. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  59782. * @param engine is the instance of BABYLON.Engine to use to create the scene
  59783. * @param onProgress a callback with a progress event for each file being loaded
  59784. * @param pluginExtension the extension used to determine the plugin
  59785. * @returns The loaded scene
  59786. */
  59787. SceneLoader.LoadAsync = function (rootUrl, sceneFilename, engine, onProgress, pluginExtension) {
  59788. if (onProgress === void 0) { onProgress = null; }
  59789. if (pluginExtension === void 0) { pluginExtension = null; }
  59790. return new Promise(function (resolve, reject) {
  59791. SceneLoader.Load(rootUrl, sceneFilename, engine, function (scene) {
  59792. resolve(scene);
  59793. }, onProgress, function (scene, message, exception) {
  59794. reject(exception || new Error(message));
  59795. }, pluginExtension);
  59796. });
  59797. };
  59798. /**
  59799. * Append a scene
  59800. * @param rootUrl a string that defines the root url for scene and resources
  59801. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  59802. * @param scene is the instance of BABYLON.Scene to append to
  59803. * @param onSuccess a callback with the scene when import succeeds
  59804. * @param onProgress a callback with a progress event for each file being loaded
  59805. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  59806. * @param pluginExtension the extension used to determine the plugin
  59807. * @returns The loaded plugin
  59808. */
  59809. SceneLoader.Append = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  59810. if (onSuccess === void 0) { onSuccess = null; }
  59811. if (onProgress === void 0) { onProgress = null; }
  59812. if (onError === void 0) { onError = null; }
  59813. if (pluginExtension === void 0) { pluginExtension = null; }
  59814. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  59815. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  59816. return null;
  59817. }
  59818. if (SceneLoader.ShowLoadingScreen) {
  59819. scene.getEngine().displayLoadingUI();
  59820. }
  59821. var loadingToken = {};
  59822. scene._addPendingData(loadingToken);
  59823. var disposeHandler = function () {
  59824. scene._removePendingData(loadingToken);
  59825. scene.getEngine().hideLoadingUI();
  59826. };
  59827. var errorHandler = function (message, exception) {
  59828. var errorMessage = "Unable to load from " + rootUrl + sceneFilename + (message ? ": " + message : "");
  59829. if (onError) {
  59830. onError(scene, errorMessage, exception);
  59831. }
  59832. else {
  59833. BABYLON.Tools.Error(errorMessage);
  59834. // should the exception be thrown?
  59835. }
  59836. disposeHandler();
  59837. };
  59838. var progressHandler = onProgress ? function (event) {
  59839. try {
  59840. onProgress(event);
  59841. }
  59842. catch (e) {
  59843. errorHandler("Error in onProgress callback", e);
  59844. }
  59845. } : undefined;
  59846. var successHandler = function () {
  59847. if (onSuccess) {
  59848. try {
  59849. onSuccess(scene);
  59850. }
  59851. catch (e) {
  59852. errorHandler("Error in onSuccess callback", e);
  59853. }
  59854. }
  59855. scene._removePendingData(loadingToken);
  59856. };
  59857. return SceneLoader._loadData(rootUrl, sceneFilename, scene, function (plugin, data, responseURL) {
  59858. if (sceneFilename === "") {
  59859. rootUrl = BABYLON.Tools.GetFolderPath(rootUrl, true);
  59860. }
  59861. if (plugin.load) {
  59862. var syncedPlugin = plugin;
  59863. if (!syncedPlugin.load(scene, data, rootUrl, errorHandler)) {
  59864. return;
  59865. }
  59866. scene.loadingPluginName = plugin.name;
  59867. successHandler();
  59868. }
  59869. else {
  59870. var asyncedPlugin = plugin;
  59871. asyncedPlugin.loadAsync(scene, data, rootUrl, progressHandler).then(function () {
  59872. scene.loadingPluginName = plugin.name;
  59873. successHandler();
  59874. }).catch(function (error) {
  59875. errorHandler(error.message, error);
  59876. });
  59877. }
  59878. if (SceneLoader.ShowLoadingScreen) {
  59879. scene.executeWhenReady(function () {
  59880. scene.getEngine().hideLoadingUI();
  59881. });
  59882. }
  59883. }, progressHandler, errorHandler, disposeHandler, pluginExtension);
  59884. };
  59885. /**
  59886. * Append a scene
  59887. * @param rootUrl a string that defines the root url for scene and resources
  59888. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  59889. * @param scene is the instance of BABYLON.Scene to append to
  59890. * @param onProgress a callback with a progress event for each file being loaded
  59891. * @param pluginExtension the extension used to determine the plugin
  59892. * @returns The given scene
  59893. */
  59894. SceneLoader.AppendAsync = function (rootUrl, sceneFilename, scene, onProgress, pluginExtension) {
  59895. if (onProgress === void 0) { onProgress = null; }
  59896. if (pluginExtension === void 0) { pluginExtension = null; }
  59897. return new Promise(function (resolve, reject) {
  59898. SceneLoader.Append(rootUrl, sceneFilename, scene, function (scene) {
  59899. resolve(scene);
  59900. }, onProgress, function (scene, message, exception) {
  59901. reject(exception || new Error(message));
  59902. }, pluginExtension);
  59903. });
  59904. };
  59905. /**
  59906. * Load a scene into an asset container
  59907. * @param rootUrl a string that defines the root url for scene and resources
  59908. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  59909. * @param scene is the instance of BABYLON.Scene to append to
  59910. * @param onSuccess a callback with the scene when import succeeds
  59911. * @param onProgress a callback with a progress event for each file being loaded
  59912. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  59913. * @param pluginExtension the extension used to determine the plugin
  59914. * @returns The loaded plugin
  59915. */
  59916. SceneLoader.LoadAssetContainer = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  59917. if (onSuccess === void 0) { onSuccess = null; }
  59918. if (onProgress === void 0) { onProgress = null; }
  59919. if (onError === void 0) { onError = null; }
  59920. if (pluginExtension === void 0) { pluginExtension = null; }
  59921. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  59922. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  59923. return null;
  59924. }
  59925. var loadingToken = {};
  59926. scene._addPendingData(loadingToken);
  59927. var disposeHandler = function () {
  59928. scene._removePendingData(loadingToken);
  59929. };
  59930. var errorHandler = function (message, exception) {
  59931. var errorMessage = "Unable to load assets from " + rootUrl + sceneFilename + (message ? ": " + message : "");
  59932. if (onError) {
  59933. onError(scene, errorMessage, exception);
  59934. }
  59935. else {
  59936. BABYLON.Tools.Error(errorMessage);
  59937. // should the exception be thrown?
  59938. }
  59939. disposeHandler();
  59940. };
  59941. var progressHandler = onProgress ? function (event) {
  59942. try {
  59943. onProgress(event);
  59944. }
  59945. catch (e) {
  59946. errorHandler("Error in onProgress callback", e);
  59947. }
  59948. } : undefined;
  59949. var successHandler = function (assets) {
  59950. if (onSuccess) {
  59951. try {
  59952. onSuccess(assets);
  59953. }
  59954. catch (e) {
  59955. errorHandler("Error in onSuccess callback", e);
  59956. }
  59957. }
  59958. scene._removePendingData(loadingToken);
  59959. };
  59960. return SceneLoader._loadData(rootUrl, sceneFilename, scene, function (plugin, data, responseURL) {
  59961. if (plugin.loadAssetContainer) {
  59962. var syncedPlugin = plugin;
  59963. var assetContainer = syncedPlugin.loadAssetContainer(scene, data, rootUrl, errorHandler);
  59964. if (!assetContainer) {
  59965. return;
  59966. }
  59967. scene.loadingPluginName = plugin.name;
  59968. successHandler(assetContainer);
  59969. }
  59970. else if (plugin.loadAssetContainerAsync) {
  59971. var asyncedPlugin = plugin;
  59972. asyncedPlugin.loadAssetContainerAsync(scene, data, rootUrl, progressHandler).then(function (assetContainer) {
  59973. scene.loadingPluginName = plugin.name;
  59974. successHandler(assetContainer);
  59975. }).catch(function (error) {
  59976. errorHandler(error.message, error);
  59977. });
  59978. }
  59979. else {
  59980. errorHandler("LoadAssetContainer is not supported by this plugin. Plugin did not provide a loadAssetContainer or loadAssetContainerAsync method.");
  59981. }
  59982. if (SceneLoader.ShowLoadingScreen) {
  59983. scene.executeWhenReady(function () {
  59984. scene.getEngine().hideLoadingUI();
  59985. });
  59986. }
  59987. }, progressHandler, errorHandler, disposeHandler, pluginExtension);
  59988. };
  59989. /**
  59990. * Load a scene into an asset container
  59991. * @param rootUrl a string that defines the root url for scene and resources
  59992. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  59993. * @param scene is the instance of BABYLON.Scene to append to
  59994. * @param onProgress a callback with a progress event for each file being loaded
  59995. * @param pluginExtension the extension used to determine the plugin
  59996. * @returns The loaded asset container
  59997. */
  59998. SceneLoader.LoadAssetContainerAsync = function (rootUrl, sceneFilename, scene, onProgress, pluginExtension) {
  59999. if (onProgress === void 0) { onProgress = null; }
  60000. if (pluginExtension === void 0) { pluginExtension = null; }
  60001. return new Promise(function (resolve, reject) {
  60002. SceneLoader.LoadAssetContainer(rootUrl, sceneFilename, scene, function (assetContainer) {
  60003. resolve(assetContainer);
  60004. }, onProgress, function (scene, message, exception) {
  60005. reject(exception || new Error(message));
  60006. }, pluginExtension);
  60007. });
  60008. };
  60009. // Flags
  60010. SceneLoader._ForceFullSceneLoadingForIncremental = false;
  60011. SceneLoader._ShowLoadingScreen = true;
  60012. SceneLoader._CleanBoneMatrixWeights = false;
  60013. SceneLoader._loggingLevel = SceneLoader.NO_LOGGING;
  60014. // Members
  60015. SceneLoader.OnPluginActivatedObservable = new BABYLON.Observable();
  60016. SceneLoader._registeredPlugins = {};
  60017. return SceneLoader;
  60018. }());
  60019. BABYLON.SceneLoader = SceneLoader;
  60020. ;
  60021. })(BABYLON || (BABYLON = {}));
  60022. //# sourceMappingURL=babylon.sceneLoader.js.map
  60023. var BABYLON;
  60024. (function (BABYLON) {
  60025. var parseMaterialById = function (id, parsedData, scene, rootUrl) {
  60026. for (var index = 0, cache = parsedData.materials.length; index < cache; index++) {
  60027. var parsedMaterial = parsedData.materials[index];
  60028. if (parsedMaterial.id === id) {
  60029. return BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  60030. }
  60031. }
  60032. return null;
  60033. };
  60034. var isDescendantOf = function (mesh, names, hierarchyIds) {
  60035. for (var i in names) {
  60036. if (mesh.name === names[i]) {
  60037. hierarchyIds.push(mesh.id);
  60038. return true;
  60039. }
  60040. }
  60041. if (mesh.parentId && hierarchyIds.indexOf(mesh.parentId) !== -1) {
  60042. hierarchyIds.push(mesh.id);
  60043. return true;
  60044. }
  60045. return false;
  60046. };
  60047. var logOperation = function (operation, producer) {
  60048. return operation + " of " + (producer ? producer.file + " from " + producer.name + " version: " + producer.version + ", exporter version: " + producer.exporter_version : "unknown");
  60049. };
  60050. var loadAssetContainer = function (scene, data, rootUrl, onError, addToScene) {
  60051. if (addToScene === void 0) { addToScene = false; }
  60052. var container = new BABYLON.AssetContainer(scene);
  60053. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  60054. // when SceneLoader.debugLogging = true (default), or exception encountered.
  60055. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  60056. // and avoid problems with multiple concurrent .babylon loads.
  60057. var log = "importScene has failed JSON parse";
  60058. try {
  60059. var parsedData = JSON.parse(data);
  60060. log = "";
  60061. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  60062. var index;
  60063. var cache;
  60064. // Lights
  60065. if (parsedData.lights !== undefined && parsedData.lights !== null) {
  60066. for (index = 0, cache = parsedData.lights.length; index < cache; index++) {
  60067. var parsedLight = parsedData.lights[index];
  60068. var light = BABYLON.Light.Parse(parsedLight, scene);
  60069. if (light) {
  60070. container.lights.push(light);
  60071. log += (index === 0 ? "\n\tLights:" : "");
  60072. log += "\n\t\t" + light.toString(fullDetails);
  60073. }
  60074. }
  60075. }
  60076. // Animations
  60077. if (parsedData.animations !== undefined && parsedData.animations !== null) {
  60078. for (index = 0, cache = parsedData.animations.length; index < cache; index++) {
  60079. var parsedAnimation = parsedData.animations[index];
  60080. var animation = BABYLON.Animation.Parse(parsedAnimation);
  60081. scene.animations.push(animation);
  60082. container.animations.push(animation);
  60083. log += (index === 0 ? "\n\tAnimations:" : "");
  60084. log += "\n\t\t" + animation.toString(fullDetails);
  60085. }
  60086. }
  60087. // Materials
  60088. if (parsedData.materials !== undefined && parsedData.materials !== null) {
  60089. for (index = 0, cache = parsedData.materials.length; index < cache; index++) {
  60090. var parsedMaterial = parsedData.materials[index];
  60091. var mat = BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  60092. container.materials.push(mat);
  60093. log += (index === 0 ? "\n\tMaterials:" : "");
  60094. log += "\n\t\t" + mat.toString(fullDetails);
  60095. }
  60096. }
  60097. if (parsedData.multiMaterials !== undefined && parsedData.multiMaterials !== null) {
  60098. for (index = 0, cache = parsedData.multiMaterials.length; index < cache; index++) {
  60099. var parsedMultiMaterial = parsedData.multiMaterials[index];
  60100. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  60101. container.multiMaterials.push(mmat);
  60102. log += (index === 0 ? "\n\tMultiMaterials:" : "");
  60103. log += "\n\t\t" + mmat.toString(fullDetails);
  60104. }
  60105. }
  60106. // Morph targets
  60107. if (parsedData.morphTargetManagers !== undefined && parsedData.morphTargetManagers !== null) {
  60108. for (var _i = 0, _a = parsedData.morphTargetManagers; _i < _a.length; _i++) {
  60109. var managerData = _a[_i];
  60110. container.morphTargetManagers.push(BABYLON.MorphTargetManager.Parse(managerData, scene));
  60111. }
  60112. }
  60113. // Skeletons
  60114. if (parsedData.skeletons !== undefined && parsedData.skeletons !== null) {
  60115. for (index = 0, cache = parsedData.skeletons.length; index < cache; index++) {
  60116. var parsedSkeleton = parsedData.skeletons[index];
  60117. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  60118. container.skeletons.push(skeleton);
  60119. log += (index === 0 ? "\n\tSkeletons:" : "");
  60120. log += "\n\t\t" + skeleton.toString(fullDetails);
  60121. }
  60122. }
  60123. // Geometries
  60124. var geometries = parsedData.geometries;
  60125. if (geometries !== undefined && geometries !== null) {
  60126. var addedGeometry = new Array();
  60127. // Boxes
  60128. var boxes = geometries.boxes;
  60129. if (boxes !== undefined && boxes !== null) {
  60130. for (index = 0, cache = boxes.length; index < cache; index++) {
  60131. var parsedBox = boxes[index];
  60132. addedGeometry.push(BABYLON.BoxGeometry.Parse(parsedBox, scene));
  60133. }
  60134. }
  60135. // Spheres
  60136. var spheres = geometries.spheres;
  60137. if (spheres !== undefined && spheres !== null) {
  60138. for (index = 0, cache = spheres.length; index < cache; index++) {
  60139. var parsedSphere = spheres[index];
  60140. addedGeometry.push(BABYLON.SphereGeometry.Parse(parsedSphere, scene));
  60141. }
  60142. }
  60143. // Cylinders
  60144. var cylinders = geometries.cylinders;
  60145. if (cylinders !== undefined && cylinders !== null) {
  60146. for (index = 0, cache = cylinders.length; index < cache; index++) {
  60147. var parsedCylinder = cylinders[index];
  60148. addedGeometry.push(BABYLON.CylinderGeometry.Parse(parsedCylinder, scene));
  60149. }
  60150. }
  60151. // Toruses
  60152. var toruses = geometries.toruses;
  60153. if (toruses !== undefined && toruses !== null) {
  60154. for (index = 0, cache = toruses.length; index < cache; index++) {
  60155. var parsedTorus = toruses[index];
  60156. addedGeometry.push(BABYLON.TorusGeometry.Parse(parsedTorus, scene));
  60157. }
  60158. }
  60159. // Grounds
  60160. var grounds = geometries.grounds;
  60161. if (grounds !== undefined && grounds !== null) {
  60162. for (index = 0, cache = grounds.length; index < cache; index++) {
  60163. var parsedGround = grounds[index];
  60164. addedGeometry.push(BABYLON.GroundGeometry.Parse(parsedGround, scene));
  60165. }
  60166. }
  60167. // Planes
  60168. var planes = geometries.planes;
  60169. if (planes !== undefined && planes !== null) {
  60170. for (index = 0, cache = planes.length; index < cache; index++) {
  60171. var parsedPlane = planes[index];
  60172. addedGeometry.push(BABYLON.PlaneGeometry.Parse(parsedPlane, scene));
  60173. }
  60174. }
  60175. // TorusKnots
  60176. var torusKnots = geometries.torusKnots;
  60177. if (torusKnots !== undefined && torusKnots !== null) {
  60178. for (index = 0, cache = torusKnots.length; index < cache; index++) {
  60179. var parsedTorusKnot = torusKnots[index];
  60180. addedGeometry.push(BABYLON.TorusKnotGeometry.Parse(parsedTorusKnot, scene));
  60181. }
  60182. }
  60183. // VertexData
  60184. var vertexData = geometries.vertexData;
  60185. if (vertexData !== undefined && vertexData !== null) {
  60186. for (index = 0, cache = vertexData.length; index < cache; index++) {
  60187. var parsedVertexData = vertexData[index];
  60188. addedGeometry.push(BABYLON.Geometry.Parse(parsedVertexData, scene, rootUrl));
  60189. }
  60190. }
  60191. addedGeometry.forEach(function (g) {
  60192. if (g) {
  60193. container.geometries.push(g);
  60194. }
  60195. });
  60196. }
  60197. // Transform nodes
  60198. if (parsedData.transformNodes !== undefined && parsedData.transformNodes !== null) {
  60199. for (index = 0, cache = parsedData.transformNodes.length; index < cache; index++) {
  60200. var parsedTransformNode = parsedData.transformNodes[index];
  60201. var node = BABYLON.TransformNode.Parse(parsedTransformNode, scene, rootUrl);
  60202. container.transformNodes.push(node);
  60203. }
  60204. }
  60205. // Meshes
  60206. if (parsedData.meshes !== undefined && parsedData.meshes !== null) {
  60207. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  60208. var parsedMesh = parsedData.meshes[index];
  60209. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  60210. container.meshes.push(mesh);
  60211. log += (index === 0 ? "\n\tMeshes:" : "");
  60212. log += "\n\t\t" + mesh.toString(fullDetails);
  60213. }
  60214. }
  60215. // Cameras
  60216. if (parsedData.cameras !== undefined && parsedData.cameras !== null) {
  60217. for (index = 0, cache = parsedData.cameras.length; index < cache; index++) {
  60218. var parsedCamera = parsedData.cameras[index];
  60219. var camera = BABYLON.Camera.Parse(parsedCamera, scene);
  60220. container.cameras.push(camera);
  60221. log += (index === 0 ? "\n\tCameras:" : "");
  60222. log += "\n\t\t" + camera.toString(fullDetails);
  60223. }
  60224. }
  60225. // Browsing all the graph to connect the dots
  60226. for (index = 0, cache = scene.cameras.length; index < cache; index++) {
  60227. var camera = scene.cameras[index];
  60228. if (camera._waitingParentId) {
  60229. camera.parent = scene.getLastEntryByID(camera._waitingParentId);
  60230. camera._waitingParentId = null;
  60231. }
  60232. }
  60233. for (index = 0, cache = scene.lights.length; index < cache; index++) {
  60234. var light_1 = scene.lights[index];
  60235. if (light_1 && light_1._waitingParentId) {
  60236. light_1.parent = scene.getLastEntryByID(light_1._waitingParentId);
  60237. light_1._waitingParentId = null;
  60238. }
  60239. }
  60240. // Sounds
  60241. // TODO: add sound
  60242. var loadedSounds = [];
  60243. var loadedSound;
  60244. if (BABYLON.AudioEngine && parsedData.sounds !== undefined && parsedData.sounds !== null) {
  60245. for (index = 0, cache = parsedData.sounds.length; index < cache; index++) {
  60246. var parsedSound = parsedData.sounds[index];
  60247. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  60248. if (!parsedSound.url)
  60249. parsedSound.url = parsedSound.name;
  60250. if (!loadedSounds[parsedSound.url]) {
  60251. loadedSound = BABYLON.Sound.Parse(parsedSound, scene, rootUrl);
  60252. loadedSounds[parsedSound.url] = loadedSound;
  60253. container.sounds.push(loadedSound);
  60254. }
  60255. else {
  60256. container.sounds.push(BABYLON.Sound.Parse(parsedSound, scene, rootUrl, loadedSounds[parsedSound.url]));
  60257. }
  60258. }
  60259. else {
  60260. container.sounds.push(new BABYLON.Sound(parsedSound.name, null, scene));
  60261. }
  60262. }
  60263. }
  60264. loadedSounds = [];
  60265. // Connect parents & children and parse actions
  60266. for (index = 0, cache = scene.transformNodes.length; index < cache; index++) {
  60267. var transformNode = scene.transformNodes[index];
  60268. if (transformNode._waitingParentId) {
  60269. transformNode.parent = scene.getLastEntryByID(transformNode._waitingParentId);
  60270. transformNode._waitingParentId = null;
  60271. }
  60272. }
  60273. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  60274. var mesh = scene.meshes[index];
  60275. if (mesh._waitingParentId) {
  60276. mesh.parent = scene.getLastEntryByID(mesh._waitingParentId);
  60277. mesh._waitingParentId = null;
  60278. }
  60279. if (mesh._waitingActions) {
  60280. BABYLON.ActionManager.Parse(mesh._waitingActions, mesh, scene);
  60281. mesh._waitingActions = null;
  60282. }
  60283. }
  60284. // freeze world matrix application
  60285. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  60286. var currentMesh = scene.meshes[index];
  60287. if (currentMesh._waitingFreezeWorldMatrix) {
  60288. currentMesh.freezeWorldMatrix();
  60289. currentMesh._waitingFreezeWorldMatrix = null;
  60290. }
  60291. else {
  60292. currentMesh.computeWorldMatrix(true);
  60293. }
  60294. }
  60295. // Particles Systems
  60296. if (parsedData.particleSystems !== undefined && parsedData.particleSystems !== null) {
  60297. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  60298. var parsedParticleSystem = parsedData.particleSystems[index];
  60299. var ps = BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl);
  60300. container.particleSystems.push(ps);
  60301. }
  60302. }
  60303. // Lens flares
  60304. if (parsedData.lensFlareSystems !== undefined && parsedData.lensFlareSystems !== null) {
  60305. for (index = 0, cache = parsedData.lensFlareSystems.length; index < cache; index++) {
  60306. var parsedLensFlareSystem = parsedData.lensFlareSystems[index];
  60307. var lf = BABYLON.LensFlareSystem.Parse(parsedLensFlareSystem, scene, rootUrl);
  60308. container.lensFlareSystems.push(lf);
  60309. }
  60310. }
  60311. // Shadows
  60312. if (parsedData.shadowGenerators !== undefined && parsedData.shadowGenerators !== null) {
  60313. for (index = 0, cache = parsedData.shadowGenerators.length; index < cache; index++) {
  60314. var parsedShadowGenerator = parsedData.shadowGenerators[index];
  60315. var sg = BABYLON.ShadowGenerator.Parse(parsedShadowGenerator, scene);
  60316. container.shadowGenerators.push(sg);
  60317. }
  60318. }
  60319. // Lights exclusions / inclusions
  60320. for (index = 0, cache = scene.lights.length; index < cache; index++) {
  60321. var light_2 = scene.lights[index];
  60322. // Excluded check
  60323. if (light_2._excludedMeshesIds.length > 0) {
  60324. for (var excludedIndex = 0; excludedIndex < light_2._excludedMeshesIds.length; excludedIndex++) {
  60325. var excludedMesh = scene.getMeshByID(light_2._excludedMeshesIds[excludedIndex]);
  60326. if (excludedMesh) {
  60327. light_2.excludedMeshes.push(excludedMesh);
  60328. }
  60329. }
  60330. light_2._excludedMeshesIds = [];
  60331. }
  60332. // Included check
  60333. if (light_2._includedOnlyMeshesIds.length > 0) {
  60334. for (var includedOnlyIndex = 0; includedOnlyIndex < light_2._includedOnlyMeshesIds.length; includedOnlyIndex++) {
  60335. var includedOnlyMesh = scene.getMeshByID(light_2._includedOnlyMeshesIds[includedOnlyIndex]);
  60336. if (includedOnlyMesh) {
  60337. light_2.includedOnlyMeshes.push(includedOnlyMesh);
  60338. }
  60339. }
  60340. light_2._includedOnlyMeshesIds = [];
  60341. }
  60342. }
  60343. // Actions (scene)
  60344. if (parsedData.actions !== undefined && parsedData.actions !== null) {
  60345. BABYLON.ActionManager.Parse(parsedData.actions, null, scene);
  60346. }
  60347. if (!addToScene) {
  60348. container.removeAllFromScene();
  60349. }
  60350. }
  60351. catch (err) {
  60352. var msg = logOperation("loadAssts", parsedData ? parsedData.producer : "Unknown") + log;
  60353. if (onError) {
  60354. onError(msg, err);
  60355. }
  60356. else {
  60357. BABYLON.Tools.Log(msg);
  60358. throw err;
  60359. }
  60360. }
  60361. finally {
  60362. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  60363. BABYLON.Tools.Log(logOperation("loadAssts", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  60364. }
  60365. }
  60366. return container;
  60367. };
  60368. BABYLON.SceneLoader.RegisterPlugin({
  60369. name: "babylon.js",
  60370. extensions: ".babylon",
  60371. canDirectLoad: function (data) {
  60372. if (data.indexOf("babylon") !== -1) {
  60373. return true;
  60374. }
  60375. return false;
  60376. },
  60377. importMesh: function (meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons, onError) {
  60378. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  60379. // when SceneLoader.debugLogging = true (default), or exception encountered.
  60380. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  60381. // and avoid problems with multiple concurrent .babylon loads.
  60382. var log = "importMesh has failed JSON parse";
  60383. try {
  60384. var parsedData = JSON.parse(data);
  60385. log = "";
  60386. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  60387. if (!meshesNames) {
  60388. meshesNames = null;
  60389. }
  60390. else if (!Array.isArray(meshesNames)) {
  60391. meshesNames = [meshesNames];
  60392. }
  60393. var hierarchyIds = new Array();
  60394. if (parsedData.meshes !== undefined && parsedData.meshes !== null) {
  60395. var loadedSkeletonsIds = [];
  60396. var loadedMaterialsIds = [];
  60397. var index;
  60398. var cache;
  60399. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  60400. var parsedMesh = parsedData.meshes[index];
  60401. if (meshesNames === null || isDescendantOf(parsedMesh, meshesNames, hierarchyIds)) {
  60402. if (meshesNames !== null) {
  60403. // Remove found mesh name from list.
  60404. delete meshesNames[meshesNames.indexOf(parsedMesh.name)];
  60405. }
  60406. //Geometry?
  60407. if (parsedMesh.geometryId !== undefined && parsedMesh.geometryId !== null) {
  60408. //does the file contain geometries?
  60409. if (parsedData.geometries !== undefined && parsedData.geometries !== null) {
  60410. //find the correct geometry and add it to the scene
  60411. var found = false;
  60412. ["boxes", "spheres", "cylinders", "toruses", "grounds", "planes", "torusKnots", "vertexData"].forEach(function (geometryType) {
  60413. if (found === true || !parsedData.geometries[geometryType] || !(Array.isArray(parsedData.geometries[geometryType]))) {
  60414. return;
  60415. }
  60416. else {
  60417. parsedData.geometries[geometryType].forEach(function (parsedGeometryData) {
  60418. if (parsedGeometryData.id === parsedMesh.geometryId) {
  60419. switch (geometryType) {
  60420. case "boxes":
  60421. BABYLON.BoxGeometry.Parse(parsedGeometryData, scene);
  60422. break;
  60423. case "spheres":
  60424. BABYLON.SphereGeometry.Parse(parsedGeometryData, scene);
  60425. break;
  60426. case "cylinders":
  60427. BABYLON.CylinderGeometry.Parse(parsedGeometryData, scene);
  60428. break;
  60429. case "toruses":
  60430. BABYLON.TorusGeometry.Parse(parsedGeometryData, scene);
  60431. break;
  60432. case "grounds":
  60433. BABYLON.GroundGeometry.Parse(parsedGeometryData, scene);
  60434. break;
  60435. case "planes":
  60436. BABYLON.PlaneGeometry.Parse(parsedGeometryData, scene);
  60437. break;
  60438. case "torusKnots":
  60439. BABYLON.TorusKnotGeometry.Parse(parsedGeometryData, scene);
  60440. break;
  60441. case "vertexData":
  60442. BABYLON.Geometry.Parse(parsedGeometryData, scene, rootUrl);
  60443. break;
  60444. }
  60445. found = true;
  60446. }
  60447. });
  60448. }
  60449. });
  60450. if (found === false) {
  60451. BABYLON.Tools.Warn("Geometry not found for mesh " + parsedMesh.id);
  60452. }
  60453. }
  60454. }
  60455. // Material ?
  60456. if (parsedMesh.materialId) {
  60457. var materialFound = (loadedMaterialsIds.indexOf(parsedMesh.materialId) !== -1);
  60458. if (materialFound === false && parsedData.multiMaterials !== undefined && parsedData.multiMaterials !== null) {
  60459. for (var multimatIndex = 0, multimatCache = parsedData.multiMaterials.length; multimatIndex < multimatCache; multimatIndex++) {
  60460. var parsedMultiMaterial = parsedData.multiMaterials[multimatIndex];
  60461. if (parsedMultiMaterial.id === parsedMesh.materialId) {
  60462. for (var matIndex = 0, matCache = parsedMultiMaterial.materials.length; matIndex < matCache; matIndex++) {
  60463. var subMatId = parsedMultiMaterial.materials[matIndex];
  60464. loadedMaterialsIds.push(subMatId);
  60465. var mat = parseMaterialById(subMatId, parsedData, scene, rootUrl);
  60466. if (mat) {
  60467. log += "\n\tMaterial " + mat.toString(fullDetails);
  60468. }
  60469. }
  60470. loadedMaterialsIds.push(parsedMultiMaterial.id);
  60471. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  60472. if (mmat) {
  60473. materialFound = true;
  60474. log += "\n\tMulti-Material " + mmat.toString(fullDetails);
  60475. }
  60476. break;
  60477. }
  60478. }
  60479. }
  60480. if (materialFound === false) {
  60481. loadedMaterialsIds.push(parsedMesh.materialId);
  60482. var mat = parseMaterialById(parsedMesh.materialId, parsedData, scene, rootUrl);
  60483. if (!mat) {
  60484. BABYLON.Tools.Warn("Material not found for mesh " + parsedMesh.id);
  60485. }
  60486. else {
  60487. log += "\n\tMaterial " + mat.toString(fullDetails);
  60488. }
  60489. }
  60490. }
  60491. // Skeleton ?
  60492. if (parsedMesh.skeletonId > -1 && parsedData.skeletons !== undefined && parsedData.skeletons !== null) {
  60493. var skeletonAlreadyLoaded = (loadedSkeletonsIds.indexOf(parsedMesh.skeletonId) > -1);
  60494. if (skeletonAlreadyLoaded === false) {
  60495. for (var skeletonIndex = 0, skeletonCache = parsedData.skeletons.length; skeletonIndex < skeletonCache; skeletonIndex++) {
  60496. var parsedSkeleton = parsedData.skeletons[skeletonIndex];
  60497. if (parsedSkeleton.id === parsedMesh.skeletonId) {
  60498. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  60499. skeletons.push(skeleton);
  60500. loadedSkeletonsIds.push(parsedSkeleton.id);
  60501. log += "\n\tSkeleton " + skeleton.toString(fullDetails);
  60502. }
  60503. }
  60504. }
  60505. }
  60506. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  60507. meshes.push(mesh);
  60508. log += "\n\tMesh " + mesh.toString(fullDetails);
  60509. }
  60510. }
  60511. // Connecting parents
  60512. var currentMesh;
  60513. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  60514. currentMesh = scene.meshes[index];
  60515. if (currentMesh._waitingParentId) {
  60516. currentMesh.parent = scene.getLastEntryByID(currentMesh._waitingParentId);
  60517. currentMesh._waitingParentId = null;
  60518. }
  60519. }
  60520. // freeze and compute world matrix application
  60521. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  60522. currentMesh = scene.meshes[index];
  60523. if (currentMesh._waitingFreezeWorldMatrix) {
  60524. currentMesh.freezeWorldMatrix();
  60525. currentMesh._waitingFreezeWorldMatrix = null;
  60526. }
  60527. else {
  60528. currentMesh.computeWorldMatrix(true);
  60529. }
  60530. }
  60531. }
  60532. // Particles
  60533. if (parsedData.particleSystems !== undefined && parsedData.particleSystems !== null) {
  60534. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  60535. var parsedParticleSystem = parsedData.particleSystems[index];
  60536. if (hierarchyIds.indexOf(parsedParticleSystem.emitterId) !== -1) {
  60537. particleSystems.push(BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl));
  60538. }
  60539. }
  60540. }
  60541. return true;
  60542. }
  60543. catch (err) {
  60544. var msg = logOperation("importMesh", parsedData ? parsedData.producer : "Unknown") + log;
  60545. if (onError) {
  60546. onError(msg, err);
  60547. }
  60548. else {
  60549. BABYLON.Tools.Log(msg);
  60550. throw err;
  60551. }
  60552. }
  60553. finally {
  60554. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  60555. BABYLON.Tools.Log(logOperation("importMesh", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  60556. }
  60557. }
  60558. return false;
  60559. },
  60560. load: function (scene, data, rootUrl, onError) {
  60561. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  60562. // when SceneLoader.debugLogging = true (default), or exception encountered.
  60563. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  60564. // and avoid problems with multiple concurrent .babylon loads.
  60565. var log = "importScene has failed JSON parse";
  60566. try {
  60567. var parsedData = JSON.parse(data);
  60568. log = "";
  60569. // Scene
  60570. if (parsedData.useDelayedTextureLoading !== undefined && parsedData.useDelayedTextureLoading !== null) {
  60571. scene.useDelayedTextureLoading = parsedData.useDelayedTextureLoading && !BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental;
  60572. }
  60573. if (parsedData.autoClear !== undefined && parsedData.autoClear !== null) {
  60574. scene.autoClear = parsedData.autoClear;
  60575. }
  60576. if (parsedData.clearColor !== undefined && parsedData.clearColor !== null) {
  60577. scene.clearColor = BABYLON.Color4.FromArray(parsedData.clearColor);
  60578. }
  60579. if (parsedData.ambientColor !== undefined && parsedData.ambientColor !== null) {
  60580. scene.ambientColor = BABYLON.Color3.FromArray(parsedData.ambientColor);
  60581. }
  60582. if (parsedData.gravity !== undefined && parsedData.gravity !== null) {
  60583. scene.gravity = BABYLON.Vector3.FromArray(parsedData.gravity);
  60584. }
  60585. // Fog
  60586. if (parsedData.fogMode && parsedData.fogMode !== 0) {
  60587. scene.fogMode = parsedData.fogMode;
  60588. scene.fogColor = BABYLON.Color3.FromArray(parsedData.fogColor);
  60589. scene.fogStart = parsedData.fogStart;
  60590. scene.fogEnd = parsedData.fogEnd;
  60591. scene.fogDensity = parsedData.fogDensity;
  60592. log += "\tFog mode for scene: ";
  60593. switch (scene.fogMode) {
  60594. // getters not compiling, so using hardcoded
  60595. case 1:
  60596. log += "exp\n";
  60597. break;
  60598. case 2:
  60599. log += "exp2\n";
  60600. break;
  60601. case 3:
  60602. log += "linear\n";
  60603. break;
  60604. }
  60605. }
  60606. //Physics
  60607. if (parsedData.physicsEnabled) {
  60608. var physicsPlugin;
  60609. if (parsedData.physicsEngine === "cannon") {
  60610. physicsPlugin = new BABYLON.CannonJSPlugin();
  60611. }
  60612. else if (parsedData.physicsEngine === "oimo") {
  60613. physicsPlugin = new BABYLON.OimoJSPlugin();
  60614. }
  60615. log = "\tPhysics engine " + (parsedData.physicsEngine ? parsedData.physicsEngine : "oimo") + " enabled\n";
  60616. //else - default engine, which is currently oimo
  60617. var physicsGravity = parsedData.physicsGravity ? BABYLON.Vector3.FromArray(parsedData.physicsGravity) : null;
  60618. scene.enablePhysics(physicsGravity, physicsPlugin);
  60619. }
  60620. // Metadata
  60621. if (parsedData.metadata !== undefined && parsedData.metadata !== null) {
  60622. scene.metadata = parsedData.metadata;
  60623. }
  60624. //collisions, if defined. otherwise, default is true
  60625. if (parsedData.collisionsEnabled !== undefined && parsedData.collisionsEnabled !== null) {
  60626. scene.collisionsEnabled = parsedData.collisionsEnabled;
  60627. }
  60628. scene.workerCollisions = !!parsedData.workerCollisions;
  60629. var container = loadAssetContainer(scene, data, rootUrl, onError, true);
  60630. if (!container) {
  60631. return false;
  60632. }
  60633. if (parsedData.autoAnimate) {
  60634. scene.beginAnimation(scene, parsedData.autoAnimateFrom, parsedData.autoAnimateTo, parsedData.autoAnimateLoop, parsedData.autoAnimateSpeed || 1.0);
  60635. }
  60636. if (parsedData.activeCameraID !== undefined && parsedData.activeCameraID !== null) {
  60637. scene.setActiveCameraByID(parsedData.activeCameraID);
  60638. }
  60639. // Environment texture
  60640. if (parsedData.environmentTexture !== undefined && parsedData.environmentTexture !== null) {
  60641. scene.environmentTexture = BABYLON.CubeTexture.CreateFromPrefilteredData(rootUrl + parsedData.environmentTexture, scene);
  60642. if (parsedData.createDefaultSkybox === true) {
  60643. var skyboxScale = (scene.activeCamera !== undefined && scene.activeCamera !== null) ? (scene.activeCamera.maxZ - scene.activeCamera.minZ) / 2 : 1000;
  60644. var skyboxBlurLevel = parsedData.skyboxBlurLevel || 0;
  60645. scene.createDefaultSkybox(undefined, true, skyboxScale, skyboxBlurLevel);
  60646. }
  60647. }
  60648. // Finish
  60649. return true;
  60650. }
  60651. catch (err) {
  60652. var msg = logOperation("importScene", parsedData ? parsedData.producer : "Unknown") + log;
  60653. if (onError) {
  60654. onError(msg, err);
  60655. }
  60656. else {
  60657. BABYLON.Tools.Log(msg);
  60658. throw err;
  60659. }
  60660. }
  60661. finally {
  60662. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  60663. BABYLON.Tools.Log(logOperation("importScene", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  60664. }
  60665. }
  60666. return false;
  60667. },
  60668. loadAssetContainer: function (scene, data, rootUrl, onError) {
  60669. var container = loadAssetContainer(scene, data, rootUrl, onError);
  60670. return container;
  60671. }
  60672. });
  60673. })(BABYLON || (BABYLON = {}));
  60674. //# sourceMappingURL=babylon.babylonFileLoader.js.map
  60675. var BABYLON;
  60676. (function (BABYLON) {
  60677. var FilesInput = /** @class */ (function () {
  60678. function FilesInput(engine, scene, sceneLoadedCallback, progressCallback, additionalRenderLoopLogicCallback, textureLoadingCallback, startingProcessingFilesCallback, onReloadCallback, errorCallback) {
  60679. this.onProcessFileCallback = function () { return true; };
  60680. this._engine = engine;
  60681. this._currentScene = scene;
  60682. this._sceneLoadedCallback = sceneLoadedCallback;
  60683. this._progressCallback = progressCallback;
  60684. this._additionalRenderLoopLogicCallback = additionalRenderLoopLogicCallback;
  60685. this._textureLoadingCallback = textureLoadingCallback;
  60686. this._startingProcessingFilesCallback = startingProcessingFilesCallback;
  60687. this._onReloadCallback = onReloadCallback;
  60688. this._errorCallback = errorCallback;
  60689. }
  60690. FilesInput.prototype.monitorElementForDragNDrop = function (elementToMonitor) {
  60691. var _this = this;
  60692. if (elementToMonitor) {
  60693. this._elementToMonitor = elementToMonitor;
  60694. this._dragEnterHandler = function (e) { _this.drag(e); };
  60695. this._dragOverHandler = function (e) { _this.drag(e); };
  60696. this._dropHandler = function (e) { _this.drop(e); };
  60697. this._elementToMonitor.addEventListener("dragenter", this._dragEnterHandler, false);
  60698. this._elementToMonitor.addEventListener("dragover", this._dragOverHandler, false);
  60699. this._elementToMonitor.addEventListener("drop", this._dropHandler, false);
  60700. }
  60701. };
  60702. FilesInput.prototype.dispose = function () {
  60703. if (!this._elementToMonitor) {
  60704. return;
  60705. }
  60706. this._elementToMonitor.removeEventListener("dragenter", this._dragEnterHandler);
  60707. this._elementToMonitor.removeEventListener("dragover", this._dragOverHandler);
  60708. this._elementToMonitor.removeEventListener("drop", this._dropHandler);
  60709. };
  60710. FilesInput.prototype.renderFunction = function () {
  60711. if (this._additionalRenderLoopLogicCallback) {
  60712. this._additionalRenderLoopLogicCallback();
  60713. }
  60714. if (this._currentScene) {
  60715. if (this._textureLoadingCallback) {
  60716. var remaining = this._currentScene.getWaitingItemsCount();
  60717. if (remaining > 0) {
  60718. this._textureLoadingCallback(remaining);
  60719. }
  60720. }
  60721. this._currentScene.render();
  60722. }
  60723. };
  60724. FilesInput.prototype.drag = function (e) {
  60725. e.stopPropagation();
  60726. e.preventDefault();
  60727. };
  60728. FilesInput.prototype.drop = function (eventDrop) {
  60729. eventDrop.stopPropagation();
  60730. eventDrop.preventDefault();
  60731. this.loadFiles(eventDrop);
  60732. };
  60733. FilesInput.prototype._traverseFolder = function (folder, files, remaining, callback) {
  60734. var _this = this;
  60735. var reader = folder.createReader();
  60736. var relativePath = folder.fullPath.replace(/^\//, "").replace(/(.+?)\/?$/, "$1/");
  60737. reader.readEntries(function (entries) {
  60738. remaining.count += entries.length;
  60739. for (var _i = 0, entries_1 = entries; _i < entries_1.length; _i++) {
  60740. var entry = entries_1[_i];
  60741. if (entry.isFile) {
  60742. entry.file(function (file) {
  60743. file.correctName = relativePath + file.name;
  60744. files.push(file);
  60745. if (--remaining.count === 0) {
  60746. callback();
  60747. }
  60748. });
  60749. }
  60750. else if (entry.isDirectory) {
  60751. _this._traverseFolder(entry, files, remaining, callback);
  60752. }
  60753. }
  60754. if (--remaining.count) {
  60755. callback();
  60756. }
  60757. });
  60758. };
  60759. FilesInput.prototype._processFiles = function (files) {
  60760. for (var i = 0; i < files.length; i++) {
  60761. var name = files[i].correctName.toLowerCase();
  60762. var extension = name.split('.').pop();
  60763. if (!this.onProcessFileCallback(files[i], name, extension)) {
  60764. continue;
  60765. }
  60766. if ((extension === "babylon" || extension === "stl" || extension === "obj" || extension === "gltf" || extension === "glb")
  60767. && name.indexOf(".binary.babylon") === -1 && name.indexOf(".incremental.babylon") === -1) {
  60768. this._sceneFileToLoad = files[i];
  60769. }
  60770. else {
  60771. FilesInput.FilesToLoad[name] = files[i];
  60772. }
  60773. }
  60774. };
  60775. FilesInput.prototype.loadFiles = function (event) {
  60776. var _this = this;
  60777. if (this._startingProcessingFilesCallback)
  60778. this._startingProcessingFilesCallback();
  60779. // Handling data transfer via drag'n'drop
  60780. if (event && event.dataTransfer && event.dataTransfer.files) {
  60781. this._filesToLoad = event.dataTransfer.files;
  60782. }
  60783. // Handling files from input files
  60784. if (event && event.target && event.target.files) {
  60785. this._filesToLoad = event.target.files;
  60786. }
  60787. if (this._filesToLoad && this._filesToLoad.length > 0) {
  60788. var files_1 = new Array();
  60789. var folders = [];
  60790. var items = event.dataTransfer ? event.dataTransfer.items : null;
  60791. for (var i = 0; i < this._filesToLoad.length; i++) {
  60792. var fileToLoad = this._filesToLoad[i];
  60793. var name_1 = fileToLoad.name.toLowerCase();
  60794. var entry = void 0;
  60795. fileToLoad.correctName = name_1;
  60796. if (items) {
  60797. var item = items[i];
  60798. if (item.getAsEntry) {
  60799. entry = item.getAsEntry();
  60800. }
  60801. else if (item.webkitGetAsEntry) {
  60802. entry = item.webkitGetAsEntry();
  60803. }
  60804. }
  60805. if (!entry) {
  60806. files_1.push(fileToLoad);
  60807. }
  60808. else {
  60809. if (entry.isDirectory) {
  60810. folders.push(entry);
  60811. }
  60812. else {
  60813. files_1.push(fileToLoad);
  60814. }
  60815. }
  60816. }
  60817. if (folders.length === 0) {
  60818. this._processFiles(files_1);
  60819. this._processReload();
  60820. }
  60821. else {
  60822. var remaining = { count: folders.length };
  60823. for (var _i = 0, folders_1 = folders; _i < folders_1.length; _i++) {
  60824. var folder = folders_1[_i];
  60825. this._traverseFolder(folder, files_1, remaining, function () {
  60826. _this._processFiles(files_1);
  60827. if (remaining.count === 0) {
  60828. _this._processReload();
  60829. }
  60830. });
  60831. }
  60832. }
  60833. }
  60834. };
  60835. FilesInput.prototype._processReload = function () {
  60836. if (this._onReloadCallback) {
  60837. this._onReloadCallback(this._sceneFileToLoad);
  60838. }
  60839. else {
  60840. this.reload();
  60841. }
  60842. };
  60843. FilesInput.prototype.reload = function () {
  60844. var _this = this;
  60845. // If a scene file has been provided
  60846. if (this._sceneFileToLoad) {
  60847. if (this._currentScene) {
  60848. if (BABYLON.Tools.errorsCount > 0) {
  60849. BABYLON.Tools.ClearLogCache();
  60850. }
  60851. this._engine.stopRenderLoop();
  60852. this._currentScene.dispose();
  60853. }
  60854. BABYLON.SceneLoader.LoadAsync("file:", this._sceneFileToLoad, this._engine, function (progress) {
  60855. if (_this._progressCallback) {
  60856. _this._progressCallback(progress);
  60857. }
  60858. }).then(function (scene) {
  60859. _this._currentScene = scene;
  60860. if (_this._sceneLoadedCallback) {
  60861. _this._sceneLoadedCallback(_this._sceneFileToLoad, _this._currentScene);
  60862. }
  60863. // Wait for textures and shaders to be ready
  60864. _this._currentScene.executeWhenReady(function () {
  60865. _this._engine.runRenderLoop(function () {
  60866. _this.renderFunction();
  60867. });
  60868. });
  60869. }).catch(function (error) {
  60870. if (_this._errorCallback) {
  60871. _this._errorCallback(_this._sceneFileToLoad, _this._currentScene, error.message);
  60872. }
  60873. });
  60874. }
  60875. else {
  60876. BABYLON.Tools.Error("Please provide a valid .babylon file.");
  60877. }
  60878. };
  60879. FilesInput.FilesToLoad = {};
  60880. return FilesInput;
  60881. }());
  60882. BABYLON.FilesInput = FilesInput;
  60883. })(BABYLON || (BABYLON = {}));
  60884. //# sourceMappingURL=babylon.filesInput.js.map
  60885. var BABYLON;
  60886. (function (BABYLON) {
  60887. /**
  60888. * This class implement a typical dictionary using a string as key and the generic type T as value.
  60889. * The underlying implementation relies on an associative array to ensure the best performances.
  60890. * The value can be anything including 'null' but except 'undefined'
  60891. */
  60892. var StringDictionary = /** @class */ (function () {
  60893. function StringDictionary() {
  60894. this._count = 0;
  60895. this._data = {};
  60896. }
  60897. /**
  60898. * This will clear this dictionary and copy the content from the 'source' one.
  60899. * If the T value is a custom object, it won't be copied/cloned, the same object will be used
  60900. * @param source the dictionary to take the content from and copy to this dictionary
  60901. */
  60902. StringDictionary.prototype.copyFrom = function (source) {
  60903. var _this = this;
  60904. this.clear();
  60905. source.forEach(function (t, v) { return _this.add(t, v); });
  60906. };
  60907. /**
  60908. * Get a value based from its key
  60909. * @param key the given key to get the matching value from
  60910. * @return the value if found, otherwise undefined is returned
  60911. */
  60912. StringDictionary.prototype.get = function (key) {
  60913. var val = this._data[key];
  60914. if (val !== undefined) {
  60915. return val;
  60916. }
  60917. return undefined;
  60918. };
  60919. /**
  60920. * Get a value from its key or add it if it doesn't exist.
  60921. * This method will ensure you that a given key/data will be present in the dictionary.
  60922. * @param key the given key to get the matching value from
  60923. * @param factory the factory that will create the value if the key is not present in the dictionary.
  60924. * The factory will only be invoked if there's no data for the given key.
  60925. * @return the value corresponding to the key.
  60926. */
  60927. StringDictionary.prototype.getOrAddWithFactory = function (key, factory) {
  60928. var val = this.get(key);
  60929. if (val !== undefined) {
  60930. return val;
  60931. }
  60932. val = factory(key);
  60933. if (val) {
  60934. this.add(key, val);
  60935. }
  60936. return val;
  60937. };
  60938. /**
  60939. * Get a value from its key if present in the dictionary otherwise add it
  60940. * @param key the key to get the value from
  60941. * @param val if there's no such key/value pair in the dictionary add it with this value
  60942. * @return the value corresponding to the key
  60943. */
  60944. StringDictionary.prototype.getOrAdd = function (key, val) {
  60945. var curVal = this.get(key);
  60946. if (curVal !== undefined) {
  60947. return curVal;
  60948. }
  60949. this.add(key, val);
  60950. return val;
  60951. };
  60952. /**
  60953. * Check if there's a given key in the dictionary
  60954. * @param key the key to check for
  60955. * @return true if the key is present, false otherwise
  60956. */
  60957. StringDictionary.prototype.contains = function (key) {
  60958. return this._data[key] !== undefined;
  60959. };
  60960. /**
  60961. * Add a new key and its corresponding value
  60962. * @param key the key to add
  60963. * @param value the value corresponding to the key
  60964. * @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
  60965. */
  60966. StringDictionary.prototype.add = function (key, value) {
  60967. if (this._data[key] !== undefined) {
  60968. return false;
  60969. }
  60970. this._data[key] = value;
  60971. ++this._count;
  60972. return true;
  60973. };
  60974. StringDictionary.prototype.set = function (key, value) {
  60975. if (this._data[key] === undefined) {
  60976. return false;
  60977. }
  60978. this._data[key] = value;
  60979. return true;
  60980. };
  60981. /**
  60982. * Get the element of the given key and remove it from the dictionary
  60983. * @param key
  60984. */
  60985. StringDictionary.prototype.getAndRemove = function (key) {
  60986. var val = this.get(key);
  60987. if (val !== undefined) {
  60988. delete this._data[key];
  60989. --this._count;
  60990. return val;
  60991. }
  60992. return null;
  60993. };
  60994. /**
  60995. * Remove a key/value from the dictionary.
  60996. * @param key the key to remove
  60997. * @return true if the item was successfully deleted, false if no item with such key exist in the dictionary
  60998. */
  60999. StringDictionary.prototype.remove = function (key) {
  61000. if (this.contains(key)) {
  61001. delete this._data[key];
  61002. --this._count;
  61003. return true;
  61004. }
  61005. return false;
  61006. };
  61007. /**
  61008. * Clear the whole content of the dictionary
  61009. */
  61010. StringDictionary.prototype.clear = function () {
  61011. this._data = {};
  61012. this._count = 0;
  61013. };
  61014. Object.defineProperty(StringDictionary.prototype, "count", {
  61015. get: function () {
  61016. return this._count;
  61017. },
  61018. enumerable: true,
  61019. configurable: true
  61020. });
  61021. /**
  61022. * Execute a callback on each key/val of the dictionary.
  61023. * Note that you can remove any element in this dictionary in the callback implementation
  61024. * @param callback the callback to execute on a given key/value pair
  61025. */
  61026. StringDictionary.prototype.forEach = function (callback) {
  61027. for (var cur in this._data) {
  61028. var val = this._data[cur];
  61029. callback(cur, val);
  61030. }
  61031. };
  61032. /**
  61033. * Execute a callback on every occurrence of the dictionary until it returns a valid TRes object.
  61034. * If the callback returns null or undefined the method will iterate to the next key/value pair
  61035. * Note that you can remove any element in this dictionary in the callback implementation
  61036. * @param callback the callback to execute, if it return a valid T instanced object the enumeration will stop and the object will be returned
  61037. */
  61038. StringDictionary.prototype.first = function (callback) {
  61039. for (var cur in this._data) {
  61040. var val = this._data[cur];
  61041. var res = callback(cur, val);
  61042. if (res) {
  61043. return res;
  61044. }
  61045. }
  61046. return null;
  61047. };
  61048. return StringDictionary;
  61049. }());
  61050. BABYLON.StringDictionary = StringDictionary;
  61051. })(BABYLON || (BABYLON = {}));
  61052. //# sourceMappingURL=babylon.stringDictionary.js.map
  61053. var BABYLON;
  61054. (function (BABYLON) {
  61055. var Tags = /** @class */ (function () {
  61056. function Tags() {
  61057. }
  61058. Tags.EnableFor = function (obj) {
  61059. obj._tags = obj._tags || {};
  61060. obj.hasTags = function () {
  61061. return Tags.HasTags(obj);
  61062. };
  61063. obj.addTags = function (tagsString) {
  61064. return Tags.AddTagsTo(obj, tagsString);
  61065. };
  61066. obj.removeTags = function (tagsString) {
  61067. return Tags.RemoveTagsFrom(obj, tagsString);
  61068. };
  61069. obj.matchesTagsQuery = function (tagsQuery) {
  61070. return Tags.MatchesQuery(obj, tagsQuery);
  61071. };
  61072. };
  61073. Tags.DisableFor = function (obj) {
  61074. delete obj._tags;
  61075. delete obj.hasTags;
  61076. delete obj.addTags;
  61077. delete obj.removeTags;
  61078. delete obj.matchesTagsQuery;
  61079. };
  61080. Tags.HasTags = function (obj) {
  61081. if (!obj._tags) {
  61082. return false;
  61083. }
  61084. return !BABYLON.Tools.IsEmpty(obj._tags);
  61085. };
  61086. Tags.GetTags = function (obj, asString) {
  61087. if (asString === void 0) { asString = true; }
  61088. if (!obj._tags) {
  61089. return null;
  61090. }
  61091. if (asString) {
  61092. var tagsArray = [];
  61093. for (var tag in obj._tags) {
  61094. if (obj._tags.hasOwnProperty(tag) && obj._tags[tag] === true) {
  61095. tagsArray.push(tag);
  61096. }
  61097. }
  61098. return tagsArray.join(" ");
  61099. }
  61100. else {
  61101. return obj._tags;
  61102. }
  61103. };
  61104. // the tags 'true' and 'false' are reserved and cannot be used as tags
  61105. // a tag cannot start with '||', '&&', and '!'
  61106. // it cannot contain whitespaces
  61107. Tags.AddTagsTo = function (obj, tagsString) {
  61108. if (!tagsString) {
  61109. return;
  61110. }
  61111. if (typeof tagsString !== "string") {
  61112. return;
  61113. }
  61114. var tags = tagsString.split(" ");
  61115. tags.forEach(function (tag, index, array) {
  61116. Tags._AddTagTo(obj, tag);
  61117. });
  61118. };
  61119. Tags._AddTagTo = function (obj, tag) {
  61120. tag = tag.trim();
  61121. if (tag === "" || tag === "true" || tag === "false") {
  61122. return;
  61123. }
  61124. if (tag.match(/[\s]/) || tag.match(/^([!]|([|]|[&]){2})/)) {
  61125. return;
  61126. }
  61127. Tags.EnableFor(obj);
  61128. obj._tags[tag] = true;
  61129. };
  61130. Tags.RemoveTagsFrom = function (obj, tagsString) {
  61131. if (!Tags.HasTags(obj)) {
  61132. return;
  61133. }
  61134. var tags = tagsString.split(" ");
  61135. for (var t in tags) {
  61136. Tags._RemoveTagFrom(obj, tags[t]);
  61137. }
  61138. };
  61139. Tags._RemoveTagFrom = function (obj, tag) {
  61140. delete obj._tags[tag];
  61141. };
  61142. Tags.MatchesQuery = function (obj, tagsQuery) {
  61143. if (tagsQuery === undefined) {
  61144. return true;
  61145. }
  61146. if (tagsQuery === "") {
  61147. return Tags.HasTags(obj);
  61148. }
  61149. return BABYLON.AndOrNotEvaluator.Eval(tagsQuery, function (r) { return Tags.HasTags(obj) && obj._tags[r]; });
  61150. };
  61151. return Tags;
  61152. }());
  61153. BABYLON.Tags = Tags;
  61154. })(BABYLON || (BABYLON = {}));
  61155. //# sourceMappingURL=babylon.tags.js.map
  61156. var BABYLON;
  61157. (function (BABYLON) {
  61158. var AndOrNotEvaluator = /** @class */ (function () {
  61159. function AndOrNotEvaluator() {
  61160. }
  61161. AndOrNotEvaluator.Eval = function (query, evaluateCallback) {
  61162. if (!query.match(/\([^\(\)]*\)/g)) {
  61163. query = AndOrNotEvaluator._HandleParenthesisContent(query, evaluateCallback);
  61164. }
  61165. else {
  61166. query = query.replace(/\([^\(\)]*\)/g, function (r) {
  61167. // remove parenthesis
  61168. r = r.slice(1, r.length - 1);
  61169. return AndOrNotEvaluator._HandleParenthesisContent(r, evaluateCallback);
  61170. });
  61171. }
  61172. if (query === "true") {
  61173. return true;
  61174. }
  61175. if (query === "false") {
  61176. return false;
  61177. }
  61178. return AndOrNotEvaluator.Eval(query, evaluateCallback);
  61179. };
  61180. AndOrNotEvaluator._HandleParenthesisContent = function (parenthesisContent, evaluateCallback) {
  61181. evaluateCallback = evaluateCallback || (function (r) {
  61182. return r === "true" ? true : false;
  61183. });
  61184. var result;
  61185. var or = parenthesisContent.split("||");
  61186. for (var i in or) {
  61187. if (or.hasOwnProperty(i)) {
  61188. var ori = AndOrNotEvaluator._SimplifyNegation(or[i].trim());
  61189. var and = ori.split("&&");
  61190. if (and.length > 1) {
  61191. for (var j = 0; j < and.length; ++j) {
  61192. var andj = AndOrNotEvaluator._SimplifyNegation(and[j].trim());
  61193. if (andj !== "true" && andj !== "false") {
  61194. if (andj[0] === "!") {
  61195. result = !evaluateCallback(andj.substring(1));
  61196. }
  61197. else {
  61198. result = evaluateCallback(andj);
  61199. }
  61200. }
  61201. else {
  61202. result = andj === "true" ? true : false;
  61203. }
  61204. if (!result) {
  61205. ori = "false";
  61206. break;
  61207. }
  61208. }
  61209. }
  61210. if (result || ori === "true") {
  61211. result = true;
  61212. break;
  61213. }
  61214. // result equals false (or undefined)
  61215. if (ori !== "true" && ori !== "false") {
  61216. if (ori[0] === "!") {
  61217. result = !evaluateCallback(ori.substring(1));
  61218. }
  61219. else {
  61220. result = evaluateCallback(ori);
  61221. }
  61222. }
  61223. else {
  61224. result = ori === "true" ? true : false;
  61225. }
  61226. }
  61227. }
  61228. // the whole parenthesis scope is replaced by 'true' or 'false'
  61229. return result ? "true" : "false";
  61230. };
  61231. AndOrNotEvaluator._SimplifyNegation = function (booleanString) {
  61232. booleanString = booleanString.replace(/^[\s!]+/, function (r) {
  61233. // remove whitespaces
  61234. r = r.replace(/[\s]/g, function () { return ""; });
  61235. return r.length % 2 ? "!" : "";
  61236. });
  61237. booleanString = booleanString.trim();
  61238. if (booleanString === "!true") {
  61239. booleanString = "false";
  61240. }
  61241. else if (booleanString === "!false") {
  61242. booleanString = "true";
  61243. }
  61244. return booleanString;
  61245. };
  61246. return AndOrNotEvaluator;
  61247. }());
  61248. BABYLON.AndOrNotEvaluator = AndOrNotEvaluator;
  61249. })(BABYLON || (BABYLON = {}));
  61250. //# sourceMappingURL=babylon.andOrNotEvaluator.js.map
  61251. var BABYLON;
  61252. (function (BABYLON) {
  61253. var Database = /** @class */ (function () {
  61254. function Database(urlToScene, callbackManifestChecked) {
  61255. // Handling various flavors of prefixed version of IndexedDB
  61256. this.idbFactory = (window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB);
  61257. this.callbackManifestChecked = callbackManifestChecked;
  61258. this.currentSceneUrl = Database.ReturnFullUrlLocation(urlToScene);
  61259. this.db = null;
  61260. this._enableSceneOffline = false;
  61261. this._enableTexturesOffline = false;
  61262. this.manifestVersionFound = 0;
  61263. this.mustUpdateRessources = false;
  61264. this.hasReachedQuota = false;
  61265. if (!Database.IDBStorageEnabled) {
  61266. this.callbackManifestChecked(true);
  61267. }
  61268. else {
  61269. this.checkManifestFile();
  61270. }
  61271. }
  61272. Object.defineProperty(Database.prototype, "enableSceneOffline", {
  61273. get: function () {
  61274. return this._enableSceneOffline;
  61275. },
  61276. enumerable: true,
  61277. configurable: true
  61278. });
  61279. Object.defineProperty(Database.prototype, "enableTexturesOffline", {
  61280. get: function () {
  61281. return this._enableTexturesOffline;
  61282. },
  61283. enumerable: true,
  61284. configurable: true
  61285. });
  61286. Database.prototype.checkManifestFile = function () {
  61287. var _this = this;
  61288. var noManifestFile = function () {
  61289. _this._enableSceneOffline = false;
  61290. _this._enableTexturesOffline = false;
  61291. _this.callbackManifestChecked(false);
  61292. };
  61293. var timeStampUsed = false;
  61294. var manifestURL = this.currentSceneUrl + ".manifest";
  61295. var xhr = new XMLHttpRequest();
  61296. if (navigator.onLine) {
  61297. // Adding a timestamp to by-pass browsers' cache
  61298. timeStampUsed = true;
  61299. manifestURL = manifestURL + (manifestURL.match(/\?/) == null ? "?" : "&") + (new Date()).getTime();
  61300. }
  61301. xhr.open("GET", manifestURL, true);
  61302. xhr.addEventListener("load", function () {
  61303. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  61304. try {
  61305. var manifestFile = JSON.parse(xhr.response);
  61306. _this._enableSceneOffline = manifestFile.enableSceneOffline;
  61307. _this._enableTexturesOffline = manifestFile.enableTexturesOffline;
  61308. if (manifestFile.version && !isNaN(parseInt(manifestFile.version))) {
  61309. _this.manifestVersionFound = manifestFile.version;
  61310. }
  61311. if (_this.callbackManifestChecked) {
  61312. _this.callbackManifestChecked(true);
  61313. }
  61314. }
  61315. catch (ex) {
  61316. noManifestFile();
  61317. }
  61318. }
  61319. else {
  61320. noManifestFile();
  61321. }
  61322. }, false);
  61323. xhr.addEventListener("error", function (event) {
  61324. if (timeStampUsed) {
  61325. timeStampUsed = false;
  61326. // Let's retry without the timeStamp
  61327. // It could fail when coupled with HTML5 Offline API
  61328. var retryManifestURL = _this.currentSceneUrl + ".manifest";
  61329. xhr.open("GET", retryManifestURL, true);
  61330. xhr.send();
  61331. }
  61332. else {
  61333. noManifestFile();
  61334. }
  61335. }, false);
  61336. try {
  61337. xhr.send();
  61338. }
  61339. catch (ex) {
  61340. BABYLON.Tools.Error("Error on XHR send request.");
  61341. this.callbackManifestChecked(false);
  61342. }
  61343. };
  61344. Database.prototype.openAsync = function (successCallback, errorCallback) {
  61345. var _this = this;
  61346. var handleError = function () {
  61347. _this.isSupported = false;
  61348. if (errorCallback)
  61349. errorCallback();
  61350. };
  61351. if (!this.idbFactory || !(this._enableSceneOffline || this._enableTexturesOffline)) {
  61352. // Your browser doesn't support IndexedDB
  61353. this.isSupported = false;
  61354. if (errorCallback)
  61355. errorCallback();
  61356. }
  61357. else {
  61358. // If the DB hasn't been opened or created yet
  61359. if (!this.db) {
  61360. this.hasReachedQuota = false;
  61361. this.isSupported = true;
  61362. var request = this.idbFactory.open("babylonjs", 1);
  61363. // Could occur if user is blocking the quota for the DB and/or doesn't grant access to IndexedDB
  61364. request.onerror = function (event) {
  61365. handleError();
  61366. };
  61367. // executes when a version change transaction cannot complete due to other active transactions
  61368. request.onblocked = function (event) {
  61369. BABYLON.Tools.Error("IDB request blocked. Please reload the page.");
  61370. handleError();
  61371. };
  61372. // DB has been opened successfully
  61373. request.onsuccess = function (event) {
  61374. _this.db = request.result;
  61375. successCallback();
  61376. };
  61377. // Initialization of the DB. Creating Scenes & Textures stores
  61378. request.onupgradeneeded = function (event) {
  61379. _this.db = (event.target).result;
  61380. if (_this.db) {
  61381. try {
  61382. _this.db.createObjectStore("scenes", { keyPath: "sceneUrl" });
  61383. _this.db.createObjectStore("versions", { keyPath: "sceneUrl" });
  61384. _this.db.createObjectStore("textures", { keyPath: "textureUrl" });
  61385. }
  61386. catch (ex) {
  61387. BABYLON.Tools.Error("Error while creating object stores. Exception: " + ex.message);
  61388. handleError();
  61389. }
  61390. }
  61391. };
  61392. }
  61393. else {
  61394. if (successCallback)
  61395. successCallback();
  61396. }
  61397. }
  61398. };
  61399. Database.prototype.loadImageFromDB = function (url, image) {
  61400. var _this = this;
  61401. var completeURL = Database.ReturnFullUrlLocation(url);
  61402. var saveAndLoadImage = function () {
  61403. if (!_this.hasReachedQuota && _this.db !== null) {
  61404. // the texture is not yet in the DB, let's try to save it
  61405. _this._saveImageIntoDBAsync(completeURL, image);
  61406. }
  61407. else {
  61408. image.src = url;
  61409. }
  61410. };
  61411. if (!this.mustUpdateRessources) {
  61412. this._loadImageFromDBAsync(completeURL, image, saveAndLoadImage);
  61413. }
  61414. else {
  61415. saveAndLoadImage();
  61416. }
  61417. };
  61418. Database.prototype._loadImageFromDBAsync = function (url, image, notInDBCallback) {
  61419. if (this.isSupported && this.db !== null) {
  61420. var texture;
  61421. var transaction = this.db.transaction(["textures"]);
  61422. transaction.onabort = function (event) {
  61423. image.src = url;
  61424. };
  61425. transaction.oncomplete = function (event) {
  61426. var blobTextureURL;
  61427. if (texture) {
  61428. var URL = window.URL || window.webkitURL;
  61429. blobTextureURL = URL.createObjectURL(texture.data, { oneTimeOnly: true });
  61430. image.onerror = function () {
  61431. BABYLON.Tools.Error("Error loading image from blob URL: " + blobTextureURL + " switching back to web url: " + url);
  61432. image.src = url;
  61433. };
  61434. image.src = blobTextureURL;
  61435. }
  61436. else {
  61437. notInDBCallback();
  61438. }
  61439. };
  61440. var getRequest = transaction.objectStore("textures").get(url);
  61441. getRequest.onsuccess = function (event) {
  61442. texture = (event.target).result;
  61443. };
  61444. getRequest.onerror = function (event) {
  61445. BABYLON.Tools.Error("Error loading texture " + url + " from DB.");
  61446. image.src = url;
  61447. };
  61448. }
  61449. else {
  61450. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  61451. image.src = url;
  61452. }
  61453. };
  61454. Database.prototype._saveImageIntoDBAsync = function (url, image) {
  61455. var _this = this;
  61456. if (this.isSupported) {
  61457. // In case of error (type not supported or quota exceeded), we're at least sending back XHR data to allow texture loading later on
  61458. var generateBlobUrl = function () {
  61459. var blobTextureURL;
  61460. if (blob) {
  61461. var URL = window.URL || window.webkitURL;
  61462. try {
  61463. blobTextureURL = URL.createObjectURL(blob, { oneTimeOnly: true });
  61464. }
  61465. // Chrome is raising a type error if we're setting the oneTimeOnly parameter
  61466. catch (ex) {
  61467. blobTextureURL = URL.createObjectURL(blob);
  61468. }
  61469. }
  61470. if (blobTextureURL) {
  61471. image.src = blobTextureURL;
  61472. }
  61473. };
  61474. if (Database.IsUASupportingBlobStorage) {
  61475. var xhr = new XMLHttpRequest(), blob;
  61476. xhr.open("GET", url, true);
  61477. xhr.responseType = "blob";
  61478. xhr.addEventListener("load", function () {
  61479. if (xhr.status === 200 && _this.db) {
  61480. // Blob as response (XHR2)
  61481. blob = xhr.response;
  61482. var transaction = _this.db.transaction(["textures"], "readwrite");
  61483. // the transaction could abort because of a QuotaExceededError error
  61484. transaction.onabort = function (event) {
  61485. try {
  61486. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  61487. var srcElement = (event.srcElement || event.target);
  61488. var error = srcElement.error;
  61489. if (error && error.name === "QuotaExceededError") {
  61490. _this.hasReachedQuota = true;
  61491. }
  61492. }
  61493. catch (ex) { }
  61494. generateBlobUrl();
  61495. };
  61496. transaction.oncomplete = function (event) {
  61497. generateBlobUrl();
  61498. };
  61499. var newTexture = { textureUrl: url, data: blob };
  61500. try {
  61501. // Put the blob into the dabase
  61502. var addRequest = transaction.objectStore("textures").put(newTexture);
  61503. addRequest.onsuccess = function (event) {
  61504. };
  61505. addRequest.onerror = function (event) {
  61506. generateBlobUrl();
  61507. };
  61508. }
  61509. catch (ex) {
  61510. // "DataCloneError" generated by Chrome when you try to inject blob into IndexedDB
  61511. if (ex.code === 25) {
  61512. Database.IsUASupportingBlobStorage = false;
  61513. }
  61514. image.src = url;
  61515. }
  61516. }
  61517. else {
  61518. image.src = url;
  61519. }
  61520. }, false);
  61521. xhr.addEventListener("error", function (event) {
  61522. BABYLON.Tools.Error("Error in XHR request in BABYLON.Database.");
  61523. image.src = url;
  61524. }, false);
  61525. xhr.send();
  61526. }
  61527. else {
  61528. image.src = url;
  61529. }
  61530. }
  61531. else {
  61532. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  61533. image.src = url;
  61534. }
  61535. };
  61536. Database.prototype._checkVersionFromDB = function (url, versionLoaded) {
  61537. var _this = this;
  61538. var updateVersion = function () {
  61539. // the version is not yet in the DB or we need to update it
  61540. _this._saveVersionIntoDBAsync(url, versionLoaded);
  61541. };
  61542. this._loadVersionFromDBAsync(url, versionLoaded, updateVersion);
  61543. };
  61544. Database.prototype._loadVersionFromDBAsync = function (url, callback, updateInDBCallback) {
  61545. var _this = this;
  61546. if (this.isSupported && this.db) {
  61547. var version;
  61548. try {
  61549. var transaction = this.db.transaction(["versions"]);
  61550. transaction.oncomplete = function (event) {
  61551. if (version) {
  61552. // If the version in the JSON file is > than the version in DB
  61553. if (_this.manifestVersionFound > version.data) {
  61554. _this.mustUpdateRessources = true;
  61555. updateInDBCallback();
  61556. }
  61557. else {
  61558. callback(version.data);
  61559. }
  61560. }
  61561. else {
  61562. _this.mustUpdateRessources = true;
  61563. updateInDBCallback();
  61564. }
  61565. };
  61566. transaction.onabort = function (event) {
  61567. callback(-1);
  61568. };
  61569. var getRequest = transaction.objectStore("versions").get(url);
  61570. getRequest.onsuccess = function (event) {
  61571. version = (event.target).result;
  61572. };
  61573. getRequest.onerror = function (event) {
  61574. BABYLON.Tools.Error("Error loading version for scene " + url + " from DB.");
  61575. callback(-1);
  61576. };
  61577. }
  61578. catch (ex) {
  61579. BABYLON.Tools.Error("Error while accessing 'versions' object store (READ OP). Exception: " + ex.message);
  61580. callback(-1);
  61581. }
  61582. }
  61583. else {
  61584. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  61585. callback(-1);
  61586. }
  61587. };
  61588. Database.prototype._saveVersionIntoDBAsync = function (url, callback) {
  61589. var _this = this;
  61590. if (this.isSupported && !this.hasReachedQuota && this.db) {
  61591. try {
  61592. // Open a transaction to the database
  61593. var transaction = this.db.transaction(["versions"], "readwrite");
  61594. // the transaction could abort because of a QuotaExceededError error
  61595. transaction.onabort = function (event) {
  61596. try {
  61597. var error = event.srcElement['error'];
  61598. if (error && error.name === "QuotaExceededError") {
  61599. _this.hasReachedQuota = true;
  61600. }
  61601. }
  61602. catch (ex) { }
  61603. callback(-1);
  61604. };
  61605. transaction.oncomplete = function (event) {
  61606. callback(_this.manifestVersionFound);
  61607. };
  61608. var newVersion = { sceneUrl: url, data: this.manifestVersionFound };
  61609. // Put the scene into the database
  61610. var addRequest = transaction.objectStore("versions").put(newVersion);
  61611. addRequest.onsuccess = function (event) {
  61612. };
  61613. addRequest.onerror = function (event) {
  61614. BABYLON.Tools.Error("Error in DB add version request in BABYLON.Database.");
  61615. };
  61616. }
  61617. catch (ex) {
  61618. BABYLON.Tools.Error("Error while accessing 'versions' object store (WRITE OP). Exception: " + ex.message);
  61619. callback(-1);
  61620. }
  61621. }
  61622. else {
  61623. callback(-1);
  61624. }
  61625. };
  61626. Database.prototype.loadFileFromDB = function (url, sceneLoaded, progressCallBack, errorCallback, useArrayBuffer) {
  61627. var _this = this;
  61628. var completeUrl = Database.ReturnFullUrlLocation(url);
  61629. var saveAndLoadFile = function () {
  61630. // the scene is not yet in the DB, let's try to save it
  61631. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack);
  61632. };
  61633. this._checkVersionFromDB(completeUrl, function (version) {
  61634. if (version !== -1) {
  61635. if (!_this.mustUpdateRessources) {
  61636. _this._loadFileFromDBAsync(completeUrl, sceneLoaded, saveAndLoadFile, useArrayBuffer);
  61637. }
  61638. else {
  61639. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack, useArrayBuffer);
  61640. }
  61641. }
  61642. else {
  61643. if (errorCallback) {
  61644. errorCallback();
  61645. }
  61646. }
  61647. });
  61648. };
  61649. Database.prototype._loadFileFromDBAsync = function (url, callback, notInDBCallback, useArrayBuffer) {
  61650. if (this.isSupported && this.db) {
  61651. var targetStore;
  61652. if (url.indexOf(".babylon") !== -1) {
  61653. targetStore = "scenes";
  61654. }
  61655. else {
  61656. targetStore = "textures";
  61657. }
  61658. var file;
  61659. var transaction = this.db.transaction([targetStore]);
  61660. transaction.oncomplete = function (event) {
  61661. if (file) {
  61662. callback(file.data);
  61663. }
  61664. else {
  61665. notInDBCallback();
  61666. }
  61667. };
  61668. transaction.onabort = function (event) {
  61669. notInDBCallback();
  61670. };
  61671. var getRequest = transaction.objectStore(targetStore).get(url);
  61672. getRequest.onsuccess = function (event) {
  61673. file = (event.target).result;
  61674. };
  61675. getRequest.onerror = function (event) {
  61676. BABYLON.Tools.Error("Error loading file " + url + " from DB.");
  61677. notInDBCallback();
  61678. };
  61679. }
  61680. else {
  61681. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  61682. callback();
  61683. }
  61684. };
  61685. Database.prototype._saveFileIntoDBAsync = function (url, callback, progressCallback, useArrayBuffer) {
  61686. var _this = this;
  61687. if (this.isSupported) {
  61688. var targetStore;
  61689. if (url.indexOf(".babylon") !== -1) {
  61690. targetStore = "scenes";
  61691. }
  61692. else {
  61693. targetStore = "textures";
  61694. }
  61695. // Create XHR
  61696. var xhr = new XMLHttpRequest();
  61697. var fileData;
  61698. xhr.open("GET", url, true);
  61699. if (useArrayBuffer) {
  61700. xhr.responseType = "arraybuffer";
  61701. }
  61702. if (progressCallback) {
  61703. xhr.onprogress = progressCallback;
  61704. }
  61705. xhr.addEventListener("load", function () {
  61706. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, !useArrayBuffer ? 1 : 6)) {
  61707. // Blob as response (XHR2)
  61708. //fileData = xhr.responseText;
  61709. fileData = !useArrayBuffer ? xhr.responseText : xhr.response;
  61710. if (!_this.hasReachedQuota && _this.db) {
  61711. // Open a transaction to the database
  61712. var transaction = _this.db.transaction([targetStore], "readwrite");
  61713. // the transaction could abort because of a QuotaExceededError error
  61714. transaction.onabort = function (event) {
  61715. try {
  61716. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  61717. var error = event.srcElement['error'];
  61718. if (error && error.name === "QuotaExceededError") {
  61719. _this.hasReachedQuota = true;
  61720. }
  61721. }
  61722. catch (ex) { }
  61723. callback(fileData);
  61724. };
  61725. transaction.oncomplete = function (event) {
  61726. callback(fileData);
  61727. };
  61728. var newFile;
  61729. if (targetStore === "scenes") {
  61730. newFile = { sceneUrl: url, data: fileData, version: _this.manifestVersionFound };
  61731. }
  61732. else {
  61733. newFile = { textureUrl: url, data: fileData };
  61734. }
  61735. try {
  61736. // Put the scene into the database
  61737. var addRequest = transaction.objectStore(targetStore).put(newFile);
  61738. addRequest.onsuccess = function (event) {
  61739. };
  61740. addRequest.onerror = function (event) {
  61741. BABYLON.Tools.Error("Error in DB add file request in BABYLON.Database.");
  61742. };
  61743. }
  61744. catch (ex) {
  61745. callback(fileData);
  61746. }
  61747. }
  61748. else {
  61749. callback(fileData);
  61750. }
  61751. }
  61752. else {
  61753. callback();
  61754. }
  61755. }, false);
  61756. xhr.addEventListener("error", function (event) {
  61757. BABYLON.Tools.Error("error on XHR request.");
  61758. callback();
  61759. }, false);
  61760. xhr.send();
  61761. }
  61762. else {
  61763. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  61764. callback();
  61765. }
  61766. };
  61767. Database.IsUASupportingBlobStorage = true;
  61768. Database.IDBStorageEnabled = true;
  61769. Database.parseURL = function (url) {
  61770. var a = document.createElement('a');
  61771. a.href = url;
  61772. var urlWithoutHash = url.substring(0, url.lastIndexOf("#"));
  61773. var fileName = url.substring(urlWithoutHash.lastIndexOf("/") + 1, url.length);
  61774. var absLocation = url.substring(0, url.indexOf(fileName, 0));
  61775. return absLocation;
  61776. };
  61777. Database.ReturnFullUrlLocation = function (url) {
  61778. if (url.indexOf("http:/") === -1 && url.indexOf("https:/") === -1) {
  61779. return (Database.parseURL(window.location.href) + url);
  61780. }
  61781. else {
  61782. return url;
  61783. }
  61784. };
  61785. return Database;
  61786. }());
  61787. BABYLON.Database = Database;
  61788. })(BABYLON || (BABYLON = {}));
  61789. //# sourceMappingURL=babylon.database.js.map
  61790. var BABYLON;
  61791. (function (BABYLON) {
  61792. var FresnelParameters = /** @class */ (function () {
  61793. function FresnelParameters() {
  61794. this._isEnabled = true;
  61795. this.leftColor = BABYLON.Color3.White();
  61796. this.rightColor = BABYLON.Color3.Black();
  61797. this.bias = 0;
  61798. this.power = 1;
  61799. }
  61800. Object.defineProperty(FresnelParameters.prototype, "isEnabled", {
  61801. get: function () {
  61802. return this._isEnabled;
  61803. },
  61804. set: function (value) {
  61805. if (this._isEnabled === value) {
  61806. return;
  61807. }
  61808. this._isEnabled = value;
  61809. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.FresnelDirtyFlag | BABYLON.Material.MiscDirtyFlag);
  61810. },
  61811. enumerable: true,
  61812. configurable: true
  61813. });
  61814. FresnelParameters.prototype.clone = function () {
  61815. var newFresnelParameters = new FresnelParameters();
  61816. BABYLON.Tools.DeepCopy(this, newFresnelParameters);
  61817. return newFresnelParameters;
  61818. };
  61819. FresnelParameters.prototype.serialize = function () {
  61820. var serializationObject = {};
  61821. serializationObject.isEnabled = this.isEnabled;
  61822. serializationObject.leftColor = this.leftColor;
  61823. serializationObject.rightColor = this.rightColor;
  61824. serializationObject.bias = this.bias;
  61825. serializationObject.power = this.power;
  61826. return serializationObject;
  61827. };
  61828. FresnelParameters.Parse = function (parsedFresnelParameters) {
  61829. var fresnelParameters = new FresnelParameters();
  61830. fresnelParameters.isEnabled = parsedFresnelParameters.isEnabled;
  61831. fresnelParameters.leftColor = BABYLON.Color3.FromArray(parsedFresnelParameters.leftColor);
  61832. fresnelParameters.rightColor = BABYLON.Color3.FromArray(parsedFresnelParameters.rightColor);
  61833. fresnelParameters.bias = parsedFresnelParameters.bias;
  61834. fresnelParameters.power = parsedFresnelParameters.power || 1.0;
  61835. return fresnelParameters;
  61836. };
  61837. return FresnelParameters;
  61838. }());
  61839. BABYLON.FresnelParameters = FresnelParameters;
  61840. })(BABYLON || (BABYLON = {}));
  61841. //# sourceMappingURL=babylon.fresnelParameters.js.map
  61842. var BABYLON;
  61843. (function (BABYLON) {
  61844. var MultiMaterial = /** @class */ (function (_super) {
  61845. __extends(MultiMaterial, _super);
  61846. function MultiMaterial(name, scene) {
  61847. var _this = _super.call(this, name, scene, true) || this;
  61848. scene.multiMaterials.push(_this);
  61849. _this.subMaterials = new Array();
  61850. _this.storeEffectOnSubMeshes = true; // multimaterial is considered like a push material
  61851. return _this;
  61852. }
  61853. Object.defineProperty(MultiMaterial.prototype, "subMaterials", {
  61854. get: function () {
  61855. return this._subMaterials;
  61856. },
  61857. set: function (value) {
  61858. this._subMaterials = value;
  61859. this._hookArray(value);
  61860. },
  61861. enumerable: true,
  61862. configurable: true
  61863. });
  61864. MultiMaterial.prototype._hookArray = function (array) {
  61865. var _this = this;
  61866. var oldPush = array.push;
  61867. array.push = function () {
  61868. var items = [];
  61869. for (var _i = 0; _i < arguments.length; _i++) {
  61870. items[_i] = arguments[_i];
  61871. }
  61872. var result = oldPush.apply(array, items);
  61873. _this._markAllSubMeshesAsTexturesDirty();
  61874. return result;
  61875. };
  61876. var oldSplice = array.splice;
  61877. array.splice = function (index, deleteCount) {
  61878. var deleted = oldSplice.apply(array, [index, deleteCount]);
  61879. _this._markAllSubMeshesAsTexturesDirty();
  61880. return deleted;
  61881. };
  61882. };
  61883. // Properties
  61884. MultiMaterial.prototype.getSubMaterial = function (index) {
  61885. if (index < 0 || index >= this.subMaterials.length) {
  61886. return this.getScene().defaultMaterial;
  61887. }
  61888. return this.subMaterials[index];
  61889. };
  61890. MultiMaterial.prototype.getActiveTextures = function () {
  61891. return (_a = _super.prototype.getActiveTextures.call(this)).concat.apply(_a, this.subMaterials.map(function (subMaterial) {
  61892. if (subMaterial) {
  61893. return subMaterial.getActiveTextures();
  61894. }
  61895. else {
  61896. return [];
  61897. }
  61898. }));
  61899. var _a;
  61900. };
  61901. // Methods
  61902. MultiMaterial.prototype.getClassName = function () {
  61903. return "MultiMaterial";
  61904. };
  61905. MultiMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  61906. for (var index = 0; index < this.subMaterials.length; index++) {
  61907. var subMaterial = this.subMaterials[index];
  61908. if (subMaterial) {
  61909. if (subMaterial.storeEffectOnSubMeshes) {
  61910. if (!subMaterial.isReadyForSubMesh(mesh, subMesh, useInstances)) {
  61911. return false;
  61912. }
  61913. continue;
  61914. }
  61915. if (!subMaterial.isReady(mesh)) {
  61916. return false;
  61917. }
  61918. }
  61919. }
  61920. return true;
  61921. };
  61922. MultiMaterial.prototype.clone = function (name, cloneChildren) {
  61923. var newMultiMaterial = new MultiMaterial(name, this.getScene());
  61924. for (var index = 0; index < this.subMaterials.length; index++) {
  61925. var subMaterial = null;
  61926. var current = this.subMaterials[index];
  61927. if (cloneChildren && current) {
  61928. subMaterial = current.clone(name + "-" + current.name);
  61929. }
  61930. else {
  61931. subMaterial = this.subMaterials[index];
  61932. }
  61933. newMultiMaterial.subMaterials.push(subMaterial);
  61934. }
  61935. return newMultiMaterial;
  61936. };
  61937. MultiMaterial.prototype.serialize = function () {
  61938. var serializationObject = {};
  61939. serializationObject.name = this.name;
  61940. serializationObject.id = this.id;
  61941. if (BABYLON.Tags) {
  61942. serializationObject.tags = BABYLON.Tags.GetTags(this);
  61943. }
  61944. serializationObject.materials = [];
  61945. for (var matIndex = 0; matIndex < this.subMaterials.length; matIndex++) {
  61946. var subMat = this.subMaterials[matIndex];
  61947. if (subMat) {
  61948. serializationObject.materials.push(subMat.id);
  61949. }
  61950. else {
  61951. serializationObject.materials.push(null);
  61952. }
  61953. }
  61954. return serializationObject;
  61955. };
  61956. MultiMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  61957. var scene = this.getScene();
  61958. if (!scene) {
  61959. return;
  61960. }
  61961. var index = scene.multiMaterials.indexOf(this);
  61962. if (index >= 0) {
  61963. scene.multiMaterials.splice(index, 1);
  61964. }
  61965. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  61966. };
  61967. return MultiMaterial;
  61968. }(BABYLON.Material));
  61969. BABYLON.MultiMaterial = MultiMaterial;
  61970. })(BABYLON || (BABYLON = {}));
  61971. //# sourceMappingURL=babylon.multiMaterial.js.map
  61972. var BABYLON;
  61973. (function (BABYLON) {
  61974. var FreeCameraTouchInput = /** @class */ (function () {
  61975. function FreeCameraTouchInput() {
  61976. this._offsetX = null;
  61977. this._offsetY = null;
  61978. this._pointerPressed = new Array();
  61979. this.touchAngularSensibility = 200000.0;
  61980. this.touchMoveSensibility = 250.0;
  61981. }
  61982. FreeCameraTouchInput.prototype.attachControl = function (element, noPreventDefault) {
  61983. var _this = this;
  61984. var previousPosition = null;
  61985. if (this._pointerInput === undefined) {
  61986. this._onLostFocus = function (evt) {
  61987. _this._offsetX = null;
  61988. _this._offsetY = null;
  61989. };
  61990. this._pointerInput = function (p, s) {
  61991. var evt = p.event;
  61992. if (evt.pointerType === "mouse") {
  61993. return;
  61994. }
  61995. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  61996. if (!noPreventDefault) {
  61997. evt.preventDefault();
  61998. }
  61999. _this._pointerPressed.push(evt.pointerId);
  62000. if (_this._pointerPressed.length !== 1) {
  62001. return;
  62002. }
  62003. previousPosition = {
  62004. x: evt.clientX,
  62005. y: evt.clientY
  62006. };
  62007. }
  62008. else if (p.type === BABYLON.PointerEventTypes.POINTERUP) {
  62009. if (!noPreventDefault) {
  62010. evt.preventDefault();
  62011. }
  62012. var index = _this._pointerPressed.indexOf(evt.pointerId);
  62013. if (index === -1) {
  62014. return;
  62015. }
  62016. _this._pointerPressed.splice(index, 1);
  62017. if (index != 0) {
  62018. return;
  62019. }
  62020. previousPosition = null;
  62021. _this._offsetX = null;
  62022. _this._offsetY = null;
  62023. }
  62024. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  62025. if (!noPreventDefault) {
  62026. evt.preventDefault();
  62027. }
  62028. if (!previousPosition) {
  62029. return;
  62030. }
  62031. var index = _this._pointerPressed.indexOf(evt.pointerId);
  62032. if (index != 0) {
  62033. return;
  62034. }
  62035. _this._offsetX = evt.clientX - previousPosition.x;
  62036. _this._offsetY = -(evt.clientY - previousPosition.y);
  62037. }
  62038. };
  62039. }
  62040. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  62041. if (this._onLostFocus) {
  62042. element.addEventListener("blur", this._onLostFocus);
  62043. }
  62044. };
  62045. FreeCameraTouchInput.prototype.detachControl = function (element) {
  62046. if (this._pointerInput && element) {
  62047. if (this._observer) {
  62048. this.camera.getScene().onPointerObservable.remove(this._observer);
  62049. this._observer = null;
  62050. }
  62051. if (this._onLostFocus) {
  62052. element.removeEventListener("blur", this._onLostFocus);
  62053. this._onLostFocus = null;
  62054. }
  62055. this._pointerPressed = [];
  62056. this._offsetX = null;
  62057. this._offsetY = null;
  62058. }
  62059. };
  62060. FreeCameraTouchInput.prototype.checkInputs = function () {
  62061. if (this._offsetX && this._offsetY) {
  62062. var camera = this.camera;
  62063. camera.cameraRotation.y += this._offsetX / this.touchAngularSensibility;
  62064. if (this._pointerPressed.length > 1) {
  62065. camera.cameraRotation.x += -this._offsetY / this.touchAngularSensibility;
  62066. }
  62067. else {
  62068. var speed = camera._computeLocalCameraSpeed();
  62069. var direction = new BABYLON.Vector3(0, 0, speed * this._offsetY / this.touchMoveSensibility);
  62070. BABYLON.Matrix.RotationYawPitchRollToRef(camera.rotation.y, camera.rotation.x, 0, camera._cameraRotationMatrix);
  62071. camera.cameraDirection.addInPlace(BABYLON.Vector3.TransformCoordinates(direction, camera._cameraRotationMatrix));
  62072. }
  62073. }
  62074. };
  62075. FreeCameraTouchInput.prototype.getClassName = function () {
  62076. return "FreeCameraTouchInput";
  62077. };
  62078. FreeCameraTouchInput.prototype.getSimpleName = function () {
  62079. return "touch";
  62080. };
  62081. __decorate([
  62082. BABYLON.serialize()
  62083. ], FreeCameraTouchInput.prototype, "touchAngularSensibility", void 0);
  62084. __decorate([
  62085. BABYLON.serialize()
  62086. ], FreeCameraTouchInput.prototype, "touchMoveSensibility", void 0);
  62087. return FreeCameraTouchInput;
  62088. }());
  62089. BABYLON.FreeCameraTouchInput = FreeCameraTouchInput;
  62090. BABYLON.CameraInputTypes["FreeCameraTouchInput"] = FreeCameraTouchInput;
  62091. })(BABYLON || (BABYLON = {}));
  62092. //# sourceMappingURL=babylon.freeCameraTouchInput.js.map
  62093. var BABYLON;
  62094. (function (BABYLON) {
  62095. // We're mainly based on the logic defined into the FreeCamera code
  62096. var TouchCamera = /** @class */ (function (_super) {
  62097. __extends(TouchCamera, _super);
  62098. //-- end properties for backward compatibility for inputs
  62099. function TouchCamera(name, position, scene) {
  62100. var _this = _super.call(this, name, position, scene) || this;
  62101. _this.inputs.addTouch();
  62102. _this._setupInputs();
  62103. return _this;
  62104. }
  62105. Object.defineProperty(TouchCamera.prototype, "touchAngularSensibility", {
  62106. //-- Begin properties for backward compatibility for inputs
  62107. get: function () {
  62108. var touch = this.inputs.attached["touch"];
  62109. if (touch)
  62110. return touch.touchAngularSensibility;
  62111. return 0;
  62112. },
  62113. set: function (value) {
  62114. var touch = this.inputs.attached["touch"];
  62115. if (touch)
  62116. touch.touchAngularSensibility = value;
  62117. },
  62118. enumerable: true,
  62119. configurable: true
  62120. });
  62121. Object.defineProperty(TouchCamera.prototype, "touchMoveSensibility", {
  62122. get: function () {
  62123. var touch = this.inputs.attached["touch"];
  62124. if (touch)
  62125. return touch.touchMoveSensibility;
  62126. return 0;
  62127. },
  62128. set: function (value) {
  62129. var touch = this.inputs.attached["touch"];
  62130. if (touch)
  62131. touch.touchMoveSensibility = value;
  62132. },
  62133. enumerable: true,
  62134. configurable: true
  62135. });
  62136. TouchCamera.prototype.getClassName = function () {
  62137. return "TouchCamera";
  62138. };
  62139. TouchCamera.prototype._setupInputs = function () {
  62140. var mouse = this.inputs.attached["mouse"];
  62141. if (mouse) {
  62142. mouse.touchEnabled = false;
  62143. }
  62144. };
  62145. return TouchCamera;
  62146. }(BABYLON.FreeCamera));
  62147. BABYLON.TouchCamera = TouchCamera;
  62148. })(BABYLON || (BABYLON = {}));
  62149. //# sourceMappingURL=babylon.touchCamera.js.map
  62150. var BABYLON;
  62151. (function (BABYLON) {
  62152. var ProceduralTexture = /** @class */ (function (_super) {
  62153. __extends(ProceduralTexture, _super);
  62154. function ProceduralTexture(name, size, fragment, scene, fallbackTexture, generateMipMaps, isCube) {
  62155. if (fallbackTexture === void 0) { fallbackTexture = null; }
  62156. if (generateMipMaps === void 0) { generateMipMaps = true; }
  62157. if (isCube === void 0) { isCube = false; }
  62158. var _this = _super.call(this, null, scene, !generateMipMaps) || this;
  62159. _this.isCube = isCube;
  62160. _this.isEnabled = true;
  62161. _this._currentRefreshId = -1;
  62162. _this._refreshRate = 1;
  62163. _this._vertexBuffers = {};
  62164. _this._uniforms = new Array();
  62165. _this._samplers = new Array();
  62166. _this._textures = {};
  62167. _this._floats = {};
  62168. _this._floatsArrays = {};
  62169. _this._colors3 = {};
  62170. _this._colors4 = {};
  62171. _this._vectors2 = {};
  62172. _this._vectors3 = {};
  62173. _this._matrices = {};
  62174. _this._fallbackTextureUsed = false;
  62175. scene._proceduralTextures.push(_this);
  62176. _this._engine = scene.getEngine();
  62177. _this.name = name;
  62178. _this.isRenderTarget = true;
  62179. _this._size = size;
  62180. _this._generateMipMaps = generateMipMaps;
  62181. _this.setFragment(fragment);
  62182. _this._fallbackTexture = fallbackTexture;
  62183. if (isCube) {
  62184. _this._texture = _this._engine.createRenderTargetCubeTexture(size, { generateMipMaps: generateMipMaps });
  62185. _this.setFloat("face", 0);
  62186. }
  62187. else {
  62188. _this._texture = _this._engine.createRenderTargetTexture(size, generateMipMaps);
  62189. }
  62190. // VBO
  62191. var vertices = [];
  62192. vertices.push(1, 1);
  62193. vertices.push(-1, 1);
  62194. vertices.push(-1, -1);
  62195. vertices.push(1, -1);
  62196. _this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(_this._engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  62197. _this._createIndexBuffer();
  62198. return _this;
  62199. }
  62200. ProceduralTexture.prototype._createIndexBuffer = function () {
  62201. var engine = this._engine;
  62202. // Indices
  62203. var indices = [];
  62204. indices.push(0);
  62205. indices.push(1);
  62206. indices.push(2);
  62207. indices.push(0);
  62208. indices.push(2);
  62209. indices.push(3);
  62210. this._indexBuffer = engine.createIndexBuffer(indices);
  62211. };
  62212. ProceduralTexture.prototype._rebuild = function () {
  62213. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  62214. if (vb) {
  62215. vb._rebuild();
  62216. }
  62217. this._createIndexBuffer();
  62218. if (this.refreshRate === BABYLON.RenderTargetTexture.REFRESHRATE_RENDER_ONCE) {
  62219. this.refreshRate = BABYLON.RenderTargetTexture.REFRESHRATE_RENDER_ONCE;
  62220. }
  62221. };
  62222. ProceduralTexture.prototype.reset = function () {
  62223. if (this._effect === undefined) {
  62224. return;
  62225. }
  62226. var engine = this._engine;
  62227. engine._releaseEffect(this._effect);
  62228. };
  62229. ProceduralTexture.prototype.isReady = function () {
  62230. var _this = this;
  62231. var engine = this._engine;
  62232. var shaders;
  62233. if (!this._fragment) {
  62234. return false;
  62235. }
  62236. if (this._fallbackTextureUsed) {
  62237. return true;
  62238. }
  62239. if (this._fragment.fragmentElement !== undefined) {
  62240. shaders = { vertex: "procedural", fragmentElement: this._fragment.fragmentElement };
  62241. }
  62242. else {
  62243. shaders = { vertex: "procedural", fragment: this._fragment };
  62244. }
  62245. this._effect = engine.createEffect(shaders, [BABYLON.VertexBuffer.PositionKind], this._uniforms, this._samplers, "", undefined, undefined, function () {
  62246. _this.releaseInternalTexture();
  62247. if (_this._fallbackTexture) {
  62248. _this._texture = _this._fallbackTexture._texture;
  62249. if (_this._texture) {
  62250. _this._texture.incrementReferences();
  62251. }
  62252. }
  62253. _this._fallbackTextureUsed = true;
  62254. });
  62255. return this._effect.isReady();
  62256. };
  62257. ProceduralTexture.prototype.resetRefreshCounter = function () {
  62258. this._currentRefreshId = -1;
  62259. };
  62260. ProceduralTexture.prototype.setFragment = function (fragment) {
  62261. this._fragment = fragment;
  62262. };
  62263. Object.defineProperty(ProceduralTexture.prototype, "refreshRate", {
  62264. get: function () {
  62265. return this._refreshRate;
  62266. },
  62267. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  62268. set: function (value) {
  62269. this._refreshRate = value;
  62270. this.resetRefreshCounter();
  62271. },
  62272. enumerable: true,
  62273. configurable: true
  62274. });
  62275. ProceduralTexture.prototype._shouldRender = function () {
  62276. if (!this.isEnabled || !this.isReady() || !this._texture) {
  62277. return false;
  62278. }
  62279. if (this._fallbackTextureUsed) {
  62280. return false;
  62281. }
  62282. if (this._currentRefreshId === -1) {
  62283. this._currentRefreshId = 1;
  62284. return true;
  62285. }
  62286. if (this.refreshRate === this._currentRefreshId) {
  62287. this._currentRefreshId = 1;
  62288. return true;
  62289. }
  62290. this._currentRefreshId++;
  62291. return false;
  62292. };
  62293. ProceduralTexture.prototype.getRenderSize = function () {
  62294. return this._size;
  62295. };
  62296. ProceduralTexture.prototype.resize = function (size, generateMipMaps) {
  62297. if (this._fallbackTextureUsed) {
  62298. return;
  62299. }
  62300. this.releaseInternalTexture();
  62301. this._texture = this._engine.createRenderTargetTexture(size, generateMipMaps);
  62302. };
  62303. ProceduralTexture.prototype._checkUniform = function (uniformName) {
  62304. if (this._uniforms.indexOf(uniformName) === -1) {
  62305. this._uniforms.push(uniformName);
  62306. }
  62307. };
  62308. ProceduralTexture.prototype.setTexture = function (name, texture) {
  62309. if (this._samplers.indexOf(name) === -1) {
  62310. this._samplers.push(name);
  62311. }
  62312. this._textures[name] = texture;
  62313. return this;
  62314. };
  62315. ProceduralTexture.prototype.setFloat = function (name, value) {
  62316. this._checkUniform(name);
  62317. this._floats[name] = value;
  62318. return this;
  62319. };
  62320. ProceduralTexture.prototype.setFloats = function (name, value) {
  62321. this._checkUniform(name);
  62322. this._floatsArrays[name] = value;
  62323. return this;
  62324. };
  62325. ProceduralTexture.prototype.setColor3 = function (name, value) {
  62326. this._checkUniform(name);
  62327. this._colors3[name] = value;
  62328. return this;
  62329. };
  62330. ProceduralTexture.prototype.setColor4 = function (name, value) {
  62331. this._checkUniform(name);
  62332. this._colors4[name] = value;
  62333. return this;
  62334. };
  62335. ProceduralTexture.prototype.setVector2 = function (name, value) {
  62336. this._checkUniform(name);
  62337. this._vectors2[name] = value;
  62338. return this;
  62339. };
  62340. ProceduralTexture.prototype.setVector3 = function (name, value) {
  62341. this._checkUniform(name);
  62342. this._vectors3[name] = value;
  62343. return this;
  62344. };
  62345. ProceduralTexture.prototype.setMatrix = function (name, value) {
  62346. this._checkUniform(name);
  62347. this._matrices[name] = value;
  62348. return this;
  62349. };
  62350. ProceduralTexture.prototype.render = function (useCameraPostProcess) {
  62351. var scene = this.getScene();
  62352. if (!scene) {
  62353. return;
  62354. }
  62355. var engine = this._engine;
  62356. // Render
  62357. engine.enableEffect(this._effect);
  62358. engine.setState(false);
  62359. // Texture
  62360. for (var name in this._textures) {
  62361. this._effect.setTexture(name, this._textures[name]);
  62362. }
  62363. // Float
  62364. for (name in this._floats) {
  62365. this._effect.setFloat(name, this._floats[name]);
  62366. }
  62367. // Floats
  62368. for (name in this._floatsArrays) {
  62369. this._effect.setArray(name, this._floatsArrays[name]);
  62370. }
  62371. // Color3
  62372. for (name in this._colors3) {
  62373. this._effect.setColor3(name, this._colors3[name]);
  62374. }
  62375. // Color4
  62376. for (name in this._colors4) {
  62377. var color = this._colors4[name];
  62378. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  62379. }
  62380. // Vector2
  62381. for (name in this._vectors2) {
  62382. this._effect.setVector2(name, this._vectors2[name]);
  62383. }
  62384. // Vector3
  62385. for (name in this._vectors3) {
  62386. this._effect.setVector3(name, this._vectors3[name]);
  62387. }
  62388. // Matrix
  62389. for (name in this._matrices) {
  62390. this._effect.setMatrix(name, this._matrices[name]);
  62391. }
  62392. if (!this._texture) {
  62393. return;
  62394. }
  62395. if (this.isCube) {
  62396. for (var face = 0; face < 6; face++) {
  62397. engine.bindFramebuffer(this._texture, face, undefined, undefined, true);
  62398. // VBOs
  62399. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  62400. this._effect.setFloat("face", face);
  62401. // Clear
  62402. engine.clear(scene.clearColor, true, true, true);
  62403. // Draw order
  62404. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  62405. // Mipmaps
  62406. if (face === 5) {
  62407. engine.generateMipMapsForCubemap(this._texture);
  62408. }
  62409. }
  62410. }
  62411. else {
  62412. engine.bindFramebuffer(this._texture, 0, undefined, undefined, true);
  62413. // VBOs
  62414. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  62415. // Clear
  62416. engine.clear(scene.clearColor, true, true, true);
  62417. // Draw order
  62418. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  62419. }
  62420. // Unbind
  62421. engine.unBindFramebuffer(this._texture, this.isCube);
  62422. if (this.onGenerated) {
  62423. this.onGenerated();
  62424. }
  62425. };
  62426. ProceduralTexture.prototype.clone = function () {
  62427. var textureSize = this.getSize();
  62428. var newTexture = new ProceduralTexture(this.name, textureSize.width, this._fragment, this.getScene(), this._fallbackTexture, this._generateMipMaps);
  62429. // Base texture
  62430. newTexture.hasAlpha = this.hasAlpha;
  62431. newTexture.level = this.level;
  62432. // RenderTarget Texture
  62433. newTexture.coordinatesMode = this.coordinatesMode;
  62434. return newTexture;
  62435. };
  62436. ProceduralTexture.prototype.dispose = function () {
  62437. var scene = this.getScene();
  62438. if (!scene) {
  62439. return;
  62440. }
  62441. var index = scene._proceduralTextures.indexOf(this);
  62442. if (index >= 0) {
  62443. scene._proceduralTextures.splice(index, 1);
  62444. }
  62445. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  62446. if (vertexBuffer) {
  62447. vertexBuffer.dispose();
  62448. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  62449. }
  62450. if (this._indexBuffer && this._engine._releaseBuffer(this._indexBuffer)) {
  62451. this._indexBuffer = null;
  62452. }
  62453. _super.prototype.dispose.call(this);
  62454. };
  62455. return ProceduralTexture;
  62456. }(BABYLON.Texture));
  62457. BABYLON.ProceduralTexture = ProceduralTexture;
  62458. })(BABYLON || (BABYLON = {}));
  62459. //# sourceMappingURL=babylon.proceduralTexture.js.map
  62460. var BABYLON;
  62461. (function (BABYLON) {
  62462. var CustomProceduralTexture = /** @class */ (function (_super) {
  62463. __extends(CustomProceduralTexture, _super);
  62464. function CustomProceduralTexture(name, texturePath, size, scene, fallbackTexture, generateMipMaps) {
  62465. var _this = _super.call(this, name, size, null, scene, fallbackTexture, generateMipMaps) || this;
  62466. _this._animate = true;
  62467. _this._time = 0;
  62468. _this._texturePath = texturePath;
  62469. //Try to load json
  62470. _this.loadJson(texturePath);
  62471. _this.refreshRate = 1;
  62472. return _this;
  62473. }
  62474. CustomProceduralTexture.prototype.loadJson = function (jsonUrl) {
  62475. var _this = this;
  62476. var noConfigFile = function () {
  62477. BABYLON.Tools.Log("No config file found in " + jsonUrl + " trying to use ShadersStore or DOM element");
  62478. try {
  62479. _this.setFragment(_this._texturePath);
  62480. }
  62481. catch (ex) {
  62482. BABYLON.Tools.Error("No json or ShaderStore or DOM element found for CustomProceduralTexture");
  62483. }
  62484. };
  62485. var configFileUrl = jsonUrl + "/config.json";
  62486. var xhr = new XMLHttpRequest();
  62487. xhr.open("GET", configFileUrl, true);
  62488. xhr.addEventListener("load", function () {
  62489. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  62490. try {
  62491. _this._config = JSON.parse(xhr.response);
  62492. _this.updateShaderUniforms();
  62493. _this.updateTextures();
  62494. _this.setFragment(_this._texturePath + "/custom");
  62495. _this._animate = _this._config.animate;
  62496. _this.refreshRate = _this._config.refreshrate;
  62497. }
  62498. catch (ex) {
  62499. noConfigFile();
  62500. }
  62501. }
  62502. else {
  62503. noConfigFile();
  62504. }
  62505. }, false);
  62506. xhr.addEventListener("error", function () {
  62507. noConfigFile();
  62508. }, false);
  62509. try {
  62510. xhr.send();
  62511. }
  62512. catch (ex) {
  62513. BABYLON.Tools.Error("CustomProceduralTexture: Error on XHR send request.");
  62514. }
  62515. };
  62516. CustomProceduralTexture.prototype.isReady = function () {
  62517. if (!_super.prototype.isReady.call(this)) {
  62518. return false;
  62519. }
  62520. for (var name in this._textures) {
  62521. var texture = this._textures[name];
  62522. if (!texture.isReady()) {
  62523. return false;
  62524. }
  62525. }
  62526. return true;
  62527. };
  62528. CustomProceduralTexture.prototype.render = function (useCameraPostProcess) {
  62529. var scene = this.getScene();
  62530. if (this._animate && scene) {
  62531. this._time += scene.getAnimationRatio() * 0.03;
  62532. this.updateShaderUniforms();
  62533. }
  62534. _super.prototype.render.call(this, useCameraPostProcess);
  62535. };
  62536. CustomProceduralTexture.prototype.updateTextures = function () {
  62537. for (var i = 0; i < this._config.sampler2Ds.length; i++) {
  62538. this.setTexture(this._config.sampler2Ds[i].sample2Dname, new BABYLON.Texture(this._texturePath + "/" + this._config.sampler2Ds[i].textureRelativeUrl, this.getScene()));
  62539. }
  62540. };
  62541. CustomProceduralTexture.prototype.updateShaderUniforms = function () {
  62542. if (this._config) {
  62543. for (var j = 0; j < this._config.uniforms.length; j++) {
  62544. var uniform = this._config.uniforms[j];
  62545. switch (uniform.type) {
  62546. case "float":
  62547. this.setFloat(uniform.name, uniform.value);
  62548. break;
  62549. case "color3":
  62550. this.setColor3(uniform.name, new BABYLON.Color3(uniform.r, uniform.g, uniform.b));
  62551. break;
  62552. case "color4":
  62553. this.setColor4(uniform.name, new BABYLON.Color4(uniform.r, uniform.g, uniform.b, uniform.a));
  62554. break;
  62555. case "vector2":
  62556. this.setVector2(uniform.name, new BABYLON.Vector2(uniform.x, uniform.y));
  62557. break;
  62558. case "vector3":
  62559. this.setVector3(uniform.name, new BABYLON.Vector3(uniform.x, uniform.y, uniform.z));
  62560. break;
  62561. }
  62562. }
  62563. }
  62564. this.setFloat("time", this._time);
  62565. };
  62566. Object.defineProperty(CustomProceduralTexture.prototype, "animate", {
  62567. get: function () {
  62568. return this._animate;
  62569. },
  62570. set: function (value) {
  62571. this._animate = value;
  62572. },
  62573. enumerable: true,
  62574. configurable: true
  62575. });
  62576. return CustomProceduralTexture;
  62577. }(BABYLON.ProceduralTexture));
  62578. BABYLON.CustomProceduralTexture = CustomProceduralTexture;
  62579. })(BABYLON || (BABYLON = {}));
  62580. //# sourceMappingURL=babylon.customProceduralTexture.js.map
  62581. var BABYLON;
  62582. (function (BABYLON) {
  62583. var FreeCameraGamepadInput = /** @class */ (function () {
  62584. function FreeCameraGamepadInput() {
  62585. this.gamepadAngularSensibility = 200;
  62586. this.gamepadMoveSensibility = 40;
  62587. // private members
  62588. this._cameraTransform = BABYLON.Matrix.Identity();
  62589. this._deltaTransform = BABYLON.Vector3.Zero();
  62590. this._vector3 = BABYLON.Vector3.Zero();
  62591. this._vector2 = BABYLON.Vector2.Zero();
  62592. }
  62593. FreeCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
  62594. var _this = this;
  62595. var manager = this.camera.getScene().gamepadManager;
  62596. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  62597. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  62598. // prioritize XBOX gamepads.
  62599. if (!_this.gamepad || gamepad.type === BABYLON.Gamepad.XBOX) {
  62600. _this.gamepad = gamepad;
  62601. }
  62602. }
  62603. });
  62604. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  62605. if (_this.gamepad === gamepad) {
  62606. _this.gamepad = null;
  62607. }
  62608. });
  62609. this.gamepad = manager.getGamepadByType(BABYLON.Gamepad.XBOX);
  62610. };
  62611. FreeCameraGamepadInput.prototype.detachControl = function (element) {
  62612. this.camera.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  62613. this.camera.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  62614. this.gamepad = null;
  62615. };
  62616. FreeCameraGamepadInput.prototype.checkInputs = function () {
  62617. if (this.gamepad && this.gamepad.leftStick) {
  62618. var camera = this.camera;
  62619. var LSValues = this.gamepad.leftStick;
  62620. var normalizedLX = LSValues.x / this.gamepadMoveSensibility;
  62621. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  62622. LSValues.x = Math.abs(normalizedLX) > 0.005 ? 0 + normalizedLX : 0;
  62623. LSValues.y = Math.abs(normalizedLY) > 0.005 ? 0 + normalizedLY : 0;
  62624. var RSValues = this.gamepad.rightStick;
  62625. if (RSValues) {
  62626. var normalizedRX = RSValues.x / this.gamepadAngularSensibility;
  62627. var normalizedRY = RSValues.y / this.gamepadAngularSensibility;
  62628. RSValues.x = Math.abs(normalizedRX) > 0.001 ? 0 + normalizedRX : 0;
  62629. RSValues.y = Math.abs(normalizedRY) > 0.001 ? 0 + normalizedRY : 0;
  62630. }
  62631. else {
  62632. RSValues = { x: 0, y: 0 };
  62633. }
  62634. if (!camera.rotationQuaternion) {
  62635. BABYLON.Matrix.RotationYawPitchRollToRef(camera.rotation.y, camera.rotation.x, 0, this._cameraTransform);
  62636. }
  62637. else {
  62638. camera.rotationQuaternion.toRotationMatrix(this._cameraTransform);
  62639. }
  62640. var speed = camera._computeLocalCameraSpeed() * 50.0;
  62641. this._vector3.copyFromFloats(LSValues.x * speed, 0, -LSValues.y * speed);
  62642. BABYLON.Vector3.TransformCoordinatesToRef(this._vector3, this._cameraTransform, this._deltaTransform);
  62643. camera.cameraDirection.addInPlace(this._deltaTransform);
  62644. this._vector2.copyFromFloats(RSValues.y, RSValues.x);
  62645. camera.cameraRotation.addInPlace(this._vector2);
  62646. }
  62647. };
  62648. FreeCameraGamepadInput.prototype.getClassName = function () {
  62649. return "FreeCameraGamepadInput";
  62650. };
  62651. FreeCameraGamepadInput.prototype.getSimpleName = function () {
  62652. return "gamepad";
  62653. };
  62654. __decorate([
  62655. BABYLON.serialize()
  62656. ], FreeCameraGamepadInput.prototype, "gamepadAngularSensibility", void 0);
  62657. __decorate([
  62658. BABYLON.serialize()
  62659. ], FreeCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
  62660. return FreeCameraGamepadInput;
  62661. }());
  62662. BABYLON.FreeCameraGamepadInput = FreeCameraGamepadInput;
  62663. BABYLON.CameraInputTypes["FreeCameraGamepadInput"] = FreeCameraGamepadInput;
  62664. })(BABYLON || (BABYLON = {}));
  62665. //# sourceMappingURL=babylon.freeCameraGamepadInput.js.map
  62666. var BABYLON;
  62667. (function (BABYLON) {
  62668. var ArcRotateCameraGamepadInput = /** @class */ (function () {
  62669. function ArcRotateCameraGamepadInput() {
  62670. this.gamepadRotationSensibility = 80;
  62671. this.gamepadMoveSensibility = 40;
  62672. }
  62673. ArcRotateCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
  62674. var _this = this;
  62675. var manager = this.camera.getScene().gamepadManager;
  62676. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  62677. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  62678. // prioritize XBOX gamepads.
  62679. if (!_this.gamepad || gamepad.type === BABYLON.Gamepad.XBOX) {
  62680. _this.gamepad = gamepad;
  62681. }
  62682. }
  62683. });
  62684. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  62685. if (_this.gamepad === gamepad) {
  62686. _this.gamepad = null;
  62687. }
  62688. });
  62689. this.gamepad = manager.getGamepadByType(BABYLON.Gamepad.XBOX);
  62690. };
  62691. ArcRotateCameraGamepadInput.prototype.detachControl = function (element) {
  62692. this.camera.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  62693. this.camera.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  62694. this.gamepad = null;
  62695. };
  62696. ArcRotateCameraGamepadInput.prototype.checkInputs = function () {
  62697. if (this.gamepad) {
  62698. var camera = this.camera;
  62699. var RSValues = this.gamepad.rightStick;
  62700. if (RSValues) {
  62701. if (RSValues.x != 0) {
  62702. var normalizedRX = RSValues.x / this.gamepadRotationSensibility;
  62703. if (normalizedRX != 0 && Math.abs(normalizedRX) > 0.005) {
  62704. camera.inertialAlphaOffset += normalizedRX;
  62705. }
  62706. }
  62707. if (RSValues.y != 0) {
  62708. var normalizedRY = RSValues.y / this.gamepadRotationSensibility;
  62709. if (normalizedRY != 0 && Math.abs(normalizedRY) > 0.005) {
  62710. camera.inertialBetaOffset += normalizedRY;
  62711. }
  62712. }
  62713. }
  62714. var LSValues = this.gamepad.leftStick;
  62715. if (LSValues && LSValues.y != 0) {
  62716. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  62717. if (normalizedLY != 0 && Math.abs(normalizedLY) > 0.005) {
  62718. this.camera.inertialRadiusOffset -= normalizedLY;
  62719. }
  62720. }
  62721. }
  62722. };
  62723. ArcRotateCameraGamepadInput.prototype.getClassName = function () {
  62724. return "ArcRotateCameraGamepadInput";
  62725. };
  62726. ArcRotateCameraGamepadInput.prototype.getSimpleName = function () {
  62727. return "gamepad";
  62728. };
  62729. __decorate([
  62730. BABYLON.serialize()
  62731. ], ArcRotateCameraGamepadInput.prototype, "gamepadRotationSensibility", void 0);
  62732. __decorate([
  62733. BABYLON.serialize()
  62734. ], ArcRotateCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
  62735. return ArcRotateCameraGamepadInput;
  62736. }());
  62737. BABYLON.ArcRotateCameraGamepadInput = ArcRotateCameraGamepadInput;
  62738. BABYLON.CameraInputTypes["ArcRotateCameraGamepadInput"] = ArcRotateCameraGamepadInput;
  62739. })(BABYLON || (BABYLON = {}));
  62740. //# sourceMappingURL=babylon.arcRotateCameraGamepadInput.js.map
  62741. var BABYLON;
  62742. (function (BABYLON) {
  62743. var GamepadManager = /** @class */ (function () {
  62744. function GamepadManager(_scene) {
  62745. var _this = this;
  62746. this._scene = _scene;
  62747. this._babylonGamepads = [];
  62748. this._oneGamepadConnected = false;
  62749. this._isMonitoring = false;
  62750. this.onGamepadDisconnectedObservable = new BABYLON.Observable();
  62751. if (!BABYLON.Tools.IsWindowObjectExist()) {
  62752. this._gamepadEventSupported = false;
  62753. }
  62754. else {
  62755. this._gamepadEventSupported = 'GamepadEvent' in window;
  62756. this._gamepadSupport = (navigator.getGamepads ||
  62757. navigator.webkitGetGamepads || navigator.msGetGamepads || navigator.webkitGamepads);
  62758. }
  62759. this.onGamepadConnectedObservable = new BABYLON.Observable(function (observer) {
  62760. // This will be used to raise the onGamepadConnected for all gamepads ALREADY connected
  62761. for (var i in _this._babylonGamepads) {
  62762. var gamepad = _this._babylonGamepads[i];
  62763. if (gamepad && gamepad._isConnected) {
  62764. _this.onGamepadConnectedObservable.notifyObserver(observer, gamepad);
  62765. }
  62766. }
  62767. });
  62768. this._onGamepadConnectedEvent = function (evt) {
  62769. var gamepad = evt.gamepad;
  62770. if (gamepad.index in _this._babylonGamepads) {
  62771. if (_this._babylonGamepads[gamepad.index].isConnected) {
  62772. return;
  62773. }
  62774. }
  62775. var newGamepad;
  62776. if (_this._babylonGamepads[gamepad.index]) {
  62777. newGamepad = _this._babylonGamepads[gamepad.index];
  62778. newGamepad.browserGamepad = gamepad;
  62779. newGamepad._isConnected = true;
  62780. }
  62781. else {
  62782. newGamepad = _this._addNewGamepad(gamepad);
  62783. }
  62784. _this.onGamepadConnectedObservable.notifyObservers(newGamepad);
  62785. _this._startMonitoringGamepads();
  62786. };
  62787. this._onGamepadDisconnectedEvent = function (evt) {
  62788. var gamepad = evt.gamepad;
  62789. // Remove the gamepad from the list of gamepads to monitor.
  62790. for (var i in _this._babylonGamepads) {
  62791. if (_this._babylonGamepads[i].index === gamepad.index) {
  62792. var disconnectedGamepad = _this._babylonGamepads[i];
  62793. disconnectedGamepad._isConnected = false;
  62794. _this.onGamepadDisconnectedObservable.notifyObservers(disconnectedGamepad);
  62795. break;
  62796. }
  62797. }
  62798. };
  62799. if (this._gamepadSupport) {
  62800. //first add already-connected gamepads
  62801. this._updateGamepadObjects();
  62802. if (this._babylonGamepads.length) {
  62803. this._startMonitoringGamepads();
  62804. }
  62805. // Checking if the gamepad connected event is supported (like in Firefox)
  62806. if (this._gamepadEventSupported) {
  62807. window.addEventListener('gamepadconnected', this._onGamepadConnectedEvent, false);
  62808. window.addEventListener('gamepaddisconnected', this._onGamepadDisconnectedEvent, false);
  62809. }
  62810. else {
  62811. this._startMonitoringGamepads();
  62812. }
  62813. }
  62814. }
  62815. Object.defineProperty(GamepadManager.prototype, "gamepads", {
  62816. get: function () {
  62817. return this._babylonGamepads;
  62818. },
  62819. enumerable: true,
  62820. configurable: true
  62821. });
  62822. GamepadManager.prototype.getGamepadByType = function (type) {
  62823. if (type === void 0) { type = BABYLON.Gamepad.XBOX; }
  62824. for (var _i = 0, _a = this._babylonGamepads; _i < _a.length; _i++) {
  62825. var gamepad = _a[_i];
  62826. if (gamepad && gamepad.type === type) {
  62827. return gamepad;
  62828. }
  62829. }
  62830. return null;
  62831. };
  62832. GamepadManager.prototype.dispose = function () {
  62833. if (this._gamepadEventSupported) {
  62834. if (this._onGamepadConnectedEvent) {
  62835. window.removeEventListener('gamepadconnected', this._onGamepadConnectedEvent);
  62836. }
  62837. if (this._onGamepadDisconnectedEvent) {
  62838. window.removeEventListener('gamepaddisconnected', this._onGamepadDisconnectedEvent);
  62839. }
  62840. this._onGamepadConnectedEvent = null;
  62841. this._onGamepadDisconnectedEvent = null;
  62842. }
  62843. this._babylonGamepads.forEach(function (gamepad) {
  62844. gamepad.dispose();
  62845. });
  62846. this.onGamepadConnectedObservable.clear();
  62847. this.onGamepadDisconnectedObservable.clear();
  62848. this._oneGamepadConnected = false;
  62849. this._stopMonitoringGamepads();
  62850. this._babylonGamepads = [];
  62851. };
  62852. GamepadManager.prototype._addNewGamepad = function (gamepad) {
  62853. if (!this._oneGamepadConnected) {
  62854. this._oneGamepadConnected = true;
  62855. }
  62856. var newGamepad;
  62857. var xboxOne = (gamepad.id.search("Xbox One") !== -1);
  62858. if (xboxOne || gamepad.id.search("Xbox 360") !== -1 || gamepad.id.search("xinput") !== -1) {
  62859. newGamepad = new BABYLON.Xbox360Pad(gamepad.id, gamepad.index, gamepad, xboxOne);
  62860. }
  62861. else if (gamepad.pose) {
  62862. newGamepad = BABYLON.PoseEnabledControllerHelper.InitiateController(gamepad);
  62863. }
  62864. else {
  62865. newGamepad = new BABYLON.GenericPad(gamepad.id, gamepad.index, gamepad);
  62866. }
  62867. this._babylonGamepads[newGamepad.index] = newGamepad;
  62868. return newGamepad;
  62869. };
  62870. GamepadManager.prototype._startMonitoringGamepads = function () {
  62871. if (!this._isMonitoring) {
  62872. this._isMonitoring = true;
  62873. //back-comp
  62874. if (!this._scene) {
  62875. this._checkGamepadsStatus();
  62876. }
  62877. }
  62878. };
  62879. GamepadManager.prototype._stopMonitoringGamepads = function () {
  62880. this._isMonitoring = false;
  62881. };
  62882. GamepadManager.prototype._checkGamepadsStatus = function () {
  62883. var _this = this;
  62884. // Hack to be compatible Chrome
  62885. this._updateGamepadObjects();
  62886. for (var i in this._babylonGamepads) {
  62887. var gamepad = this._babylonGamepads[i];
  62888. if (!gamepad || !gamepad.isConnected) {
  62889. continue;
  62890. }
  62891. gamepad.update();
  62892. }
  62893. if (this._isMonitoring && !this._scene) {
  62894. BABYLON.Tools.QueueNewFrame(function () { _this._checkGamepadsStatus(); });
  62895. }
  62896. };
  62897. // This function is called only on Chrome, which does not properly support
  62898. // connection/disconnection events and forces you to recopy again the gamepad object
  62899. GamepadManager.prototype._updateGamepadObjects = function () {
  62900. var gamepads = navigator.getGamepads ? navigator.getGamepads() : (navigator.webkitGetGamepads ? navigator.webkitGetGamepads() : []);
  62901. for (var i = 0; i < gamepads.length; i++) {
  62902. if (gamepads[i]) {
  62903. if (!this._babylonGamepads[gamepads[i].index]) {
  62904. var newGamepad = this._addNewGamepad(gamepads[i]);
  62905. this.onGamepadConnectedObservable.notifyObservers(newGamepad);
  62906. }
  62907. else {
  62908. // Forced to copy again this object for Chrome for unknown reason
  62909. this._babylonGamepads[i].browserGamepad = gamepads[i];
  62910. if (!this._babylonGamepads[i].isConnected) {
  62911. this._babylonGamepads[i]._isConnected = true;
  62912. this.onGamepadConnectedObservable.notifyObservers(this._babylonGamepads[i]);
  62913. }
  62914. }
  62915. }
  62916. }
  62917. };
  62918. return GamepadManager;
  62919. }());
  62920. BABYLON.GamepadManager = GamepadManager;
  62921. })(BABYLON || (BABYLON = {}));
  62922. //# sourceMappingURL=babylon.gamepadManager.js.map
  62923. var BABYLON;
  62924. (function (BABYLON) {
  62925. var StickValues = /** @class */ (function () {
  62926. function StickValues(x, y) {
  62927. this.x = x;
  62928. this.y = y;
  62929. }
  62930. return StickValues;
  62931. }());
  62932. BABYLON.StickValues = StickValues;
  62933. var Gamepad = /** @class */ (function () {
  62934. function Gamepad(id, index, browserGamepad, leftStickX, leftStickY, rightStickX, rightStickY) {
  62935. if (leftStickX === void 0) { leftStickX = 0; }
  62936. if (leftStickY === void 0) { leftStickY = 1; }
  62937. if (rightStickX === void 0) { rightStickX = 2; }
  62938. if (rightStickY === void 0) { rightStickY = 3; }
  62939. this.id = id;
  62940. this.index = index;
  62941. this.browserGamepad = browserGamepad;
  62942. this._isConnected = true;
  62943. this._invertLeftStickY = false;
  62944. this.type = Gamepad.GAMEPAD;
  62945. this._leftStickAxisX = leftStickX;
  62946. this._leftStickAxisY = leftStickY;
  62947. this._rightStickAxisX = rightStickX;
  62948. this._rightStickAxisY = rightStickY;
  62949. if (this.browserGamepad.axes.length >= 2) {
  62950. this._leftStick = { x: this.browserGamepad.axes[this._leftStickAxisX], y: this.browserGamepad.axes[this._leftStickAxisY] };
  62951. }
  62952. if (this.browserGamepad.axes.length >= 4) {
  62953. this._rightStick = { x: this.browserGamepad.axes[this._rightStickAxisX], y: this.browserGamepad.axes[this._rightStickAxisY] };
  62954. }
  62955. }
  62956. Object.defineProperty(Gamepad.prototype, "isConnected", {
  62957. get: function () {
  62958. return this._isConnected;
  62959. },
  62960. enumerable: true,
  62961. configurable: true
  62962. });
  62963. Gamepad.prototype.onleftstickchanged = function (callback) {
  62964. this._onleftstickchanged = callback;
  62965. };
  62966. Gamepad.prototype.onrightstickchanged = function (callback) {
  62967. this._onrightstickchanged = callback;
  62968. };
  62969. Object.defineProperty(Gamepad.prototype, "leftStick", {
  62970. get: function () {
  62971. return this._leftStick;
  62972. },
  62973. set: function (newValues) {
  62974. if (this._onleftstickchanged && (this._leftStick.x !== newValues.x || this._leftStick.y !== newValues.y)) {
  62975. this._onleftstickchanged(newValues);
  62976. }
  62977. this._leftStick = newValues;
  62978. },
  62979. enumerable: true,
  62980. configurable: true
  62981. });
  62982. Object.defineProperty(Gamepad.prototype, "rightStick", {
  62983. get: function () {
  62984. return this._rightStick;
  62985. },
  62986. set: function (newValues) {
  62987. if (this._onrightstickchanged && (this._rightStick.x !== newValues.x || this._rightStick.y !== newValues.y)) {
  62988. this._onrightstickchanged(newValues);
  62989. }
  62990. this._rightStick = newValues;
  62991. },
  62992. enumerable: true,
  62993. configurable: true
  62994. });
  62995. Gamepad.prototype.update = function () {
  62996. if (this._leftStick) {
  62997. this.leftStick = { x: this.browserGamepad.axes[this._leftStickAxisX], y: this.browserGamepad.axes[this._leftStickAxisY] };
  62998. if (this._invertLeftStickY) {
  62999. this.leftStick.y *= -1;
  63000. }
  63001. }
  63002. if (this._rightStick) {
  63003. this.rightStick = { x: this.browserGamepad.axes[this._rightStickAxisX], y: this.browserGamepad.axes[this._rightStickAxisY] };
  63004. }
  63005. };
  63006. Gamepad.prototype.dispose = function () {
  63007. };
  63008. Gamepad.GAMEPAD = 0;
  63009. Gamepad.GENERIC = 1;
  63010. Gamepad.XBOX = 2;
  63011. Gamepad.POSE_ENABLED = 3;
  63012. return Gamepad;
  63013. }());
  63014. BABYLON.Gamepad = Gamepad;
  63015. var GenericPad = /** @class */ (function (_super) {
  63016. __extends(GenericPad, _super);
  63017. function GenericPad(id, index, browserGamepad) {
  63018. var _this = _super.call(this, id, index, browserGamepad) || this;
  63019. _this.onButtonDownObservable = new BABYLON.Observable();
  63020. _this.onButtonUpObservable = new BABYLON.Observable();
  63021. _this.type = Gamepad.GENERIC;
  63022. _this._buttons = new Array(browserGamepad.buttons.length);
  63023. return _this;
  63024. }
  63025. GenericPad.prototype.onbuttondown = function (callback) {
  63026. this._onbuttondown = callback;
  63027. };
  63028. GenericPad.prototype.onbuttonup = function (callback) {
  63029. this._onbuttonup = callback;
  63030. };
  63031. GenericPad.prototype._setButtonValue = function (newValue, currentValue, buttonIndex) {
  63032. if (newValue !== currentValue) {
  63033. if (newValue === 1) {
  63034. if (this._onbuttondown) {
  63035. this._onbuttondown(buttonIndex);
  63036. }
  63037. this.onButtonDownObservable.notifyObservers(buttonIndex);
  63038. }
  63039. if (newValue === 0) {
  63040. if (this._onbuttonup) {
  63041. this._onbuttonup(buttonIndex);
  63042. }
  63043. this.onButtonUpObservable.notifyObservers(buttonIndex);
  63044. }
  63045. }
  63046. return newValue;
  63047. };
  63048. GenericPad.prototype.update = function () {
  63049. _super.prototype.update.call(this);
  63050. for (var index = 0; index < this._buttons.length; index++) {
  63051. this._buttons[index] = this._setButtonValue(this.browserGamepad.buttons[index].value, this._buttons[index], index);
  63052. }
  63053. };
  63054. GenericPad.prototype.dispose = function () {
  63055. _super.prototype.dispose.call(this);
  63056. this.onButtonDownObservable.clear();
  63057. this.onButtonUpObservable.clear();
  63058. };
  63059. return GenericPad;
  63060. }(Gamepad));
  63061. BABYLON.GenericPad = GenericPad;
  63062. })(BABYLON || (BABYLON = {}));
  63063. //# sourceMappingURL=babylon.gamepad.js.map
  63064. var BABYLON;
  63065. (function (BABYLON) {
  63066. var Xbox360Button;
  63067. (function (Xbox360Button) {
  63068. Xbox360Button[Xbox360Button["A"] = 0] = "A";
  63069. Xbox360Button[Xbox360Button["B"] = 1] = "B";
  63070. Xbox360Button[Xbox360Button["X"] = 2] = "X";
  63071. Xbox360Button[Xbox360Button["Y"] = 3] = "Y";
  63072. Xbox360Button[Xbox360Button["Start"] = 4] = "Start";
  63073. Xbox360Button[Xbox360Button["Back"] = 5] = "Back";
  63074. Xbox360Button[Xbox360Button["LB"] = 6] = "LB";
  63075. Xbox360Button[Xbox360Button["RB"] = 7] = "RB";
  63076. Xbox360Button[Xbox360Button["LeftStick"] = 8] = "LeftStick";
  63077. Xbox360Button[Xbox360Button["RightStick"] = 9] = "RightStick";
  63078. })(Xbox360Button = BABYLON.Xbox360Button || (BABYLON.Xbox360Button = {}));
  63079. var Xbox360Dpad;
  63080. (function (Xbox360Dpad) {
  63081. Xbox360Dpad[Xbox360Dpad["Up"] = 0] = "Up";
  63082. Xbox360Dpad[Xbox360Dpad["Down"] = 1] = "Down";
  63083. Xbox360Dpad[Xbox360Dpad["Left"] = 2] = "Left";
  63084. Xbox360Dpad[Xbox360Dpad["Right"] = 3] = "Right";
  63085. })(Xbox360Dpad = BABYLON.Xbox360Dpad || (BABYLON.Xbox360Dpad = {}));
  63086. var Xbox360Pad = /** @class */ (function (_super) {
  63087. __extends(Xbox360Pad, _super);
  63088. function Xbox360Pad(id, index, gamepad, xboxOne) {
  63089. if (xboxOne === void 0) { xboxOne = false; }
  63090. var _this = _super.call(this, id, index, gamepad, 0, 1, 2, 3) || this;
  63091. _this._leftTrigger = 0;
  63092. _this._rightTrigger = 0;
  63093. _this.onButtonDownObservable = new BABYLON.Observable();
  63094. _this.onButtonUpObservable = new BABYLON.Observable();
  63095. _this.onPadDownObservable = new BABYLON.Observable();
  63096. _this.onPadUpObservable = new BABYLON.Observable();
  63097. _this._buttonA = 0;
  63098. _this._buttonB = 0;
  63099. _this._buttonX = 0;
  63100. _this._buttonY = 0;
  63101. _this._buttonBack = 0;
  63102. _this._buttonStart = 0;
  63103. _this._buttonLB = 0;
  63104. _this._buttonRB = 0;
  63105. _this._buttonLeftStick = 0;
  63106. _this._buttonRightStick = 0;
  63107. _this._dPadUp = 0;
  63108. _this._dPadDown = 0;
  63109. _this._dPadLeft = 0;
  63110. _this._dPadRight = 0;
  63111. _this._isXboxOnePad = false;
  63112. _this.type = BABYLON.Gamepad.XBOX;
  63113. _this._isXboxOnePad = xboxOne;
  63114. return _this;
  63115. }
  63116. Xbox360Pad.prototype.onlefttriggerchanged = function (callback) {
  63117. this._onlefttriggerchanged = callback;
  63118. };
  63119. Xbox360Pad.prototype.onrighttriggerchanged = function (callback) {
  63120. this._onrighttriggerchanged = callback;
  63121. };
  63122. Object.defineProperty(Xbox360Pad.prototype, "leftTrigger", {
  63123. get: function () {
  63124. return this._leftTrigger;
  63125. },
  63126. set: function (newValue) {
  63127. if (this._onlefttriggerchanged && this._leftTrigger !== newValue) {
  63128. this._onlefttriggerchanged(newValue);
  63129. }
  63130. this._leftTrigger = newValue;
  63131. },
  63132. enumerable: true,
  63133. configurable: true
  63134. });
  63135. Object.defineProperty(Xbox360Pad.prototype, "rightTrigger", {
  63136. get: function () {
  63137. return this._rightTrigger;
  63138. },
  63139. set: function (newValue) {
  63140. if (this._onrighttriggerchanged && this._rightTrigger !== newValue) {
  63141. this._onrighttriggerchanged(newValue);
  63142. }
  63143. this._rightTrigger = newValue;
  63144. },
  63145. enumerable: true,
  63146. configurable: true
  63147. });
  63148. Xbox360Pad.prototype.onbuttondown = function (callback) {
  63149. this._onbuttondown = callback;
  63150. };
  63151. Xbox360Pad.prototype.onbuttonup = function (callback) {
  63152. this._onbuttonup = callback;
  63153. };
  63154. Xbox360Pad.prototype.ondpaddown = function (callback) {
  63155. this._ondpaddown = callback;
  63156. };
  63157. Xbox360Pad.prototype.ondpadup = function (callback) {
  63158. this._ondpadup = callback;
  63159. };
  63160. Xbox360Pad.prototype._setButtonValue = function (newValue, currentValue, buttonType) {
  63161. if (newValue !== currentValue) {
  63162. if (newValue === 1) {
  63163. if (this._onbuttondown) {
  63164. this._onbuttondown(buttonType);
  63165. }
  63166. this.onButtonDownObservable.notifyObservers(buttonType);
  63167. }
  63168. if (newValue === 0) {
  63169. if (this._onbuttonup) {
  63170. this._onbuttonup(buttonType);
  63171. }
  63172. this.onButtonUpObservable.notifyObservers(buttonType);
  63173. }
  63174. }
  63175. return newValue;
  63176. };
  63177. Xbox360Pad.prototype._setDPadValue = function (newValue, currentValue, buttonType) {
  63178. if (newValue !== currentValue) {
  63179. if (newValue === 1) {
  63180. if (this._ondpaddown) {
  63181. this._ondpaddown(buttonType);
  63182. }
  63183. this.onPadDownObservable.notifyObservers(buttonType);
  63184. }
  63185. if (newValue === 0) {
  63186. if (this._ondpadup) {
  63187. this._ondpadup(buttonType);
  63188. }
  63189. this.onPadUpObservable.notifyObservers(buttonType);
  63190. }
  63191. }
  63192. return newValue;
  63193. };
  63194. Object.defineProperty(Xbox360Pad.prototype, "buttonA", {
  63195. get: function () {
  63196. return this._buttonA;
  63197. },
  63198. set: function (value) {
  63199. this._buttonA = this._setButtonValue(value, this._buttonA, Xbox360Button.A);
  63200. },
  63201. enumerable: true,
  63202. configurable: true
  63203. });
  63204. Object.defineProperty(Xbox360Pad.prototype, "buttonB", {
  63205. get: function () {
  63206. return this._buttonB;
  63207. },
  63208. set: function (value) {
  63209. this._buttonB = this._setButtonValue(value, this._buttonB, Xbox360Button.B);
  63210. },
  63211. enumerable: true,
  63212. configurable: true
  63213. });
  63214. Object.defineProperty(Xbox360Pad.prototype, "buttonX", {
  63215. get: function () {
  63216. return this._buttonX;
  63217. },
  63218. set: function (value) {
  63219. this._buttonX = this._setButtonValue(value, this._buttonX, Xbox360Button.X);
  63220. },
  63221. enumerable: true,
  63222. configurable: true
  63223. });
  63224. Object.defineProperty(Xbox360Pad.prototype, "buttonY", {
  63225. get: function () {
  63226. return this._buttonY;
  63227. },
  63228. set: function (value) {
  63229. this._buttonY = this._setButtonValue(value, this._buttonY, Xbox360Button.Y);
  63230. },
  63231. enumerable: true,
  63232. configurable: true
  63233. });
  63234. Object.defineProperty(Xbox360Pad.prototype, "buttonStart", {
  63235. get: function () {
  63236. return this._buttonStart;
  63237. },
  63238. set: function (value) {
  63239. this._buttonStart = this._setButtonValue(value, this._buttonStart, Xbox360Button.Start);
  63240. },
  63241. enumerable: true,
  63242. configurable: true
  63243. });
  63244. Object.defineProperty(Xbox360Pad.prototype, "buttonBack", {
  63245. get: function () {
  63246. return this._buttonBack;
  63247. },
  63248. set: function (value) {
  63249. this._buttonBack = this._setButtonValue(value, this._buttonBack, Xbox360Button.Back);
  63250. },
  63251. enumerable: true,
  63252. configurable: true
  63253. });
  63254. Object.defineProperty(Xbox360Pad.prototype, "buttonLB", {
  63255. get: function () {
  63256. return this._buttonLB;
  63257. },
  63258. set: function (value) {
  63259. this._buttonLB = this._setButtonValue(value, this._buttonLB, Xbox360Button.LB);
  63260. },
  63261. enumerable: true,
  63262. configurable: true
  63263. });
  63264. Object.defineProperty(Xbox360Pad.prototype, "buttonRB", {
  63265. get: function () {
  63266. return this._buttonRB;
  63267. },
  63268. set: function (value) {
  63269. this._buttonRB = this._setButtonValue(value, this._buttonRB, Xbox360Button.RB);
  63270. },
  63271. enumerable: true,
  63272. configurable: true
  63273. });
  63274. Object.defineProperty(Xbox360Pad.prototype, "buttonLeftStick", {
  63275. get: function () {
  63276. return this._buttonLeftStick;
  63277. },
  63278. set: function (value) {
  63279. this._buttonLeftStick = this._setButtonValue(value, this._buttonLeftStick, Xbox360Button.LeftStick);
  63280. },
  63281. enumerable: true,
  63282. configurable: true
  63283. });
  63284. Object.defineProperty(Xbox360Pad.prototype, "buttonRightStick", {
  63285. get: function () {
  63286. return this._buttonRightStick;
  63287. },
  63288. set: function (value) {
  63289. this._buttonRightStick = this._setButtonValue(value, this._buttonRightStick, Xbox360Button.RightStick);
  63290. },
  63291. enumerable: true,
  63292. configurable: true
  63293. });
  63294. Object.defineProperty(Xbox360Pad.prototype, "dPadUp", {
  63295. get: function () {
  63296. return this._dPadUp;
  63297. },
  63298. set: function (value) {
  63299. this._dPadUp = this._setDPadValue(value, this._dPadUp, Xbox360Dpad.Up);
  63300. },
  63301. enumerable: true,
  63302. configurable: true
  63303. });
  63304. Object.defineProperty(Xbox360Pad.prototype, "dPadDown", {
  63305. get: function () {
  63306. return this._dPadDown;
  63307. },
  63308. set: function (value) {
  63309. this._dPadDown = this._setDPadValue(value, this._dPadDown, Xbox360Dpad.Down);
  63310. },
  63311. enumerable: true,
  63312. configurable: true
  63313. });
  63314. Object.defineProperty(Xbox360Pad.prototype, "dPadLeft", {
  63315. get: function () {
  63316. return this._dPadLeft;
  63317. },
  63318. set: function (value) {
  63319. this._dPadLeft = this._setDPadValue(value, this._dPadLeft, Xbox360Dpad.Left);
  63320. },
  63321. enumerable: true,
  63322. configurable: true
  63323. });
  63324. Object.defineProperty(Xbox360Pad.prototype, "dPadRight", {
  63325. get: function () {
  63326. return this._dPadRight;
  63327. },
  63328. set: function (value) {
  63329. this._dPadRight = this._setDPadValue(value, this._dPadRight, Xbox360Dpad.Right);
  63330. },
  63331. enumerable: true,
  63332. configurable: true
  63333. });
  63334. Xbox360Pad.prototype.update = function () {
  63335. _super.prototype.update.call(this);
  63336. if (this._isXboxOnePad) {
  63337. this.buttonA = this.browserGamepad.buttons[0].value;
  63338. this.buttonB = this.browserGamepad.buttons[1].value;
  63339. this.buttonX = this.browserGamepad.buttons[2].value;
  63340. this.buttonY = this.browserGamepad.buttons[3].value;
  63341. this.buttonLB = this.browserGamepad.buttons[4].value;
  63342. this.buttonRB = this.browserGamepad.buttons[5].value;
  63343. this.leftTrigger = this.browserGamepad.axes[2];
  63344. this.rightTrigger = this.browserGamepad.axes[5];
  63345. this.buttonBack = this.browserGamepad.buttons[9].value;
  63346. this.buttonStart = this.browserGamepad.buttons[8].value;
  63347. this.buttonLeftStick = this.browserGamepad.buttons[6].value;
  63348. this.buttonRightStick = this.browserGamepad.buttons[7].value;
  63349. this.dPadUp = this.browserGamepad.buttons[11].value;
  63350. this.dPadDown = this.browserGamepad.buttons[12].value;
  63351. this.dPadLeft = this.browserGamepad.buttons[13].value;
  63352. this.dPadRight = this.browserGamepad.buttons[14].value;
  63353. }
  63354. else {
  63355. this.buttonA = this.browserGamepad.buttons[0].value;
  63356. this.buttonB = this.browserGamepad.buttons[1].value;
  63357. this.buttonX = this.browserGamepad.buttons[2].value;
  63358. this.buttonY = this.browserGamepad.buttons[3].value;
  63359. this.buttonLB = this.browserGamepad.buttons[4].value;
  63360. this.buttonRB = this.browserGamepad.buttons[5].value;
  63361. this.leftTrigger = this.browserGamepad.buttons[6].value;
  63362. this.rightTrigger = this.browserGamepad.buttons[7].value;
  63363. this.buttonBack = this.browserGamepad.buttons[8].value;
  63364. this.buttonStart = this.browserGamepad.buttons[9].value;
  63365. this.buttonLeftStick = this.browserGamepad.buttons[10].value;
  63366. this.buttonRightStick = this.browserGamepad.buttons[11].value;
  63367. this.dPadUp = this.browserGamepad.buttons[12].value;
  63368. this.dPadDown = this.browserGamepad.buttons[13].value;
  63369. this.dPadLeft = this.browserGamepad.buttons[14].value;
  63370. this.dPadRight = this.browserGamepad.buttons[15].value;
  63371. }
  63372. };
  63373. Xbox360Pad.prototype.dispose = function () {
  63374. _super.prototype.dispose.call(this);
  63375. this.onButtonDownObservable.clear();
  63376. this.onButtonUpObservable.clear();
  63377. this.onPadDownObservable.clear();
  63378. this.onPadUpObservable.clear();
  63379. };
  63380. return Xbox360Pad;
  63381. }(BABYLON.Gamepad));
  63382. BABYLON.Xbox360Pad = Xbox360Pad;
  63383. })(BABYLON || (BABYLON = {}));
  63384. //# sourceMappingURL=babylon.xboxGamepad.js.map
  63385. var BABYLON;
  63386. (function (BABYLON) {
  63387. var PoseEnabledControllerType;
  63388. (function (PoseEnabledControllerType) {
  63389. PoseEnabledControllerType[PoseEnabledControllerType["VIVE"] = 0] = "VIVE";
  63390. PoseEnabledControllerType[PoseEnabledControllerType["OCULUS"] = 1] = "OCULUS";
  63391. PoseEnabledControllerType[PoseEnabledControllerType["WINDOWS"] = 2] = "WINDOWS";
  63392. PoseEnabledControllerType[PoseEnabledControllerType["GEAR_VR"] = 3] = "GEAR_VR";
  63393. PoseEnabledControllerType[PoseEnabledControllerType["GENERIC"] = 4] = "GENERIC";
  63394. })(PoseEnabledControllerType = BABYLON.PoseEnabledControllerType || (BABYLON.PoseEnabledControllerType = {}));
  63395. var PoseEnabledControllerHelper = /** @class */ (function () {
  63396. function PoseEnabledControllerHelper() {
  63397. }
  63398. PoseEnabledControllerHelper.InitiateController = function (vrGamepad) {
  63399. // Oculus Touch
  63400. if (vrGamepad.id.indexOf('Oculus Touch') !== -1) {
  63401. return new BABYLON.OculusTouchController(vrGamepad);
  63402. }
  63403. else if (vrGamepad.id.indexOf(BABYLON.WindowsMotionController.GAMEPAD_ID_PREFIX) === 0) {
  63404. return new BABYLON.WindowsMotionController(vrGamepad);
  63405. }
  63406. else if (vrGamepad.id.toLowerCase().indexOf('openvr') !== -1) {
  63407. return new BABYLON.ViveController(vrGamepad);
  63408. }
  63409. else if (vrGamepad.id.indexOf(BABYLON.GearVRController.GAMEPAD_ID_PREFIX) === 0) {
  63410. return new BABYLON.GearVRController(vrGamepad);
  63411. }
  63412. else {
  63413. return new BABYLON.GenericController(vrGamepad);
  63414. }
  63415. };
  63416. return PoseEnabledControllerHelper;
  63417. }());
  63418. BABYLON.PoseEnabledControllerHelper = PoseEnabledControllerHelper;
  63419. var PoseEnabledController = /** @class */ (function (_super) {
  63420. __extends(PoseEnabledController, _super);
  63421. function PoseEnabledController(browserGamepad) {
  63422. var _this = _super.call(this, browserGamepad.id, browserGamepad.index, browserGamepad) || this;
  63423. // Represents device position and rotation in room space. Should only be used to help calculate babylon space values
  63424. _this._deviceRoomPosition = BABYLON.Vector3.Zero();
  63425. _this._deviceRoomRotationQuaternion = new BABYLON.Quaternion();
  63426. // Represents device position and rotation in babylon space
  63427. _this.devicePosition = BABYLON.Vector3.Zero();
  63428. _this.deviceRotationQuaternion = new BABYLON.Quaternion();
  63429. _this.deviceScaleFactor = 1;
  63430. _this._leftHandSystemQuaternion = new BABYLON.Quaternion();
  63431. _this._deviceToWorld = BABYLON.Matrix.Identity();
  63432. _this._workingMatrix = BABYLON.Matrix.Identity();
  63433. _this.type = BABYLON.Gamepad.POSE_ENABLED;
  63434. _this.controllerType = PoseEnabledControllerType.GENERIC;
  63435. _this.position = BABYLON.Vector3.Zero();
  63436. _this.rotationQuaternion = new BABYLON.Quaternion();
  63437. _this._calculatedPosition = BABYLON.Vector3.Zero();
  63438. _this._calculatedRotation = new BABYLON.Quaternion();
  63439. BABYLON.Quaternion.RotationYawPitchRollToRef(Math.PI, 0, 0, _this._leftHandSystemQuaternion);
  63440. return _this;
  63441. }
  63442. PoseEnabledController.prototype.update = function () {
  63443. _super.prototype.update.call(this);
  63444. var pose = this.browserGamepad.pose;
  63445. this.updateFromDevice(pose);
  63446. BABYLON.Vector3.TransformCoordinatesToRef(this._calculatedPosition, this._deviceToWorld, this.devicePosition);
  63447. this._deviceToWorld.getRotationMatrixToRef(this._workingMatrix);
  63448. BABYLON.Quaternion.FromRotationMatrixToRef(this._workingMatrix, this.deviceRotationQuaternion);
  63449. this.deviceRotationQuaternion.multiplyInPlace(this._calculatedRotation);
  63450. if (this._mesh) {
  63451. this._mesh.position.copyFrom(this.devicePosition);
  63452. if (this._mesh.rotationQuaternion) {
  63453. this._mesh.rotationQuaternion.copyFrom(this.deviceRotationQuaternion);
  63454. }
  63455. }
  63456. };
  63457. PoseEnabledController.prototype.updateFromDevice = function (poseData) {
  63458. if (poseData) {
  63459. this.rawPose = poseData;
  63460. if (poseData.position) {
  63461. this._deviceRoomPosition.copyFromFloats(poseData.position[0], poseData.position[1], -poseData.position[2]);
  63462. if (this._mesh && this._mesh.getScene().useRightHandedSystem) {
  63463. this._deviceRoomPosition.z *= -1;
  63464. }
  63465. this._deviceRoomPosition.scaleToRef(this.deviceScaleFactor, this._calculatedPosition);
  63466. this._calculatedPosition.addInPlace(this.position);
  63467. }
  63468. var pose = this.rawPose;
  63469. if (poseData.orientation && pose.orientation) {
  63470. this._deviceRoomRotationQuaternion.copyFromFloats(pose.orientation[0], pose.orientation[1], -pose.orientation[2], -pose.orientation[3]);
  63471. if (this._mesh) {
  63472. if (this._mesh.getScene().useRightHandedSystem) {
  63473. this._deviceRoomRotationQuaternion.z *= -1;
  63474. this._deviceRoomRotationQuaternion.w *= -1;
  63475. }
  63476. else {
  63477. this._deviceRoomRotationQuaternion.multiplyToRef(this._leftHandSystemQuaternion, this._deviceRoomRotationQuaternion);
  63478. }
  63479. }
  63480. // if the camera is set, rotate to the camera's rotation
  63481. this._deviceRoomRotationQuaternion.multiplyToRef(this.rotationQuaternion, this._calculatedRotation);
  63482. }
  63483. }
  63484. };
  63485. PoseEnabledController.prototype.attachToMesh = function (mesh) {
  63486. if (this._mesh) {
  63487. this._mesh.parent = null;
  63488. }
  63489. this._mesh = mesh;
  63490. if (this._poseControlledCamera) {
  63491. this._mesh.parent = this._poseControlledCamera;
  63492. }
  63493. if (!this._mesh.rotationQuaternion) {
  63494. this._mesh.rotationQuaternion = new BABYLON.Quaternion();
  63495. }
  63496. };
  63497. PoseEnabledController.prototype.attachToPoseControlledCamera = function (camera) {
  63498. this._poseControlledCamera = camera;
  63499. if (this._mesh) {
  63500. this._mesh.parent = this._poseControlledCamera;
  63501. }
  63502. };
  63503. PoseEnabledController.prototype.dispose = function () {
  63504. if (this._mesh) {
  63505. this._mesh.dispose();
  63506. }
  63507. this._mesh = null;
  63508. _super.prototype.dispose.call(this);
  63509. };
  63510. Object.defineProperty(PoseEnabledController.prototype, "mesh", {
  63511. get: function () {
  63512. return this._mesh;
  63513. },
  63514. enumerable: true,
  63515. configurable: true
  63516. });
  63517. PoseEnabledController.prototype.getForwardRay = function (length) {
  63518. if (length === void 0) { length = 100; }
  63519. if (!this.mesh) {
  63520. return new BABYLON.Ray(BABYLON.Vector3.Zero(), new BABYLON.Vector3(0, 0, 1), length);
  63521. }
  63522. var m = this.mesh.getWorldMatrix();
  63523. var origin = m.getTranslation();
  63524. var forward = new BABYLON.Vector3(0, 0, -1);
  63525. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, m);
  63526. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  63527. return new BABYLON.Ray(origin, direction, length);
  63528. };
  63529. return PoseEnabledController;
  63530. }(BABYLON.Gamepad));
  63531. BABYLON.PoseEnabledController = PoseEnabledController;
  63532. })(BABYLON || (BABYLON = {}));
  63533. //# sourceMappingURL=babylon.poseEnabledController.js.map
  63534. var BABYLON;
  63535. (function (BABYLON) {
  63536. var WebVRController = /** @class */ (function (_super) {
  63537. __extends(WebVRController, _super);
  63538. function WebVRController(vrGamepad) {
  63539. var _this = _super.call(this, vrGamepad) || this;
  63540. // Observables
  63541. _this.onTriggerStateChangedObservable = new BABYLON.Observable();
  63542. _this.onMainButtonStateChangedObservable = new BABYLON.Observable();
  63543. _this.onSecondaryButtonStateChangedObservable = new BABYLON.Observable();
  63544. _this.onPadStateChangedObservable = new BABYLON.Observable();
  63545. _this.onPadValuesChangedObservable = new BABYLON.Observable();
  63546. _this.pad = { x: 0, y: 0 };
  63547. // avoid GC, store state in a tmp object
  63548. _this._changes = {
  63549. pressChanged: false,
  63550. touchChanged: false,
  63551. valueChanged: false,
  63552. changed: false
  63553. };
  63554. _this._buttons = new Array(vrGamepad.buttons.length);
  63555. _this.hand = vrGamepad.hand;
  63556. return _this;
  63557. }
  63558. WebVRController.prototype.onButtonStateChange = function (callback) {
  63559. this._onButtonStateChange = callback;
  63560. };
  63561. Object.defineProperty(WebVRController.prototype, "defaultModel", {
  63562. get: function () {
  63563. return this._defaultModel;
  63564. },
  63565. enumerable: true,
  63566. configurable: true
  63567. });
  63568. WebVRController.prototype.update = function () {
  63569. _super.prototype.update.call(this);
  63570. for (var index = 0; index < this._buttons.length; index++) {
  63571. this._setButtonValue(this.browserGamepad.buttons[index], this._buttons[index], index);
  63572. }
  63573. ;
  63574. if (this.leftStick.x !== this.pad.x || this.leftStick.y !== this.pad.y) {
  63575. this.pad.x = this.leftStick.x;
  63576. this.pad.y = this.leftStick.y;
  63577. this.onPadValuesChangedObservable.notifyObservers(this.pad);
  63578. }
  63579. };
  63580. WebVRController.prototype._setButtonValue = function (newState, currentState, buttonIndex) {
  63581. if (!newState) {
  63582. newState = {
  63583. pressed: false,
  63584. touched: false,
  63585. value: 0
  63586. };
  63587. }
  63588. if (!currentState) {
  63589. this._buttons[buttonIndex] = {
  63590. pressed: newState.pressed,
  63591. touched: newState.touched,
  63592. value: newState.value
  63593. };
  63594. return;
  63595. }
  63596. this._checkChanges(newState, currentState);
  63597. if (this._changes.changed) {
  63598. this._onButtonStateChange && this._onButtonStateChange(this.index, buttonIndex, newState);
  63599. this.handleButtonChange(buttonIndex, newState, this._changes);
  63600. }
  63601. this._buttons[buttonIndex].pressed = newState.pressed;
  63602. this._buttons[buttonIndex].touched = newState.touched;
  63603. // oculus triggers are never 0, thou not touched.
  63604. this._buttons[buttonIndex].value = newState.value < 0.00000001 ? 0 : newState.value;
  63605. };
  63606. WebVRController.prototype._checkChanges = function (newState, currentState) {
  63607. this._changes.pressChanged = newState.pressed !== currentState.pressed;
  63608. this._changes.touchChanged = newState.touched !== currentState.touched;
  63609. this._changes.valueChanged = newState.value !== currentState.value;
  63610. this._changes.changed = this._changes.pressChanged || this._changes.touchChanged || this._changes.valueChanged;
  63611. return this._changes;
  63612. };
  63613. WebVRController.prototype.dispose = function () {
  63614. _super.prototype.dispose.call(this);
  63615. this.onTriggerStateChangedObservable.clear();
  63616. this.onMainButtonStateChangedObservable.clear();
  63617. this.onSecondaryButtonStateChangedObservable.clear();
  63618. this.onPadStateChangedObservable.clear();
  63619. this.onPadValuesChangedObservable.clear();
  63620. };
  63621. return WebVRController;
  63622. }(BABYLON.PoseEnabledController));
  63623. BABYLON.WebVRController = WebVRController;
  63624. })(BABYLON || (BABYLON = {}));
  63625. //# sourceMappingURL=babylon.webVRController.js.map
  63626. var BABYLON;
  63627. (function (BABYLON) {
  63628. var OculusTouchController = /** @class */ (function (_super) {
  63629. __extends(OculusTouchController, _super);
  63630. function OculusTouchController(vrGamepad) {
  63631. var _this = _super.call(this, vrGamepad) || this;
  63632. _this.onSecondaryTriggerStateChangedObservable = new BABYLON.Observable();
  63633. _this.onThumbRestChangedObservable = new BABYLON.Observable();
  63634. _this.controllerType = BABYLON.PoseEnabledControllerType.OCULUS;
  63635. return _this;
  63636. }
  63637. OculusTouchController.prototype.initControllerMesh = function (scene, meshLoaded) {
  63638. var _this = this;
  63639. var meshName;
  63640. // Hand
  63641. if (this.hand === 'left') {
  63642. meshName = OculusTouchController.MODEL_LEFT_FILENAME;
  63643. }
  63644. else {
  63645. meshName = OculusTouchController.MODEL_RIGHT_FILENAME;
  63646. }
  63647. BABYLON.SceneLoader.ImportMesh("", OculusTouchController.MODEL_BASE_URL, meshName, scene, function (newMeshes) {
  63648. /*
  63649. Parent Mesh name: oculus_touch_left
  63650. - body
  63651. - trigger
  63652. - thumbstick
  63653. - grip
  63654. - button_y
  63655. - button_x
  63656. - button_enter
  63657. */
  63658. _this._defaultModel = newMeshes[1];
  63659. _this.attachToMesh(_this._defaultModel);
  63660. if (meshLoaded) {
  63661. meshLoaded(_this._defaultModel);
  63662. }
  63663. });
  63664. };
  63665. Object.defineProperty(OculusTouchController.prototype, "onAButtonStateChangedObservable", {
  63666. // helper getters for left and right hand.
  63667. get: function () {
  63668. if (this.hand === 'right') {
  63669. return this.onMainButtonStateChangedObservable;
  63670. }
  63671. else {
  63672. throw new Error('No A button on left hand');
  63673. }
  63674. },
  63675. enumerable: true,
  63676. configurable: true
  63677. });
  63678. Object.defineProperty(OculusTouchController.prototype, "onBButtonStateChangedObservable", {
  63679. get: function () {
  63680. if (this.hand === 'right') {
  63681. return this.onSecondaryButtonStateChangedObservable;
  63682. }
  63683. else {
  63684. throw new Error('No B button on left hand');
  63685. }
  63686. },
  63687. enumerable: true,
  63688. configurable: true
  63689. });
  63690. Object.defineProperty(OculusTouchController.prototype, "onXButtonStateChangedObservable", {
  63691. get: function () {
  63692. if (this.hand === 'left') {
  63693. return this.onMainButtonStateChangedObservable;
  63694. }
  63695. else {
  63696. throw new Error('No X button on right hand');
  63697. }
  63698. },
  63699. enumerable: true,
  63700. configurable: true
  63701. });
  63702. Object.defineProperty(OculusTouchController.prototype, "onYButtonStateChangedObservable", {
  63703. get: function () {
  63704. if (this.hand === 'left') {
  63705. return this.onSecondaryButtonStateChangedObservable;
  63706. }
  63707. else {
  63708. throw new Error('No Y button on right hand');
  63709. }
  63710. },
  63711. enumerable: true,
  63712. configurable: true
  63713. });
  63714. /*
  63715. 0) thumb stick (touch, press, value = pressed (0,1)). value is in this.leftStick
  63716. 1) index trigger (touch (?), press (only when value > 0.1), value 0 to 1)
  63717. 2) secondary trigger (same)
  63718. 3) A (right) X (left), touch, pressed = value
  63719. 4) B / Y
  63720. 5) thumb rest
  63721. */
  63722. OculusTouchController.prototype.handleButtonChange = function (buttonIdx, state, changes) {
  63723. var notifyObject = state; //{ state: state, changes: changes };
  63724. var triggerDirection = this.hand === 'right' ? -1 : 1;
  63725. switch (buttonIdx) {
  63726. case 0:
  63727. this.onPadStateChangedObservable.notifyObservers(notifyObject);
  63728. return;
  63729. case 1:// index trigger
  63730. if (this._defaultModel) {
  63731. (this._defaultModel.getChildren()[3]).rotation.x = -notifyObject.value * 0.20;
  63732. (this._defaultModel.getChildren()[3]).position.y = -notifyObject.value * 0.005;
  63733. (this._defaultModel.getChildren()[3]).position.z = -notifyObject.value * 0.005;
  63734. }
  63735. this.onTriggerStateChangedObservable.notifyObservers(notifyObject);
  63736. return;
  63737. case 2:// secondary trigger
  63738. if (this._defaultModel) {
  63739. (this._defaultModel.getChildren()[4]).position.x = triggerDirection * notifyObject.value * 0.0035;
  63740. }
  63741. this.onSecondaryTriggerStateChangedObservable.notifyObservers(notifyObject);
  63742. return;
  63743. case 3:
  63744. if (this._defaultModel) {
  63745. if (notifyObject.pressed) {
  63746. (this._defaultModel.getChildren()[1]).position.y = -0.001;
  63747. }
  63748. else {
  63749. (this._defaultModel.getChildren()[1]).position.y = 0;
  63750. }
  63751. }
  63752. this.onMainButtonStateChangedObservable.notifyObservers(notifyObject);
  63753. return;
  63754. case 4:
  63755. if (this._defaultModel) {
  63756. if (notifyObject.pressed) {
  63757. (this._defaultModel.getChildren()[2]).position.y = -0.001;
  63758. }
  63759. else {
  63760. (this._defaultModel.getChildren()[2]).position.y = 0;
  63761. }
  63762. }
  63763. this.onSecondaryButtonStateChangedObservable.notifyObservers(notifyObject);
  63764. return;
  63765. case 5:
  63766. this.onThumbRestChangedObservable.notifyObservers(notifyObject);
  63767. return;
  63768. }
  63769. };
  63770. OculusTouchController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/oculus/';
  63771. OculusTouchController.MODEL_LEFT_FILENAME = 'left.babylon';
  63772. OculusTouchController.MODEL_RIGHT_FILENAME = 'right.babylon';
  63773. return OculusTouchController;
  63774. }(BABYLON.WebVRController));
  63775. BABYLON.OculusTouchController = OculusTouchController;
  63776. })(BABYLON || (BABYLON = {}));
  63777. //# sourceMappingURL=babylon.oculusTouchController.js.map
  63778. var BABYLON;
  63779. (function (BABYLON) {
  63780. var ViveController = /** @class */ (function (_super) {
  63781. __extends(ViveController, _super);
  63782. function ViveController(vrGamepad) {
  63783. var _this = _super.call(this, vrGamepad) || this;
  63784. _this.controllerType = BABYLON.PoseEnabledControllerType.VIVE;
  63785. _this._invertLeftStickY = true;
  63786. return _this;
  63787. }
  63788. ViveController.prototype.initControllerMesh = function (scene, meshLoaded) {
  63789. var _this = this;
  63790. BABYLON.SceneLoader.ImportMesh("", ViveController.MODEL_BASE_URL, ViveController.MODEL_FILENAME, scene, function (newMeshes) {
  63791. /*
  63792. Parent Mesh name: ViveWand
  63793. - body
  63794. - r_gripper
  63795. - l_gripper
  63796. - menu_button
  63797. - system_button
  63798. - trackpad
  63799. - trigger
  63800. - LED
  63801. */
  63802. _this._defaultModel = newMeshes[1];
  63803. _this.attachToMesh(_this._defaultModel);
  63804. if (meshLoaded) {
  63805. meshLoaded(_this._defaultModel);
  63806. }
  63807. });
  63808. };
  63809. Object.defineProperty(ViveController.prototype, "onLeftButtonStateChangedObservable", {
  63810. get: function () {
  63811. return this.onMainButtonStateChangedObservable;
  63812. },
  63813. enumerable: true,
  63814. configurable: true
  63815. });
  63816. Object.defineProperty(ViveController.prototype, "onRightButtonStateChangedObservable", {
  63817. get: function () {
  63818. return this.onMainButtonStateChangedObservable;
  63819. },
  63820. enumerable: true,
  63821. configurable: true
  63822. });
  63823. Object.defineProperty(ViveController.prototype, "onMenuButtonStateChangedObservable", {
  63824. get: function () {
  63825. return this.onSecondaryButtonStateChangedObservable;
  63826. },
  63827. enumerable: true,
  63828. configurable: true
  63829. });
  63830. /**
  63831. * Vive mapping:
  63832. * 0: touchpad
  63833. * 1: trigger
  63834. * 2: left AND right buttons
  63835. * 3: menu button
  63836. */
  63837. ViveController.prototype.handleButtonChange = function (buttonIdx, state, changes) {
  63838. var notifyObject = state; //{ state: state, changes: changes };
  63839. switch (buttonIdx) {
  63840. case 0:
  63841. this.onPadStateChangedObservable.notifyObservers(notifyObject);
  63842. return;
  63843. case 1:// index trigger
  63844. if (this._defaultModel) {
  63845. (this._defaultModel.getChildren()[6]).rotation.x = -notifyObject.value * 0.15;
  63846. }
  63847. this.onTriggerStateChangedObservable.notifyObservers(notifyObject);
  63848. return;
  63849. case 2:// left AND right button
  63850. this.onMainButtonStateChangedObservable.notifyObservers(notifyObject);
  63851. return;
  63852. case 3:
  63853. if (this._defaultModel) {
  63854. if (notifyObject.pressed) {
  63855. (this._defaultModel.getChildren()[2]).position.y = -0.001;
  63856. }
  63857. else {
  63858. (this._defaultModel.getChildren()[2]).position.y = 0;
  63859. }
  63860. }
  63861. this.onSecondaryButtonStateChangedObservable.notifyObservers(notifyObject);
  63862. return;
  63863. }
  63864. };
  63865. ViveController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/vive/';
  63866. ViveController.MODEL_FILENAME = 'wand.babylon';
  63867. return ViveController;
  63868. }(BABYLON.WebVRController));
  63869. BABYLON.ViveController = ViveController;
  63870. })(BABYLON || (BABYLON = {}));
  63871. //# sourceMappingURL=babylon.viveController.js.map
  63872. var BABYLON;
  63873. (function (BABYLON) {
  63874. var GenericController = /** @class */ (function (_super) {
  63875. __extends(GenericController, _super);
  63876. function GenericController(vrGamepad) {
  63877. return _super.call(this, vrGamepad) || this;
  63878. }
  63879. GenericController.prototype.initControllerMesh = function (scene, meshLoaded) {
  63880. var _this = this;
  63881. BABYLON.SceneLoader.ImportMesh("", GenericController.MODEL_BASE_URL, GenericController.MODEL_FILENAME, scene, function (newMeshes) {
  63882. _this._defaultModel = newMeshes[1];
  63883. _this.attachToMesh(_this._defaultModel);
  63884. if (meshLoaded) {
  63885. meshLoaded(_this._defaultModel);
  63886. }
  63887. });
  63888. };
  63889. GenericController.prototype.handleButtonChange = function (buttonIdx, state, changes) {
  63890. console.log("Button id: " + buttonIdx + "state: ");
  63891. console.dir(state);
  63892. };
  63893. GenericController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/generic/';
  63894. GenericController.MODEL_FILENAME = 'generic.babylon';
  63895. return GenericController;
  63896. }(BABYLON.WebVRController));
  63897. BABYLON.GenericController = GenericController;
  63898. })(BABYLON || (BABYLON = {}));
  63899. //# sourceMappingURL=babylon.genericController.js.map
  63900. var BABYLON;
  63901. (function (BABYLON) {
  63902. var LoadedMeshInfo = /** @class */ (function () {
  63903. function LoadedMeshInfo() {
  63904. this.buttonMeshes = {};
  63905. this.axisMeshes = {};
  63906. }
  63907. return LoadedMeshInfo;
  63908. }());
  63909. var WindowsMotionController = /** @class */ (function (_super) {
  63910. __extends(WindowsMotionController, _super);
  63911. function WindowsMotionController(vrGamepad) {
  63912. var _this = _super.call(this, vrGamepad) || this;
  63913. _this._mapping = {
  63914. // Semantic button names
  63915. buttons: ['thumbstick', 'trigger', 'grip', 'menu', 'trackpad'],
  63916. // A mapping of the button name to glTF model node name
  63917. // that should be transformed by button value.
  63918. buttonMeshNames: {
  63919. 'trigger': 'SELECT',
  63920. 'menu': 'MENU',
  63921. 'grip': 'GRASP',
  63922. 'thumbstick': 'THUMBSTICK_PRESS',
  63923. 'trackpad': 'TOUCHPAD_PRESS'
  63924. },
  63925. // This mapping is used to translate from the Motion Controller to Babylon semantics
  63926. buttonObservableNames: {
  63927. 'trigger': 'onTriggerStateChangedObservable',
  63928. 'menu': 'onSecondaryButtonStateChangedObservable',
  63929. 'grip': 'onMainButtonStateChangedObservable',
  63930. 'thumbstick': 'onPadStateChangedObservable',
  63931. 'trackpad': 'onTrackpadChangedObservable'
  63932. },
  63933. // A mapping of the axis name to glTF model node name
  63934. // that should be transformed by axis value.
  63935. // This array mirrors the browserGamepad.axes array, such that
  63936. // the mesh corresponding to axis 0 is in this array index 0.
  63937. axisMeshNames: [
  63938. 'THUMBSTICK_X',
  63939. 'THUMBSTICK_Y',
  63940. 'TOUCHPAD_TOUCH_X',
  63941. 'TOUCHPAD_TOUCH_Y'
  63942. ],
  63943. pointingPoseMeshName: 'POINTING_POSE'
  63944. };
  63945. _this.onTrackpadChangedObservable = new BABYLON.Observable();
  63946. _this.onTrackpadValuesChangedObservable = new BABYLON.Observable();
  63947. _this.trackpad = { x: 0, y: 0 };
  63948. _this.controllerType = BABYLON.PoseEnabledControllerType.WINDOWS;
  63949. _this._loadedMeshInfo = null;
  63950. return _this;
  63951. }
  63952. Object.defineProperty(WindowsMotionController.prototype, "onTriggerButtonStateChangedObservable", {
  63953. get: function () {
  63954. return this.onTriggerStateChangedObservable;
  63955. },
  63956. enumerable: true,
  63957. configurable: true
  63958. });
  63959. Object.defineProperty(WindowsMotionController.prototype, "onMenuButtonStateChangedObservable", {
  63960. get: function () {
  63961. return this.onSecondaryButtonStateChangedObservable;
  63962. },
  63963. enumerable: true,
  63964. configurable: true
  63965. });
  63966. Object.defineProperty(WindowsMotionController.prototype, "onGripButtonStateChangedObservable", {
  63967. get: function () {
  63968. return this.onMainButtonStateChangedObservable;
  63969. },
  63970. enumerable: true,
  63971. configurable: true
  63972. });
  63973. Object.defineProperty(WindowsMotionController.prototype, "onThumbstickButtonStateChangedObservable", {
  63974. get: function () {
  63975. return this.onPadStateChangedObservable;
  63976. },
  63977. enumerable: true,
  63978. configurable: true
  63979. });
  63980. Object.defineProperty(WindowsMotionController.prototype, "onTouchpadButtonStateChangedObservable", {
  63981. get: function () {
  63982. return this.onTrackpadChangedObservable;
  63983. },
  63984. enumerable: true,
  63985. configurable: true
  63986. });
  63987. Object.defineProperty(WindowsMotionController.prototype, "onTouchpadValuesChangedObservable", {
  63988. get: function () {
  63989. return this.onTrackpadValuesChangedObservable;
  63990. },
  63991. enumerable: true,
  63992. configurable: true
  63993. });
  63994. /**
  63995. * Called once per frame by the engine.
  63996. */
  63997. WindowsMotionController.prototype.update = function () {
  63998. _super.prototype.update.call(this);
  63999. // Only need to animate axes if there is a loaded mesh
  64000. if (this._loadedMeshInfo) {
  64001. if (this.browserGamepad.axes) {
  64002. if (this.browserGamepad.axes[2] != this.trackpad.x || this.browserGamepad.axes[3] != this.trackpad.y) {
  64003. this.trackpad.x = this.browserGamepad["axes"][2];
  64004. this.trackpad.y = this.browserGamepad["axes"][3];
  64005. this.onTrackpadValuesChangedObservable.notifyObservers(this.trackpad);
  64006. }
  64007. for (var axis = 0; axis < this._mapping.axisMeshNames.length; axis++) {
  64008. this.lerpAxisTransform(axis, this.browserGamepad.axes[axis]);
  64009. }
  64010. }
  64011. }
  64012. };
  64013. /**
  64014. * Called once for each button that changed state since the last frame
  64015. * @param buttonIdx Which button index changed
  64016. * @param state New state of the button
  64017. * @param changes Which properties on the state changed since last frame
  64018. */
  64019. WindowsMotionController.prototype.handleButtonChange = function (buttonIdx, state, changes) {
  64020. var buttonName = this._mapping.buttons[buttonIdx];
  64021. if (!buttonName) {
  64022. return;
  64023. }
  64024. // Only emit events for buttons that we know how to map from index to name
  64025. var observable = this[(this._mapping.buttonObservableNames)[buttonName]];
  64026. if (observable) {
  64027. observable.notifyObservers(state);
  64028. }
  64029. this.lerpButtonTransform(buttonName, state.value);
  64030. };
  64031. WindowsMotionController.prototype.lerpButtonTransform = function (buttonName, buttonValue) {
  64032. // If there is no loaded mesh, there is nothing to transform.
  64033. if (!this._loadedMeshInfo) {
  64034. return;
  64035. }
  64036. var meshInfo = this._loadedMeshInfo.buttonMeshes[buttonName];
  64037. if (!meshInfo.unpressed.rotationQuaternion || !meshInfo.pressed.rotationQuaternion || !meshInfo.value.rotationQuaternion) {
  64038. return;
  64039. }
  64040. BABYLON.Quaternion.SlerpToRef(meshInfo.unpressed.rotationQuaternion, meshInfo.pressed.rotationQuaternion, buttonValue, meshInfo.value.rotationQuaternion);
  64041. BABYLON.Vector3.LerpToRef(meshInfo.unpressed.position, meshInfo.pressed.position, buttonValue, meshInfo.value.position);
  64042. };
  64043. WindowsMotionController.prototype.lerpAxisTransform = function (axis, axisValue) {
  64044. if (!this._loadedMeshInfo) {
  64045. return;
  64046. }
  64047. var meshInfo = this._loadedMeshInfo.axisMeshes[axis];
  64048. if (!meshInfo) {
  64049. return;
  64050. }
  64051. if (!meshInfo.min.rotationQuaternion || !meshInfo.max.rotationQuaternion || !meshInfo.value.rotationQuaternion) {
  64052. return;
  64053. }
  64054. // Convert from gamepad value range (-1 to +1) to lerp range (0 to 1)
  64055. var lerpValue = axisValue * 0.5 + 0.5;
  64056. BABYLON.Quaternion.SlerpToRef(meshInfo.min.rotationQuaternion, meshInfo.max.rotationQuaternion, lerpValue, meshInfo.value.rotationQuaternion);
  64057. BABYLON.Vector3.LerpToRef(meshInfo.min.position, meshInfo.max.position, lerpValue, meshInfo.value.position);
  64058. };
  64059. /**
  64060. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  64061. * @param scene scene in which to add meshes
  64062. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  64063. */
  64064. WindowsMotionController.prototype.initControllerMesh = function (scene, meshLoaded, forceDefault) {
  64065. var _this = this;
  64066. if (forceDefault === void 0) { forceDefault = false; }
  64067. var path;
  64068. var filename;
  64069. // Checking if GLB loader is present
  64070. if (BABYLON.SceneLoader.IsPluginForExtensionAvailable(".glb")) {
  64071. // Determine the device specific folder based on the ID suffix
  64072. var device = 'default';
  64073. if (this.id && !forceDefault) {
  64074. var match = this.id.match(WindowsMotionController.GAMEPAD_ID_PATTERN);
  64075. device = ((match && match[0]) || device);
  64076. }
  64077. // Hand
  64078. if (this.hand === 'left') {
  64079. filename = WindowsMotionController.MODEL_LEFT_FILENAME;
  64080. }
  64081. else {
  64082. filename = WindowsMotionController.MODEL_RIGHT_FILENAME;
  64083. }
  64084. path = WindowsMotionController.MODEL_BASE_URL + device + '/';
  64085. }
  64086. else {
  64087. BABYLON.Tools.Warn("You need to reference GLTF loader to load Windows Motion Controllers model. Falling back to generic models");
  64088. path = BABYLON.GenericController.MODEL_BASE_URL;
  64089. filename = BABYLON.GenericController.MODEL_FILENAME;
  64090. }
  64091. BABYLON.SceneLoader.ImportMesh("", path, filename, scene, function (meshes) {
  64092. // glTF files successfully loaded from the remote server, now process them to ensure they are in the right format.
  64093. _this._loadedMeshInfo = _this.processModel(scene, meshes);
  64094. if (!_this._loadedMeshInfo) {
  64095. return;
  64096. }
  64097. _this._defaultModel = _this._loadedMeshInfo.rootNode;
  64098. _this.attachToMesh(_this._defaultModel);
  64099. if (meshLoaded) {
  64100. meshLoaded(_this._defaultModel);
  64101. }
  64102. }, null, function (scene, message) {
  64103. BABYLON.Tools.Log(message);
  64104. BABYLON.Tools.Warn('Failed to retrieve controller model from the remote server: ' + path + filename);
  64105. if (!forceDefault) {
  64106. _this.initControllerMesh(scene, meshLoaded, true);
  64107. }
  64108. });
  64109. };
  64110. /**
  64111. * Takes a list of meshes (as loaded from the glTF file) and finds the root node, as well as nodes that
  64112. * can be transformed by button presses and axes values, based on this._mapping.
  64113. *
  64114. * @param scene scene in which the meshes exist
  64115. * @param meshes list of meshes that make up the controller model to process
  64116. * @return structured view of the given meshes, with mapping of buttons and axes to meshes that can be transformed.
  64117. */
  64118. WindowsMotionController.prototype.processModel = function (scene, meshes) {
  64119. var loadedMeshInfo = null;
  64120. // Create a new mesh to contain the glTF hierarchy
  64121. var parentMesh = new BABYLON.Mesh(this.id + " " + this.hand, scene);
  64122. // Find the root node in the loaded glTF scene, and attach it as a child of 'parentMesh'
  64123. var childMesh = null;
  64124. for (var i = 0; i < meshes.length; i++) {
  64125. var mesh = meshes[i];
  64126. if (!mesh.parent) {
  64127. // Exclude controller meshes from picking results
  64128. mesh.isPickable = false;
  64129. // Handle root node, attach to the new parentMesh
  64130. childMesh = mesh;
  64131. break;
  64132. }
  64133. }
  64134. if (childMesh) {
  64135. childMesh.setParent(parentMesh);
  64136. // Create our mesh info. Note that this method will always return non-null.
  64137. loadedMeshInfo = this.createMeshInfo(parentMesh);
  64138. }
  64139. else {
  64140. BABYLON.Tools.Warn('Could not find root node in model file.');
  64141. }
  64142. return loadedMeshInfo;
  64143. };
  64144. WindowsMotionController.prototype.createMeshInfo = function (rootNode) {
  64145. var loadedMeshInfo = new LoadedMeshInfo();
  64146. var i;
  64147. loadedMeshInfo.rootNode = rootNode;
  64148. // Reset the caches
  64149. loadedMeshInfo.buttonMeshes = {};
  64150. loadedMeshInfo.axisMeshes = {};
  64151. // Button Meshes
  64152. for (i = 0; i < this._mapping.buttons.length; i++) {
  64153. var buttonMeshName = this._mapping.buttonMeshNames[this._mapping.buttons[i]];
  64154. if (!buttonMeshName) {
  64155. BABYLON.Tools.Log('Skipping unknown button at index: ' + i + ' with mapped name: ' + this._mapping.buttons[i]);
  64156. continue;
  64157. }
  64158. var buttonMesh = getChildByName(rootNode, buttonMeshName);
  64159. if (!buttonMesh) {
  64160. BABYLON.Tools.Warn('Missing button mesh with name: ' + buttonMeshName);
  64161. continue;
  64162. }
  64163. var buttonMeshInfo = {
  64164. index: i,
  64165. value: getImmediateChildByName(buttonMesh, 'VALUE'),
  64166. pressed: getImmediateChildByName(buttonMesh, 'PRESSED'),
  64167. unpressed: getImmediateChildByName(buttonMesh, 'UNPRESSED')
  64168. };
  64169. if (buttonMeshInfo.value && buttonMeshInfo.pressed && buttonMeshInfo.unpressed) {
  64170. loadedMeshInfo.buttonMeshes[this._mapping.buttons[i]] = buttonMeshInfo;
  64171. }
  64172. else {
  64173. // If we didn't find the mesh, it simply means this button won't have transforms applied as mapped button value changes.
  64174. BABYLON.Tools.Warn('Missing button submesh under mesh with name: ' + buttonMeshName +
  64175. '(VALUE: ' + !!buttonMeshInfo.value +
  64176. ', PRESSED: ' + !!buttonMeshInfo.pressed +
  64177. ', UNPRESSED:' + !!buttonMeshInfo.unpressed +
  64178. ')');
  64179. }
  64180. }
  64181. // Axis Meshes
  64182. for (i = 0; i < this._mapping.axisMeshNames.length; i++) {
  64183. var axisMeshName = this._mapping.axisMeshNames[i];
  64184. if (!axisMeshName) {
  64185. BABYLON.Tools.Log('Skipping unknown axis at index: ' + i);
  64186. continue;
  64187. }
  64188. var axisMesh = getChildByName(rootNode, axisMeshName);
  64189. if (!axisMesh) {
  64190. BABYLON.Tools.Warn('Missing axis mesh with name: ' + axisMeshName);
  64191. continue;
  64192. }
  64193. var axisMeshInfo = {
  64194. index: i,
  64195. value: getImmediateChildByName(axisMesh, 'VALUE'),
  64196. min: getImmediateChildByName(axisMesh, 'MIN'),
  64197. max: getImmediateChildByName(axisMesh, 'MAX')
  64198. };
  64199. if (axisMeshInfo.value && axisMeshInfo.min && axisMeshInfo.max) {
  64200. loadedMeshInfo.axisMeshes[i] = axisMeshInfo;
  64201. }
  64202. else {
  64203. // If we didn't find the mesh, it simply means thit axis won't have transforms applied as mapped axis values change.
  64204. BABYLON.Tools.Warn('Missing axis submesh under mesh with name: ' + axisMeshName +
  64205. '(VALUE: ' + !!axisMeshInfo.value +
  64206. ', MIN: ' + !!axisMeshInfo.min +
  64207. ', MAX:' + !!axisMeshInfo.max +
  64208. ')');
  64209. }
  64210. }
  64211. // Pointing Ray
  64212. loadedMeshInfo.pointingPoseNode = getChildByName(rootNode, this._mapping.pointingPoseMeshName);
  64213. if (!loadedMeshInfo.pointingPoseNode) {
  64214. BABYLON.Tools.Warn('Missing pointing pose mesh with name: ' + this._mapping.pointingPoseMeshName);
  64215. }
  64216. return loadedMeshInfo;
  64217. // Look through all children recursively. This will return null if no mesh exists with the given name.
  64218. function getChildByName(node, name) {
  64219. return node.getChildMeshes(false, function (n) { return n.name === name; })[0];
  64220. }
  64221. // Look through only immediate children. This will return null if no mesh exists with the given name.
  64222. function getImmediateChildByName(node, name) {
  64223. return node.getChildMeshes(true, function (n) { return n.name == name; })[0];
  64224. }
  64225. };
  64226. WindowsMotionController.prototype.getForwardRay = function (length) {
  64227. if (length === void 0) { length = 100; }
  64228. if (!(this._loadedMeshInfo && this._loadedMeshInfo.pointingPoseNode)) {
  64229. return _super.prototype.getForwardRay.call(this, length);
  64230. }
  64231. var m = this._loadedMeshInfo.pointingPoseNode.getWorldMatrix();
  64232. var origin = m.getTranslation();
  64233. var forward = new BABYLON.Vector3(0, 0, -1);
  64234. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, m);
  64235. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  64236. return new BABYLON.Ray(origin, direction, length);
  64237. };
  64238. WindowsMotionController.prototype.dispose = function () {
  64239. _super.prototype.dispose.call(this);
  64240. this.onTrackpadChangedObservable.clear();
  64241. };
  64242. WindowsMotionController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/microsoft/';
  64243. WindowsMotionController.MODEL_LEFT_FILENAME = 'left.glb';
  64244. WindowsMotionController.MODEL_RIGHT_FILENAME = 'right.glb';
  64245. WindowsMotionController.GAMEPAD_ID_PREFIX = 'Spatial Controller (Spatial Interaction Source) ';
  64246. WindowsMotionController.GAMEPAD_ID_PATTERN = /([0-9a-zA-Z]+-[0-9a-zA-Z]+)$/;
  64247. return WindowsMotionController;
  64248. }(BABYLON.WebVRController));
  64249. BABYLON.WindowsMotionController = WindowsMotionController;
  64250. })(BABYLON || (BABYLON = {}));
  64251. //# sourceMappingURL=babylon.windowsMotionController.js.map
  64252. var BABYLON;
  64253. (function (BABYLON) {
  64254. var GearVRController = /** @class */ (function (_super) {
  64255. __extends(GearVRController, _super);
  64256. function GearVRController(vrGamepad) {
  64257. var _this = _super.call(this, vrGamepad) || this;
  64258. _this._buttonIndexToObservableNameMap = [
  64259. 'onTrackpadChangedObservable',
  64260. 'onTriggerStateChangedObservable' // Trigger
  64261. ];
  64262. _this.controllerType = BABYLON.PoseEnabledControllerType.GEAR_VR;
  64263. return _this;
  64264. }
  64265. GearVRController.prototype.initControllerMesh = function (scene, meshLoaded) {
  64266. var _this = this;
  64267. BABYLON.SceneLoader.ImportMesh("", GearVRController.MODEL_BASE_URL, GearVRController.MODEL_FILENAME, scene, function (newMeshes) {
  64268. _this._defaultModel = newMeshes[1];
  64269. _this.attachToMesh(_this._defaultModel);
  64270. if (meshLoaded) {
  64271. meshLoaded(_this._defaultModel);
  64272. }
  64273. });
  64274. };
  64275. GearVRController.prototype.handleButtonChange = function (buttonIdx, state, changes) {
  64276. if (buttonIdx < this._buttonIndexToObservableNameMap.length) {
  64277. var observableName = this._buttonIndexToObservableNameMap[buttonIdx];
  64278. // Only emit events for buttons that we know how to map from index to observable
  64279. var observable = this[observableName];
  64280. if (observable) {
  64281. observable.notifyObservers(state);
  64282. }
  64283. }
  64284. };
  64285. GearVRController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/generic/';
  64286. GearVRController.MODEL_FILENAME = 'generic.babylon';
  64287. GearVRController.GAMEPAD_ID_PREFIX = 'Gear VR'; // id is 'Gear VR Controller'
  64288. return GearVRController;
  64289. }(BABYLON.WebVRController));
  64290. BABYLON.GearVRController = GearVRController;
  64291. })(BABYLON || (BABYLON = {}));
  64292. //# sourceMappingURL=babylon.gearVRController.js.map
  64293. var BABYLON;
  64294. (function (BABYLON) {
  64295. var FollowCamera = /** @class */ (function (_super) {
  64296. __extends(FollowCamera, _super);
  64297. function FollowCamera(name, position, scene, lockedTarget) {
  64298. if (lockedTarget === void 0) { lockedTarget = null; }
  64299. var _this = _super.call(this, name, position, scene) || this;
  64300. _this.radius = 12;
  64301. _this.rotationOffset = 0;
  64302. _this.heightOffset = 4;
  64303. _this.cameraAcceleration = 0.05;
  64304. _this.maxCameraSpeed = 20;
  64305. _this.lockedTarget = lockedTarget;
  64306. return _this;
  64307. }
  64308. FollowCamera.prototype.getRadians = function (degrees) {
  64309. return degrees * Math.PI / 180;
  64310. };
  64311. FollowCamera.prototype.follow = function (cameraTarget) {
  64312. if (!cameraTarget)
  64313. return;
  64314. var yRotation;
  64315. if (cameraTarget.rotationQuaternion) {
  64316. var rotMatrix = new BABYLON.Matrix();
  64317. cameraTarget.rotationQuaternion.toRotationMatrix(rotMatrix);
  64318. yRotation = Math.atan2(rotMatrix.m[8], rotMatrix.m[10]);
  64319. }
  64320. else {
  64321. yRotation = cameraTarget.rotation.y;
  64322. }
  64323. var radians = this.getRadians(this.rotationOffset) + yRotation;
  64324. var targetPosition = cameraTarget.getAbsolutePosition();
  64325. var targetX = targetPosition.x + Math.sin(radians) * this.radius;
  64326. var targetZ = targetPosition.z + Math.cos(radians) * this.radius;
  64327. var dx = targetX - this.position.x;
  64328. var dy = (targetPosition.y + this.heightOffset) - this.position.y;
  64329. var dz = (targetZ) - this.position.z;
  64330. var vx = dx * this.cameraAcceleration * 2; //this is set to .05
  64331. var vy = dy * this.cameraAcceleration;
  64332. var vz = dz * this.cameraAcceleration * 2;
  64333. if (vx > this.maxCameraSpeed || vx < -this.maxCameraSpeed) {
  64334. vx = vx < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  64335. }
  64336. if (vy > this.maxCameraSpeed || vy < -this.maxCameraSpeed) {
  64337. vy = vy < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  64338. }
  64339. if (vz > this.maxCameraSpeed || vz < -this.maxCameraSpeed) {
  64340. vz = vz < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  64341. }
  64342. this.position = new BABYLON.Vector3(this.position.x + vx, this.position.y + vy, this.position.z + vz);
  64343. this.setTarget(targetPosition);
  64344. };
  64345. FollowCamera.prototype._checkInputs = function () {
  64346. _super.prototype._checkInputs.call(this);
  64347. if (this.lockedTarget) {
  64348. this.follow(this.lockedTarget);
  64349. }
  64350. };
  64351. FollowCamera.prototype.getClassName = function () {
  64352. return "FollowCamera";
  64353. };
  64354. __decorate([
  64355. BABYLON.serialize()
  64356. ], FollowCamera.prototype, "radius", void 0);
  64357. __decorate([
  64358. BABYLON.serialize()
  64359. ], FollowCamera.prototype, "rotationOffset", void 0);
  64360. __decorate([
  64361. BABYLON.serialize()
  64362. ], FollowCamera.prototype, "heightOffset", void 0);
  64363. __decorate([
  64364. BABYLON.serialize()
  64365. ], FollowCamera.prototype, "cameraAcceleration", void 0);
  64366. __decorate([
  64367. BABYLON.serialize()
  64368. ], FollowCamera.prototype, "maxCameraSpeed", void 0);
  64369. __decorate([
  64370. BABYLON.serializeAsMeshReference("lockedTargetId")
  64371. ], FollowCamera.prototype, "lockedTarget", void 0);
  64372. return FollowCamera;
  64373. }(BABYLON.TargetCamera));
  64374. BABYLON.FollowCamera = FollowCamera;
  64375. var ArcFollowCamera = /** @class */ (function (_super) {
  64376. __extends(ArcFollowCamera, _super);
  64377. function ArcFollowCamera(name, alpha, beta, radius, target, scene) {
  64378. var _this = _super.call(this, name, BABYLON.Vector3.Zero(), scene) || this;
  64379. _this.alpha = alpha;
  64380. _this.beta = beta;
  64381. _this.radius = radius;
  64382. _this.target = target;
  64383. _this._cartesianCoordinates = BABYLON.Vector3.Zero();
  64384. _this.follow();
  64385. return _this;
  64386. }
  64387. ArcFollowCamera.prototype.follow = function () {
  64388. if (!this.target) {
  64389. return;
  64390. }
  64391. this._cartesianCoordinates.x = this.radius * Math.cos(this.alpha) * Math.cos(this.beta);
  64392. this._cartesianCoordinates.y = this.radius * Math.sin(this.beta);
  64393. this._cartesianCoordinates.z = this.radius * Math.sin(this.alpha) * Math.cos(this.beta);
  64394. var targetPosition = this.target.getAbsolutePosition();
  64395. this.position = targetPosition.add(this._cartesianCoordinates);
  64396. this.setTarget(targetPosition);
  64397. };
  64398. ArcFollowCamera.prototype._checkInputs = function () {
  64399. _super.prototype._checkInputs.call(this);
  64400. this.follow();
  64401. };
  64402. ArcFollowCamera.prototype.getClassName = function () {
  64403. return "ArcFollowCamera";
  64404. };
  64405. return ArcFollowCamera;
  64406. }(BABYLON.TargetCamera));
  64407. BABYLON.ArcFollowCamera = ArcFollowCamera;
  64408. })(BABYLON || (BABYLON = {}));
  64409. //# sourceMappingURL=babylon.followCamera.js.map
  64410. var BABYLON;
  64411. (function (BABYLON) {
  64412. // We're mainly based on the logic defined into the FreeCamera code
  64413. var UniversalCamera = /** @class */ (function (_super) {
  64414. __extends(UniversalCamera, _super);
  64415. //-- end properties for backward compatibility for inputs
  64416. function UniversalCamera(name, position, scene) {
  64417. var _this = _super.call(this, name, position, scene) || this;
  64418. _this.inputs.addGamepad();
  64419. return _this;
  64420. }
  64421. Object.defineProperty(UniversalCamera.prototype, "gamepadAngularSensibility", {
  64422. //-- Begin properties for backward compatibility for inputs
  64423. get: function () {
  64424. var gamepad = this.inputs.attached["gamepad"];
  64425. if (gamepad)
  64426. return gamepad.gamepadAngularSensibility;
  64427. return 0;
  64428. },
  64429. set: function (value) {
  64430. var gamepad = this.inputs.attached["gamepad"];
  64431. if (gamepad)
  64432. gamepad.gamepadAngularSensibility = value;
  64433. },
  64434. enumerable: true,
  64435. configurable: true
  64436. });
  64437. Object.defineProperty(UniversalCamera.prototype, "gamepadMoveSensibility", {
  64438. get: function () {
  64439. var gamepad = this.inputs.attached["gamepad"];
  64440. if (gamepad)
  64441. return gamepad.gamepadMoveSensibility;
  64442. return 0;
  64443. },
  64444. set: function (value) {
  64445. var gamepad = this.inputs.attached["gamepad"];
  64446. if (gamepad)
  64447. gamepad.gamepadMoveSensibility = value;
  64448. },
  64449. enumerable: true,
  64450. configurable: true
  64451. });
  64452. UniversalCamera.prototype.getClassName = function () {
  64453. return "UniversalCamera";
  64454. };
  64455. return UniversalCamera;
  64456. }(BABYLON.TouchCamera));
  64457. BABYLON.UniversalCamera = UniversalCamera;
  64458. })(BABYLON || (BABYLON = {}));
  64459. //# sourceMappingURL=babylon.universalCamera.js.map
  64460. var BABYLON;
  64461. (function (BABYLON) {
  64462. // We're mainly based on the logic defined into the FreeCamera code
  64463. var GamepadCamera = /** @class */ (function (_super) {
  64464. __extends(GamepadCamera, _super);
  64465. //-- end properties for backward compatibility for inputs
  64466. function GamepadCamera(name, position, scene) {
  64467. return _super.call(this, name, position, scene) || this;
  64468. }
  64469. Object.defineProperty(GamepadCamera.prototype, "gamepadAngularSensibility", {
  64470. //-- Begin properties for backward compatibility for inputs
  64471. get: function () {
  64472. var gamepad = this.inputs.attached["gamepad"];
  64473. if (gamepad)
  64474. return gamepad.gamepadAngularSensibility;
  64475. return 0;
  64476. },
  64477. set: function (value) {
  64478. var gamepad = this.inputs.attached["gamepad"];
  64479. if (gamepad)
  64480. gamepad.gamepadAngularSensibility = value;
  64481. },
  64482. enumerable: true,
  64483. configurable: true
  64484. });
  64485. Object.defineProperty(GamepadCamera.prototype, "gamepadMoveSensibility", {
  64486. get: function () {
  64487. var gamepad = this.inputs.attached["gamepad"];
  64488. if (gamepad)
  64489. return gamepad.gamepadMoveSensibility;
  64490. return 0;
  64491. },
  64492. set: function (value) {
  64493. var gamepad = this.inputs.attached["gamepad"];
  64494. if (gamepad)
  64495. gamepad.gamepadMoveSensibility = value;
  64496. },
  64497. enumerable: true,
  64498. configurable: true
  64499. });
  64500. GamepadCamera.prototype.getClassName = function () {
  64501. return "GamepadCamera";
  64502. };
  64503. return GamepadCamera;
  64504. }(BABYLON.UniversalCamera));
  64505. BABYLON.GamepadCamera = GamepadCamera;
  64506. })(BABYLON || (BABYLON = {}));
  64507. //# sourceMappingURL=babylon.gamepadCamera.js.map
  64508. var BABYLON;
  64509. (function (BABYLON) {
  64510. var PostProcessRenderPipelineManager = /** @class */ (function () {
  64511. function PostProcessRenderPipelineManager() {
  64512. this._renderPipelines = {};
  64513. }
  64514. PostProcessRenderPipelineManager.prototype.addPipeline = function (renderPipeline) {
  64515. this._renderPipelines[renderPipeline._name] = renderPipeline;
  64516. };
  64517. PostProcessRenderPipelineManager.prototype.attachCamerasToRenderPipeline = function (renderPipelineName, cameras, unique) {
  64518. if (unique === void 0) { unique = false; }
  64519. var renderPipeline = this._renderPipelines[renderPipelineName];
  64520. if (!renderPipeline) {
  64521. return;
  64522. }
  64523. renderPipeline._attachCameras(cameras, unique);
  64524. };
  64525. PostProcessRenderPipelineManager.prototype.detachCamerasFromRenderPipeline = function (renderPipelineName, cameras) {
  64526. var renderPipeline = this._renderPipelines[renderPipelineName];
  64527. if (!renderPipeline) {
  64528. return;
  64529. }
  64530. renderPipeline._detachCameras(cameras);
  64531. };
  64532. PostProcessRenderPipelineManager.prototype.enableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  64533. var renderPipeline = this._renderPipelines[renderPipelineName];
  64534. if (!renderPipeline) {
  64535. return;
  64536. }
  64537. renderPipeline._enableEffect(renderEffectName, cameras);
  64538. };
  64539. PostProcessRenderPipelineManager.prototype.disableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  64540. var renderPipeline = this._renderPipelines[renderPipelineName];
  64541. if (!renderPipeline) {
  64542. return;
  64543. }
  64544. renderPipeline._disableEffect(renderEffectName, cameras);
  64545. };
  64546. PostProcessRenderPipelineManager.prototype.update = function () {
  64547. for (var renderPipelineName in this._renderPipelines) {
  64548. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  64549. var pipeline = this._renderPipelines[renderPipelineName];
  64550. if (!pipeline.isSupported) {
  64551. pipeline.dispose();
  64552. delete this._renderPipelines[renderPipelineName];
  64553. }
  64554. else {
  64555. pipeline._update();
  64556. }
  64557. }
  64558. }
  64559. };
  64560. PostProcessRenderPipelineManager.prototype._rebuild = function () {
  64561. for (var renderPipelineName in this._renderPipelines) {
  64562. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  64563. var pipeline = this._renderPipelines[renderPipelineName];
  64564. pipeline._rebuild();
  64565. }
  64566. }
  64567. };
  64568. PostProcessRenderPipelineManager.prototype.dispose = function () {
  64569. for (var renderPipelineName in this._renderPipelines) {
  64570. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  64571. var pipeline = this._renderPipelines[renderPipelineName];
  64572. pipeline.dispose();
  64573. }
  64574. }
  64575. };
  64576. return PostProcessRenderPipelineManager;
  64577. }());
  64578. BABYLON.PostProcessRenderPipelineManager = PostProcessRenderPipelineManager;
  64579. })(BABYLON || (BABYLON = {}));
  64580. //# sourceMappingURL=babylon.postProcessRenderPipelineManager.js.map
  64581. var BABYLON;
  64582. (function (BABYLON) {
  64583. /**
  64584. * This represents a set of one or more post processes in Babylon.
  64585. * A post process can be used to apply a shader to a texture after it is rendered.
  64586. * @example https://doc.babylonjs.com/how_to/how_to_use_postprocessrenderpipeline
  64587. */
  64588. var PostProcessRenderEffect = /** @class */ (function () {
  64589. /**
  64590. * Instantiates a post process render effect.
  64591. * A post process can be used to apply a shader to a texture after it is rendered.
  64592. * @param engine The engine the effect is tied to
  64593. * @param name The name of the effect
  64594. * @param getPostProcesses A function that returns a set of post processes which the effect will run in order to be run.
  64595. * @param singleInstance False if this post process can be run on multiple cameras. (default: true)
  64596. */
  64597. function PostProcessRenderEffect(engine, name, getPostProcesses, singleInstance) {
  64598. this._name = name;
  64599. this._singleInstance = singleInstance || true;
  64600. this._getPostProcesses = getPostProcesses;
  64601. this._cameras = {};
  64602. this._indicesForCamera = {};
  64603. this._postProcesses = {};
  64604. }
  64605. Object.defineProperty(PostProcessRenderEffect.prototype, "isSupported", {
  64606. /**
  64607. * Checks if all the post processes in the effect are supported.
  64608. */
  64609. get: function () {
  64610. for (var index in this._postProcesses) {
  64611. for (var ppIndex in this._postProcesses[index]) {
  64612. if (!this._postProcesses[index][ppIndex].isSupported) {
  64613. return false;
  64614. }
  64615. }
  64616. }
  64617. return true;
  64618. },
  64619. enumerable: true,
  64620. configurable: true
  64621. });
  64622. /**
  64623. * Updates the current state of the effect
  64624. */
  64625. PostProcessRenderEffect.prototype._update = function () {
  64626. };
  64627. /**
  64628. * Attaches the effect on cameras
  64629. * @param cameras The camera to attach to.
  64630. */
  64631. PostProcessRenderEffect.prototype._attachCameras = function (cameras) {
  64632. var _this = this;
  64633. var cameraKey;
  64634. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  64635. if (!cams) {
  64636. return;
  64637. }
  64638. for (var i = 0; i < cams.length; i++) {
  64639. var camera = cams[i];
  64640. var cameraName = camera.name;
  64641. if (this._singleInstance) {
  64642. cameraKey = 0;
  64643. }
  64644. else {
  64645. cameraKey = cameraName;
  64646. }
  64647. if (!this._postProcesses[cameraKey]) {
  64648. var postProcess = this._getPostProcesses();
  64649. if (postProcess) {
  64650. this._postProcesses[cameraKey] = Array.isArray(postProcess) ? postProcess : [postProcess];
  64651. }
  64652. }
  64653. if (!this._indicesForCamera[cameraName]) {
  64654. this._indicesForCamera[cameraName] = [];
  64655. }
  64656. this._postProcesses[cameraKey].forEach(function (postProcess) {
  64657. var index = camera.attachPostProcess(postProcess);
  64658. _this._indicesForCamera[cameraName].push(index);
  64659. });
  64660. if (!this._cameras[cameraName]) {
  64661. this._cameras[cameraName] = camera;
  64662. }
  64663. }
  64664. };
  64665. /**
  64666. * Detatches the effect on cameras
  64667. * @param cameras The camera to detatch from.
  64668. */
  64669. PostProcessRenderEffect.prototype._detachCameras = function (cameras) {
  64670. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  64671. if (!cams) {
  64672. return;
  64673. }
  64674. for (var i = 0; i < cams.length; i++) {
  64675. var camera = cams[i];
  64676. var cameraName = camera.name;
  64677. this._postProcesses[this._singleInstance ? 0 : cameraName].forEach(function (postProcess) {
  64678. camera.detachPostProcess(postProcess);
  64679. });
  64680. if (this._cameras[cameraName]) {
  64681. //this._indicesForCamera.splice(index, 1);
  64682. this._cameras[cameraName] = null;
  64683. }
  64684. }
  64685. };
  64686. /**
  64687. * Enables the effect on given cameras
  64688. * @param cameras The camera to enable.
  64689. */
  64690. PostProcessRenderEffect.prototype._enable = function (cameras) {
  64691. var _this = this;
  64692. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  64693. if (!cams) {
  64694. return;
  64695. }
  64696. for (var i = 0; i < cams.length; i++) {
  64697. var camera = cams[i];
  64698. var cameraName = camera.name;
  64699. for (var j = 0; j < this._indicesForCamera[cameraName].length; j++) {
  64700. if (camera._postProcesses[this._indicesForCamera[cameraName][j]] === undefined) {
  64701. this._postProcesses[this._singleInstance ? 0 : cameraName].forEach(function (postProcess) {
  64702. cams[i].attachPostProcess(postProcess, _this._indicesForCamera[cameraName][j]);
  64703. });
  64704. }
  64705. }
  64706. }
  64707. };
  64708. /**
  64709. * Disables the effect on the given cameras
  64710. * @param cameras The camera to disable.
  64711. */
  64712. PostProcessRenderEffect.prototype._disable = function (cameras) {
  64713. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  64714. if (!cams) {
  64715. return;
  64716. }
  64717. for (var i = 0; i < cams.length; i++) {
  64718. var camera = cams[i];
  64719. var cameraName = camera.name;
  64720. this._postProcesses[this._singleInstance ? 0 : cameraName].forEach(function (postProcess) {
  64721. camera.detachPostProcess(postProcess);
  64722. });
  64723. }
  64724. };
  64725. /**
  64726. * Gets a list of the post processes contained in the effect.
  64727. * @param camera The camera to get the post processes on.
  64728. * @returns The list of the post processes in the effect.
  64729. */
  64730. PostProcessRenderEffect.prototype.getPostProcesses = function (camera) {
  64731. if (this._singleInstance) {
  64732. return this._postProcesses[0];
  64733. }
  64734. else {
  64735. if (!camera) {
  64736. return null;
  64737. }
  64738. return this._postProcesses[camera.name];
  64739. }
  64740. };
  64741. return PostProcessRenderEffect;
  64742. }());
  64743. BABYLON.PostProcessRenderEffect = PostProcessRenderEffect;
  64744. })(BABYLON || (BABYLON = {}));
  64745. //# sourceMappingURL=babylon.postProcessRenderEffect.js.map
  64746. var BABYLON;
  64747. (function (BABYLON) {
  64748. var PostProcessRenderPipeline = /** @class */ (function () {
  64749. function PostProcessRenderPipeline(engine, name) {
  64750. this._name = name;
  64751. this._renderEffects = {};
  64752. this._renderEffectsForIsolatedPass = new Array();
  64753. this._cameras = [];
  64754. }
  64755. PostProcessRenderPipeline.prototype.getClassName = function () {
  64756. return "PostProcessRenderPipeline";
  64757. };
  64758. Object.defineProperty(PostProcessRenderPipeline.prototype, "isSupported", {
  64759. get: function () {
  64760. for (var renderEffectName in this._renderEffects) {
  64761. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  64762. if (!this._renderEffects[renderEffectName].isSupported) {
  64763. return false;
  64764. }
  64765. }
  64766. }
  64767. return true;
  64768. },
  64769. enumerable: true,
  64770. configurable: true
  64771. });
  64772. PostProcessRenderPipeline.prototype.addEffect = function (renderEffect) {
  64773. this._renderEffects[renderEffect._name] = renderEffect;
  64774. };
  64775. // private
  64776. PostProcessRenderPipeline.prototype._rebuild = function () {
  64777. };
  64778. PostProcessRenderPipeline.prototype._enableEffect = function (renderEffectName, cameras) {
  64779. var renderEffects = this._renderEffects[renderEffectName];
  64780. if (!renderEffects) {
  64781. return;
  64782. }
  64783. renderEffects._enable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  64784. };
  64785. PostProcessRenderPipeline.prototype._disableEffect = function (renderEffectName, cameras) {
  64786. var renderEffects = this._renderEffects[renderEffectName];
  64787. if (!renderEffects) {
  64788. return;
  64789. }
  64790. renderEffects._disable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  64791. };
  64792. PostProcessRenderPipeline.prototype._attachCameras = function (cameras, unique) {
  64793. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  64794. if (!cams) {
  64795. return;
  64796. }
  64797. var indicesToDelete = [];
  64798. var i;
  64799. for (i = 0; i < cams.length; i++) {
  64800. var camera = cams[i];
  64801. var cameraName = camera.name;
  64802. if (this._cameras.indexOf(camera) === -1) {
  64803. this._cameras[cameraName] = camera;
  64804. }
  64805. else if (unique) {
  64806. indicesToDelete.push(i);
  64807. }
  64808. }
  64809. for (i = 0; i < indicesToDelete.length; i++) {
  64810. cameras.splice(indicesToDelete[i], 1);
  64811. }
  64812. for (var renderEffectName in this._renderEffects) {
  64813. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  64814. this._renderEffects[renderEffectName]._attachCameras(cams);
  64815. }
  64816. }
  64817. };
  64818. PostProcessRenderPipeline.prototype._detachCameras = function (cameras) {
  64819. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  64820. if (!cams) {
  64821. return;
  64822. }
  64823. for (var renderEffectName in this._renderEffects) {
  64824. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  64825. this._renderEffects[renderEffectName]._detachCameras(cams);
  64826. }
  64827. }
  64828. for (var i = 0; i < cams.length; i++) {
  64829. this._cameras.splice(this._cameras.indexOf(cams[i]), 1);
  64830. }
  64831. };
  64832. PostProcessRenderPipeline.prototype._update = function () {
  64833. for (var renderEffectName in this._renderEffects) {
  64834. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  64835. this._renderEffects[renderEffectName]._update();
  64836. }
  64837. }
  64838. for (var i = 0; i < this._cameras.length; i++) {
  64839. var cameraName = this._cameras[i].name;
  64840. if (this._renderEffectsForIsolatedPass[cameraName]) {
  64841. this._renderEffectsForIsolatedPass[cameraName]._update();
  64842. }
  64843. }
  64844. };
  64845. PostProcessRenderPipeline.prototype._reset = function () {
  64846. this._renderEffects = {};
  64847. this._renderEffectsForIsolatedPass = new Array();
  64848. };
  64849. PostProcessRenderPipeline.prototype.dispose = function () {
  64850. // Must be implemented by children
  64851. };
  64852. __decorate([
  64853. BABYLON.serialize()
  64854. ], PostProcessRenderPipeline.prototype, "_name", void 0);
  64855. return PostProcessRenderPipeline;
  64856. }());
  64857. BABYLON.PostProcessRenderPipeline = PostProcessRenderPipeline;
  64858. })(BABYLON || (BABYLON = {}));
  64859. //# sourceMappingURL=babylon.postProcessRenderPipeline.js.map
  64860. var BABYLON;
  64861. (function (BABYLON) {
  64862. var DepthRenderer = /** @class */ (function () {
  64863. function DepthRenderer(scene, type) {
  64864. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_FLOAT; }
  64865. var _this = this;
  64866. this._scene = scene;
  64867. var engine = scene.getEngine();
  64868. // Render target
  64869. this._depthMap = new BABYLON.RenderTargetTexture("depthMap", { width: engine.getRenderWidth(), height: engine.getRenderHeight() }, this._scene, false, true, type);
  64870. this._depthMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  64871. this._depthMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  64872. this._depthMap.refreshRate = 1;
  64873. this._depthMap.renderParticles = false;
  64874. this._depthMap.renderList = null;
  64875. // set default depth value to 1.0 (far away)
  64876. this._depthMap.onClearObservable.add(function (engine) {
  64877. engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true, true);
  64878. });
  64879. // Custom render function
  64880. var renderSubMesh = function (subMesh) {
  64881. var mesh = subMesh.getRenderingMesh();
  64882. var scene = _this._scene;
  64883. var engine = scene.getEngine();
  64884. var material = subMesh.getMaterial();
  64885. if (!material) {
  64886. return;
  64887. }
  64888. // Culling and reverse (right handed system)
  64889. engine.setState(material.backFaceCulling, 0, false, scene.useRightHandedSystem);
  64890. // Managing instances
  64891. var batch = mesh._getInstancesRenderList(subMesh._id);
  64892. if (batch.mustReturn) {
  64893. return;
  64894. }
  64895. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  64896. if (_this.isReady(subMesh, hardwareInstancedRendering) && scene.activeCamera) {
  64897. engine.enableEffect(_this._effect);
  64898. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  64899. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  64900. _this._effect.setFloat2("depthValues", scene.activeCamera.minZ, scene.activeCamera.minZ + scene.activeCamera.maxZ);
  64901. // Alpha test
  64902. if (material && material.needAlphaTesting()) {
  64903. var alphaTexture = material.getAlphaTestTexture();
  64904. if (alphaTexture) {
  64905. _this._effect.setTexture("diffuseSampler", alphaTexture);
  64906. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  64907. }
  64908. }
  64909. // Bones
  64910. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  64911. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  64912. }
  64913. // Draw
  64914. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  64915. }
  64916. };
  64917. this._depthMap.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  64918. var index;
  64919. if (depthOnlySubMeshes.length) {
  64920. engine.setColorWrite(false);
  64921. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  64922. renderSubMesh(depthOnlySubMeshes.data[index]);
  64923. }
  64924. engine.setColorWrite(true);
  64925. }
  64926. for (index = 0; index < opaqueSubMeshes.length; index++) {
  64927. renderSubMesh(opaqueSubMeshes.data[index]);
  64928. }
  64929. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  64930. renderSubMesh(alphaTestSubMeshes.data[index]);
  64931. }
  64932. };
  64933. }
  64934. DepthRenderer.prototype.isReady = function (subMesh, useInstances) {
  64935. var material = subMesh.getMaterial();
  64936. if (material.disableDepthWrite) {
  64937. return false;
  64938. }
  64939. var defines = [];
  64940. var attribs = [BABYLON.VertexBuffer.PositionKind];
  64941. var mesh = subMesh.getMesh();
  64942. // Alpha test
  64943. if (material && material.needAlphaTesting()) {
  64944. defines.push("#define ALPHATEST");
  64945. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  64946. attribs.push(BABYLON.VertexBuffer.UVKind);
  64947. defines.push("#define UV1");
  64948. }
  64949. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  64950. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  64951. defines.push("#define UV2");
  64952. }
  64953. }
  64954. // Bones
  64955. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  64956. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  64957. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  64958. if (mesh.numBoneInfluencers > 4) {
  64959. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  64960. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  64961. }
  64962. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  64963. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  64964. }
  64965. else {
  64966. defines.push("#define NUM_BONE_INFLUENCERS 0");
  64967. }
  64968. // Instances
  64969. if (useInstances) {
  64970. defines.push("#define INSTANCES");
  64971. attribs.push("world0");
  64972. attribs.push("world1");
  64973. attribs.push("world2");
  64974. attribs.push("world3");
  64975. }
  64976. // Get correct effect
  64977. var join = defines.join("\n");
  64978. if (this._cachedDefines !== join) {
  64979. this._cachedDefines = join;
  64980. this._effect = this._scene.getEngine().createEffect("depth", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "depthValues"], ["diffuseSampler"], join);
  64981. }
  64982. return this._effect.isReady();
  64983. };
  64984. DepthRenderer.prototype.getDepthMap = function () {
  64985. return this._depthMap;
  64986. };
  64987. // Methods
  64988. DepthRenderer.prototype.dispose = function () {
  64989. this._depthMap.dispose();
  64990. };
  64991. return DepthRenderer;
  64992. }());
  64993. BABYLON.DepthRenderer = DepthRenderer;
  64994. })(BABYLON || (BABYLON = {}));
  64995. //# sourceMappingURL=babylon.depthRenderer.js.map
  64996. var BABYLON;
  64997. (function (BABYLON) {
  64998. var SSAORenderingPipeline = /** @class */ (function (_super) {
  64999. __extends(SSAORenderingPipeline, _super);
  65000. /**
  65001. * @constructor
  65002. * @param {string} name - The rendering pipeline name
  65003. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  65004. * @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 }
  65005. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  65006. */
  65007. function SSAORenderingPipeline(name, scene, ratio, cameras) {
  65008. var _this = _super.call(this, scene.getEngine(), name) || this;
  65009. // Members
  65010. /**
  65011. * The PassPostProcess id in the pipeline that contains the original scene color
  65012. * @type {string}
  65013. */
  65014. _this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  65015. /**
  65016. * The SSAO PostProcess id in the pipeline
  65017. * @type {string}
  65018. */
  65019. _this.SSAORenderEffect = "SSAORenderEffect";
  65020. /**
  65021. * The horizontal blur PostProcess id in the pipeline
  65022. * @type {string}
  65023. */
  65024. _this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  65025. /**
  65026. * The vertical blur PostProcess id in the pipeline
  65027. * @type {string}
  65028. */
  65029. _this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  65030. /**
  65031. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  65032. * @type {string}
  65033. */
  65034. _this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  65035. /**
  65036. * The output strength of the SSAO post-process. Default value is 1.0.
  65037. * @type {number}
  65038. */
  65039. _this.totalStrength = 1.0;
  65040. /**
  65041. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 0.0006
  65042. * @type {number}
  65043. */
  65044. _this.radius = 0.0001;
  65045. /**
  65046. * Related to fallOff, used to interpolate SSAO samples (first interpolate function input) based on the occlusion difference of each pixel
  65047. * Must not be equal to fallOff and superior to fallOff.
  65048. * Default value is 0.975
  65049. * @type {number}
  65050. */
  65051. _this.area = 0.0075;
  65052. /**
  65053. * Related to area, used to interpolate SSAO samples (second interpolate function input) based on the occlusion difference of each pixel
  65054. * Must not be equal to area and inferior to area.
  65055. * Default value is 0.0
  65056. * @type {number}
  65057. */
  65058. _this.fallOff = 0.000001;
  65059. /**
  65060. * The base color of the SSAO post-process
  65061. * The final result is "base + ssao" between [0, 1]
  65062. * @type {number}
  65063. */
  65064. _this.base = 0.5;
  65065. _this._firstUpdate = true;
  65066. _this._scene = scene;
  65067. // Set up assets
  65068. _this._createRandomTexture();
  65069. _this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  65070. var ssaoRatio = ratio.ssaoRatio || ratio;
  65071. var combineRatio = ratio.combineRatio || ratio;
  65072. _this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", combineRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  65073. _this._createSSAOPostProcess(ssaoRatio);
  65074. _this._createBlurPostProcess(ssaoRatio);
  65075. _this._createSSAOCombinePostProcess(combineRatio);
  65076. // Set up pipeline
  65077. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOOriginalSceneColorEffect, function () { return _this._originalColorPostProcess; }, true));
  65078. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAORenderEffect, function () { return _this._ssaoPostProcess; }, true));
  65079. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurHRenderEffect, function () { return _this._blurHPostProcess; }, true));
  65080. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurVRenderEffect, function () { return _this._blurVPostProcess; }, true));
  65081. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOCombineRenderEffect, function () { return _this._ssaoCombinePostProcess; }, true));
  65082. // Finish
  65083. scene.postProcessRenderPipelineManager.addPipeline(_this);
  65084. if (cameras)
  65085. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  65086. return _this;
  65087. }
  65088. // Public Methods
  65089. /**
  65090. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  65091. */
  65092. SSAORenderingPipeline.prototype.dispose = function (disableDepthRender) {
  65093. if (disableDepthRender === void 0) { disableDepthRender = false; }
  65094. for (var i = 0; i < this._scene.cameras.length; i++) {
  65095. var camera = this._scene.cameras[i];
  65096. this._originalColorPostProcess.dispose(camera);
  65097. this._ssaoPostProcess.dispose(camera);
  65098. this._blurHPostProcess.dispose(camera);
  65099. this._blurVPostProcess.dispose(camera);
  65100. this._ssaoCombinePostProcess.dispose(camera);
  65101. }
  65102. this._randomTexture.dispose();
  65103. if (disableDepthRender)
  65104. this._scene.disableDepthRenderer();
  65105. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  65106. _super.prototype.dispose.call(this);
  65107. };
  65108. // Private Methods
  65109. SSAORenderingPipeline.prototype._createBlurPostProcess = function (ratio) {
  65110. var _this = this;
  65111. var size = 16;
  65112. 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);
  65113. 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);
  65114. this._blurHPostProcess.onActivateObservable.add(function () {
  65115. var dw = _this._blurHPostProcess.width / _this._scene.getEngine().getRenderWidth();
  65116. _this._blurHPostProcess.kernel = size * dw;
  65117. });
  65118. this._blurVPostProcess.onActivateObservable.add(function () {
  65119. var dw = _this._blurVPostProcess.height / _this._scene.getEngine().getRenderHeight();
  65120. _this._blurVPostProcess.kernel = size * dw;
  65121. });
  65122. };
  65123. SSAORenderingPipeline.prototype._rebuild = function () {
  65124. this._firstUpdate = true;
  65125. _super.prototype._rebuild.call(this);
  65126. };
  65127. SSAORenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  65128. var _this = this;
  65129. var numSamples = 16;
  65130. var sampleSphere = [
  65131. 0.5381, 0.1856, -0.4319,
  65132. 0.1379, 0.2486, 0.4430,
  65133. 0.3371, 0.5679, -0.0057,
  65134. -0.6999, -0.0451, -0.0019,
  65135. 0.0689, -0.1598, -0.8547,
  65136. 0.0560, 0.0069, -0.1843,
  65137. -0.0146, 0.1402, 0.0762,
  65138. 0.0100, -0.1924, -0.0344,
  65139. -0.3577, -0.5301, -0.4358,
  65140. -0.3169, 0.1063, 0.0158,
  65141. 0.0103, -0.5869, 0.0046,
  65142. -0.0897, -0.4940, 0.3287,
  65143. 0.7119, -0.0154, -0.0918,
  65144. -0.0533, 0.0596, -0.5411,
  65145. 0.0352, -0.0631, 0.5460,
  65146. -0.4776, 0.2847, -0.0271
  65147. ];
  65148. var samplesFactor = 1.0 / numSamples;
  65149. this._ssaoPostProcess = new BABYLON.PostProcess("ssao", "ssao", [
  65150. "sampleSphere", "samplesFactor", "randTextureTiles", "totalStrength", "radius",
  65151. "area", "fallOff", "base", "range", "viewport"
  65152. ], ["randomSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define SAMPLES " + numSamples + "\n#define SSAO");
  65153. this._ssaoPostProcess.onApply = function (effect) {
  65154. if (_this._firstUpdate) {
  65155. effect.setArray3("sampleSphere", sampleSphere);
  65156. effect.setFloat("samplesFactor", samplesFactor);
  65157. effect.setFloat("randTextureTiles", 4.0);
  65158. }
  65159. effect.setFloat("totalStrength", _this.totalStrength);
  65160. effect.setFloat("radius", _this.radius);
  65161. effect.setFloat("area", _this.area);
  65162. effect.setFloat("fallOff", _this.fallOff);
  65163. effect.setFloat("base", _this.base);
  65164. effect.setTexture("textureSampler", _this._depthTexture);
  65165. effect.setTexture("randomSampler", _this._randomTexture);
  65166. };
  65167. };
  65168. SSAORenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  65169. var _this = this;
  65170. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  65171. this._ssaoCombinePostProcess.onApply = function (effect) {
  65172. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  65173. };
  65174. };
  65175. SSAORenderingPipeline.prototype._createRandomTexture = function () {
  65176. var size = 512;
  65177. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  65178. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  65179. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  65180. var context = this._randomTexture.getContext();
  65181. var rand = function (min, max) {
  65182. return Math.random() * (max - min) + min;
  65183. };
  65184. var randVector = BABYLON.Vector3.Zero();
  65185. for (var x = 0; x < size; x++) {
  65186. for (var y = 0; y < size; y++) {
  65187. randVector.x = Math.floor(rand(-1.0, 1.0) * 255);
  65188. randVector.y = Math.floor(rand(-1.0, 1.0) * 255);
  65189. randVector.z = Math.floor(rand(-1.0, 1.0) * 255);
  65190. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  65191. context.fillRect(x, y, 1, 1);
  65192. }
  65193. }
  65194. this._randomTexture.update(false);
  65195. };
  65196. __decorate([
  65197. BABYLON.serialize()
  65198. ], SSAORenderingPipeline.prototype, "totalStrength", void 0);
  65199. __decorate([
  65200. BABYLON.serialize()
  65201. ], SSAORenderingPipeline.prototype, "radius", void 0);
  65202. __decorate([
  65203. BABYLON.serialize()
  65204. ], SSAORenderingPipeline.prototype, "area", void 0);
  65205. __decorate([
  65206. BABYLON.serialize()
  65207. ], SSAORenderingPipeline.prototype, "fallOff", void 0);
  65208. __decorate([
  65209. BABYLON.serialize()
  65210. ], SSAORenderingPipeline.prototype, "base", void 0);
  65211. return SSAORenderingPipeline;
  65212. }(BABYLON.PostProcessRenderPipeline));
  65213. BABYLON.SSAORenderingPipeline = SSAORenderingPipeline;
  65214. })(BABYLON || (BABYLON = {}));
  65215. //# sourceMappingURL=babylon.ssaoRenderingPipeline.js.map
  65216. var BABYLON;
  65217. (function (BABYLON) {
  65218. var SSAO2RenderingPipeline = /** @class */ (function (_super) {
  65219. __extends(SSAO2RenderingPipeline, _super);
  65220. /**
  65221. * @constructor
  65222. * @param {string} name - The rendering pipeline name
  65223. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  65224. * @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 }
  65225. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  65226. */
  65227. function SSAO2RenderingPipeline(name, scene, ratio, cameras) {
  65228. var _this = _super.call(this, scene.getEngine(), name) || this;
  65229. // Members
  65230. /**
  65231. * The PassPostProcess id in the pipeline that contains the original scene color
  65232. * @type {string}
  65233. */
  65234. _this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  65235. /**
  65236. * The SSAO PostProcess id in the pipeline
  65237. * @type {string}
  65238. */
  65239. _this.SSAORenderEffect = "SSAORenderEffect";
  65240. /**
  65241. * The horizontal blur PostProcess id in the pipeline
  65242. * @type {string}
  65243. */
  65244. _this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  65245. /**
  65246. * The vertical blur PostProcess id in the pipeline
  65247. * @type {string}
  65248. */
  65249. _this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  65250. /**
  65251. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  65252. * @type {string}
  65253. */
  65254. _this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  65255. /**
  65256. * The output strength of the SSAO post-process. Default value is 1.0.
  65257. * @type {number}
  65258. */
  65259. _this.totalStrength = 1.0;
  65260. /**
  65261. * Maximum depth value to still render AO. A smooth falloff makes the dimming more natural, so there will be no abrupt shading change.
  65262. * @type {number}
  65263. */
  65264. _this.maxZ = 100.0;
  65265. /**
  65266. * In order to save performances, SSAO radius is clamped on close geometry. This ratio changes by how much
  65267. * @type {number}
  65268. */
  65269. _this.minZAspect = 0.2;
  65270. /**
  65271. * Number of samples used for the SSAO calculations. Default value is 8
  65272. * @type {number}
  65273. */
  65274. _this._samples = 8;
  65275. /**
  65276. * Are we using bilateral blur ?
  65277. * @type {boolean}
  65278. */
  65279. _this._expensiveBlur = true;
  65280. /**
  65281. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 2.0
  65282. * @type {number}
  65283. */
  65284. _this.radius = 2.0;
  65285. /**
  65286. * The base color of the SSAO post-process
  65287. * The final result is "base + ssao" between [0, 1]
  65288. * @type {number}
  65289. */
  65290. _this.base = 0.1;
  65291. _this._firstUpdate = true;
  65292. _this._scene = scene;
  65293. if (!_this.isSupported) {
  65294. BABYLON.Tools.Error("SSAO 2 needs WebGL 2 support.");
  65295. return _this;
  65296. }
  65297. var ssaoRatio = ratio.ssaoRatio || ratio;
  65298. var blurRatio = ratio.blurRatio || ratio;
  65299. // Set up assets
  65300. var geometryBufferRenderer = scene.enableGeometryBufferRenderer();
  65301. _this._createRandomTexture();
  65302. _this._depthTexture = geometryBufferRenderer.getGBuffer().textures[0];
  65303. _this._normalTexture = geometryBufferRenderer.getGBuffer().textures[1];
  65304. _this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  65305. _this._createSSAOPostProcess(1.0);
  65306. _this._createBlurPostProcess(ssaoRatio, blurRatio);
  65307. _this._createSSAOCombinePostProcess(blurRatio);
  65308. // Set up pipeline
  65309. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOOriginalSceneColorEffect, function () { return _this._originalColorPostProcess; }, true));
  65310. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAORenderEffect, function () { return _this._ssaoPostProcess; }, true));
  65311. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurHRenderEffect, function () { return _this._blurHPostProcess; }, true));
  65312. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurVRenderEffect, function () { return _this._blurVPostProcess; }, true));
  65313. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOCombineRenderEffect, function () { return _this._ssaoCombinePostProcess; }, true));
  65314. // Finish
  65315. scene.postProcessRenderPipelineManager.addPipeline(_this);
  65316. if (cameras)
  65317. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  65318. return _this;
  65319. }
  65320. Object.defineProperty(SSAO2RenderingPipeline.prototype, "samples", {
  65321. get: function () {
  65322. return this._samples;
  65323. },
  65324. set: function (n) {
  65325. this._ssaoPostProcess.updateEffect("#define SAMPLES " + n + "\n#define SSAO");
  65326. this._samples = n;
  65327. this._sampleSphere = this._generateHemisphere();
  65328. this._firstUpdate = true;
  65329. },
  65330. enumerable: true,
  65331. configurable: true
  65332. });
  65333. Object.defineProperty(SSAO2RenderingPipeline.prototype, "expensiveBlur", {
  65334. get: function () {
  65335. return this._expensiveBlur;
  65336. },
  65337. set: function (b) {
  65338. 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"]);
  65339. this._blurVPostProcess.updateEffect("#define BILATERAL_BLUR\n#define SAMPLES 16\n#define EXPENSIVE " + (b ? "1" : "0") + "\n", null, ["textureSampler", "depthSampler"]);
  65340. this._expensiveBlur = b;
  65341. this._firstUpdate = true;
  65342. },
  65343. enumerable: true,
  65344. configurable: true
  65345. });
  65346. Object.defineProperty(SSAO2RenderingPipeline, "IsSupported", {
  65347. /**
  65348. * Support test.
  65349. * @type {boolean}
  65350. */
  65351. get: function () {
  65352. var engine = BABYLON.Engine.LastCreatedEngine;
  65353. if (!engine) {
  65354. return false;
  65355. }
  65356. return engine.getCaps().drawBuffersExtension;
  65357. },
  65358. enumerable: true,
  65359. configurable: true
  65360. });
  65361. // Public Methods
  65362. /**
  65363. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  65364. */
  65365. SSAO2RenderingPipeline.prototype.dispose = function (disableGeometryBufferRenderer) {
  65366. if (disableGeometryBufferRenderer === void 0) { disableGeometryBufferRenderer = false; }
  65367. for (var i = 0; i < this._scene.cameras.length; i++) {
  65368. var camera = this._scene.cameras[i];
  65369. this._originalColorPostProcess.dispose(camera);
  65370. this._ssaoPostProcess.dispose(camera);
  65371. this._blurHPostProcess.dispose(camera);
  65372. this._blurVPostProcess.dispose(camera);
  65373. this._ssaoCombinePostProcess.dispose(camera);
  65374. }
  65375. this._randomTexture.dispose();
  65376. if (disableGeometryBufferRenderer)
  65377. this._scene.disableGeometryBufferRenderer();
  65378. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  65379. _super.prototype.dispose.call(this);
  65380. };
  65381. // Private Methods
  65382. SSAO2RenderingPipeline.prototype._createBlurPostProcess = function (ssaoRatio, blurRatio) {
  65383. var _this = this;
  65384. this._samplerOffsets = [];
  65385. var expensive = this.expensiveBlur;
  65386. for (var i = -8; i < 8; i++) {
  65387. this._samplerOffsets.push(i * 2 + 0.5);
  65388. }
  65389. 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");
  65390. this._blurHPostProcess.onApply = function (effect) {
  65391. if (!_this._scene.activeCamera) {
  65392. return;
  65393. }
  65394. effect.setFloat("outSize", _this._ssaoCombinePostProcess.width > 0 ? _this._ssaoCombinePostProcess.width : _this._originalColorPostProcess.width);
  65395. effect.setFloat("near", _this._scene.activeCamera.minZ);
  65396. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  65397. effect.setFloat("radius", _this.radius);
  65398. effect.setTexture("depthSampler", _this._depthTexture);
  65399. if (_this._firstUpdate) {
  65400. effect.setArray("samplerOffsets", _this._samplerOffsets);
  65401. }
  65402. };
  65403. 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");
  65404. this._blurVPostProcess.onApply = function (effect) {
  65405. if (!_this._scene.activeCamera) {
  65406. return;
  65407. }
  65408. effect.setFloat("outSize", _this._ssaoCombinePostProcess.height > 0 ? _this._ssaoCombinePostProcess.height : _this._originalColorPostProcess.height);
  65409. effect.setFloat("near", _this._scene.activeCamera.minZ);
  65410. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  65411. effect.setFloat("radius", _this.radius);
  65412. effect.setTexture("depthSampler", _this._depthTexture);
  65413. if (_this._firstUpdate) {
  65414. effect.setArray("samplerOffsets", _this._samplerOffsets);
  65415. _this._firstUpdate = false;
  65416. }
  65417. };
  65418. };
  65419. SSAO2RenderingPipeline.prototype._rebuild = function () {
  65420. this._firstUpdate = true;
  65421. _super.prototype._rebuild.call(this);
  65422. };
  65423. SSAO2RenderingPipeline.prototype._generateHemisphere = function () {
  65424. var numSamples = this.samples;
  65425. var result = [];
  65426. var vector, scale;
  65427. var rand = function (min, max) {
  65428. return Math.random() * (max - min) + min;
  65429. };
  65430. var i = 0;
  65431. while (i < numSamples) {
  65432. vector = new BABYLON.Vector3(rand(-1.0, 1.0), rand(-1.0, 1.0), rand(0.30, 1.0));
  65433. vector.normalize();
  65434. scale = i / numSamples;
  65435. scale = BABYLON.Scalar.Lerp(0.1, 1.0, scale * scale);
  65436. vector.scaleInPlace(scale);
  65437. result.push(vector.x, vector.y, vector.z);
  65438. i++;
  65439. }
  65440. return result;
  65441. };
  65442. SSAO2RenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  65443. var _this = this;
  65444. var numSamples = this.samples;
  65445. this._sampleSphere = this._generateHemisphere();
  65446. this._ssaoPostProcess = new BABYLON.PostProcess("ssao2", "ssao2", [
  65447. "sampleSphere", "samplesFactor", "randTextureTiles", "totalStrength", "radius",
  65448. "base", "range", "projection", "near", "far", "texelSize",
  65449. "xViewport", "yViewport", "maxZ", "minZAspect"
  65450. ], ["randomSampler", "normalSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define SAMPLES " + numSamples + "\n#define SSAO");
  65451. this._ssaoPostProcess.onApply = function (effect) {
  65452. if (_this._firstUpdate) {
  65453. effect.setArray3("sampleSphere", _this._sampleSphere);
  65454. effect.setFloat("randTextureTiles", 4.0);
  65455. }
  65456. if (!_this._scene.activeCamera) {
  65457. return;
  65458. }
  65459. effect.setFloat("samplesFactor", 1 / _this.samples);
  65460. effect.setFloat("totalStrength", _this.totalStrength);
  65461. effect.setFloat2("texelSize", 1 / _this._ssaoPostProcess.width, 1 / _this._ssaoPostProcess.height);
  65462. effect.setFloat("radius", _this.radius);
  65463. effect.setFloat("maxZ", _this.maxZ);
  65464. effect.setFloat("minZAspect", _this.minZAspect);
  65465. effect.setFloat("base", _this.base);
  65466. effect.setFloat("near", _this._scene.activeCamera.minZ);
  65467. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  65468. effect.setFloat("xViewport", Math.tan(_this._scene.activeCamera.fov / 2) * _this._scene.getEngine().getAspectRatio(_this._scene.activeCamera, true));
  65469. effect.setFloat("yViewport", Math.tan(_this._scene.activeCamera.fov / 2));
  65470. effect.setMatrix("projection", _this._scene.getProjectionMatrix());
  65471. effect.setTexture("textureSampler", _this._depthTexture);
  65472. effect.setTexture("normalSampler", _this._normalTexture);
  65473. effect.setTexture("randomSampler", _this._randomTexture);
  65474. };
  65475. };
  65476. SSAO2RenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  65477. var _this = this;
  65478. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  65479. this._ssaoCombinePostProcess.onApply = function (effect) {
  65480. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  65481. };
  65482. };
  65483. SSAO2RenderingPipeline.prototype._createRandomTexture = function () {
  65484. var size = 512;
  65485. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  65486. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  65487. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  65488. var context = this._randomTexture.getContext();
  65489. var rand = function (min, max) {
  65490. return Math.random() * (max - min) + min;
  65491. };
  65492. var randVector = BABYLON.Vector3.Zero();
  65493. for (var x = 0; x < size; x++) {
  65494. for (var y = 0; y < size; y++) {
  65495. randVector.x = rand(0.0, 1.0);
  65496. randVector.y = rand(0.0, 1.0);
  65497. randVector.z = 0.0;
  65498. randVector.normalize();
  65499. randVector.scaleInPlace(255);
  65500. randVector.x = Math.floor(randVector.x);
  65501. randVector.y = Math.floor(randVector.y);
  65502. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  65503. context.fillRect(x, y, 1, 1);
  65504. }
  65505. }
  65506. this._randomTexture.update(false);
  65507. };
  65508. __decorate([
  65509. BABYLON.serialize()
  65510. ], SSAO2RenderingPipeline.prototype, "totalStrength", void 0);
  65511. __decorate([
  65512. BABYLON.serialize()
  65513. ], SSAO2RenderingPipeline.prototype, "maxZ", void 0);
  65514. __decorate([
  65515. BABYLON.serialize()
  65516. ], SSAO2RenderingPipeline.prototype, "minZAspect", void 0);
  65517. __decorate([
  65518. BABYLON.serialize("samples")
  65519. ], SSAO2RenderingPipeline.prototype, "_samples", void 0);
  65520. __decorate([
  65521. BABYLON.serialize("expensiveBlur")
  65522. ], SSAO2RenderingPipeline.prototype, "_expensiveBlur", void 0);
  65523. __decorate([
  65524. BABYLON.serialize()
  65525. ], SSAO2RenderingPipeline.prototype, "radius", void 0);
  65526. __decorate([
  65527. BABYLON.serialize()
  65528. ], SSAO2RenderingPipeline.prototype, "base", void 0);
  65529. return SSAO2RenderingPipeline;
  65530. }(BABYLON.PostProcessRenderPipeline));
  65531. BABYLON.SSAO2RenderingPipeline = SSAO2RenderingPipeline;
  65532. })(BABYLON || (BABYLON = {}));
  65533. //# sourceMappingURL=babylon.ssao2RenderingPipeline.js.map
  65534. // BABYLON.JS Chromatic Aberration GLSL Shader
  65535. // Author: Olivier Guyot
  65536. // Separates very slightly R, G and B colors on the edges of the screen
  65537. // Inspired by Francois Tarlier & Martins Upitis
  65538. var BABYLON;
  65539. (function (BABYLON) {
  65540. var LensRenderingPipeline = /** @class */ (function (_super) {
  65541. __extends(LensRenderingPipeline, _super);
  65542. /**
  65543. * @constructor
  65544. *
  65545. * Effect parameters are as follow:
  65546. * {
  65547. * chromatic_aberration: number; // from 0 to x (1 for realism)
  65548. * edge_blur: number; // from 0 to x (1 for realism)
  65549. * distortion: number; // from 0 to x (1 for realism)
  65550. * grain_amount: number; // from 0 to 1
  65551. * grain_texture: BABYLON.Texture; // texture to use for grain effect; if unset, use random B&W noise
  65552. * dof_focus_distance: number; // depth-of-field: focus distance; unset to disable (disabled by default)
  65553. * dof_aperture: number; // depth-of-field: focus blur bias (default: 1)
  65554. * dof_darken: number; // depth-of-field: darken that which is out of focus (from 0 to 1, disabled by default)
  65555. * dof_pentagon: boolean; // depth-of-field: makes a pentagon-like "bokeh" effect
  65556. * dof_gain: number; // depth-of-field: highlights gain; unset to disable (disabled by default)
  65557. * dof_threshold: number; // depth-of-field: highlights threshold (default: 1)
  65558. * blur_noise: boolean; // add a little bit of noise to the blur (default: true)
  65559. * }
  65560. * Note: if an effect parameter is unset, effect is disabled
  65561. *
  65562. * @param {string} name - The rendering pipeline name
  65563. * @param {object} parameters - An object containing all parameters (see above)
  65564. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  65565. * @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)
  65566. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  65567. */
  65568. function LensRenderingPipeline(name, parameters, scene, ratio, cameras) {
  65569. if (ratio === void 0) { ratio = 1.0; }
  65570. var _this = _super.call(this, scene.getEngine(), name) || this;
  65571. // Lens effects can be of the following:
  65572. // - chromatic aberration (slight shift of RGB colors)
  65573. // - blur on the edge of the lens
  65574. // - lens distortion
  65575. // - depth-of-field blur & highlights enhancing
  65576. // - depth-of-field 'bokeh' effect (shapes appearing in blurred areas)
  65577. // - grain effect (noise or custom texture)
  65578. // Two additional texture samplers are needed:
  65579. // - depth map (for depth-of-field)
  65580. // - grain texture
  65581. /**
  65582. * The chromatic aberration PostProcess id in the pipeline
  65583. * @type {string}
  65584. */
  65585. _this.LensChromaticAberrationEffect = "LensChromaticAberrationEffect";
  65586. /**
  65587. * The highlights enhancing PostProcess id in the pipeline
  65588. * @type {string}
  65589. */
  65590. _this.HighlightsEnhancingEffect = "HighlightsEnhancingEffect";
  65591. /**
  65592. * The depth-of-field PostProcess id in the pipeline
  65593. * @type {string}
  65594. */
  65595. _this.LensDepthOfFieldEffect = "LensDepthOfFieldEffect";
  65596. _this._scene = scene;
  65597. // Fetch texture samplers
  65598. _this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  65599. if (parameters.grain_texture) {
  65600. _this._grainTexture = parameters.grain_texture;
  65601. }
  65602. else {
  65603. _this._createGrainTexture();
  65604. }
  65605. // save parameters
  65606. _this._edgeBlur = parameters.edge_blur ? parameters.edge_blur : 0;
  65607. _this._grainAmount = parameters.grain_amount ? parameters.grain_amount : 0;
  65608. _this._chromaticAberration = parameters.chromatic_aberration ? parameters.chromatic_aberration : 0;
  65609. _this._distortion = parameters.distortion ? parameters.distortion : 0;
  65610. _this._highlightsGain = parameters.dof_gain !== undefined ? parameters.dof_gain : -1;
  65611. _this._highlightsThreshold = parameters.dof_threshold ? parameters.dof_threshold : 1;
  65612. _this._dofDistance = parameters.dof_focus_distance !== undefined ? parameters.dof_focus_distance : -1;
  65613. _this._dofAperture = parameters.dof_aperture ? parameters.dof_aperture : 1;
  65614. _this._dofDarken = parameters.dof_darken ? parameters.dof_darken : 0;
  65615. _this._dofPentagon = parameters.dof_pentagon !== undefined ? parameters.dof_pentagon : true;
  65616. _this._blurNoise = parameters.blur_noise !== undefined ? parameters.blur_noise : true;
  65617. // Create effects
  65618. _this._createChromaticAberrationPostProcess(ratio);
  65619. _this._createHighlightsPostProcess(ratio);
  65620. _this._createDepthOfFieldPostProcess(ratio / 4);
  65621. // Set up pipeline
  65622. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.LensChromaticAberrationEffect, function () { return _this._chromaticAberrationPostProcess; }, true));
  65623. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.HighlightsEnhancingEffect, function () { return _this._highlightsPostProcess; }, true));
  65624. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.LensDepthOfFieldEffect, function () { return _this._depthOfFieldPostProcess; }, true));
  65625. if (_this._highlightsGain === -1) {
  65626. _this._disableEffect(_this.HighlightsEnhancingEffect, null);
  65627. }
  65628. // Finish
  65629. scene.postProcessRenderPipelineManager.addPipeline(_this);
  65630. if (cameras) {
  65631. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  65632. }
  65633. return _this;
  65634. }
  65635. // public methods (self explanatory)
  65636. LensRenderingPipeline.prototype.setEdgeBlur = function (amount) { this._edgeBlur = amount; };
  65637. LensRenderingPipeline.prototype.disableEdgeBlur = function () { this._edgeBlur = 0; };
  65638. LensRenderingPipeline.prototype.setGrainAmount = function (amount) { this._grainAmount = amount; };
  65639. LensRenderingPipeline.prototype.disableGrain = function () { this._grainAmount = 0; };
  65640. LensRenderingPipeline.prototype.setChromaticAberration = function (amount) { this._chromaticAberration = amount; };
  65641. LensRenderingPipeline.prototype.disableChromaticAberration = function () { this._chromaticAberration = 0; };
  65642. LensRenderingPipeline.prototype.setEdgeDistortion = function (amount) { this._distortion = amount; };
  65643. LensRenderingPipeline.prototype.disableEdgeDistortion = function () { this._distortion = 0; };
  65644. LensRenderingPipeline.prototype.setFocusDistance = function (amount) { this._dofDistance = amount; };
  65645. LensRenderingPipeline.prototype.disableDepthOfField = function () { this._dofDistance = -1; };
  65646. LensRenderingPipeline.prototype.setAperture = function (amount) { this._dofAperture = amount; };
  65647. LensRenderingPipeline.prototype.setDarkenOutOfFocus = function (amount) { this._dofDarken = amount; };
  65648. LensRenderingPipeline.prototype.enablePentagonBokeh = function () {
  65649. this._highlightsPostProcess.updateEffect("#define PENTAGON\n");
  65650. };
  65651. LensRenderingPipeline.prototype.disablePentagonBokeh = function () {
  65652. this._highlightsPostProcess.updateEffect();
  65653. };
  65654. LensRenderingPipeline.prototype.enableNoiseBlur = function () { this._blurNoise = true; };
  65655. LensRenderingPipeline.prototype.disableNoiseBlur = function () { this._blurNoise = false; };
  65656. LensRenderingPipeline.prototype.setHighlightsGain = function (amount) {
  65657. this._highlightsGain = amount;
  65658. };
  65659. LensRenderingPipeline.prototype.setHighlightsThreshold = function (amount) {
  65660. if (this._highlightsGain === -1) {
  65661. this._highlightsGain = 1.0;
  65662. }
  65663. this._highlightsThreshold = amount;
  65664. };
  65665. LensRenderingPipeline.prototype.disableHighlights = function () {
  65666. this._highlightsGain = -1;
  65667. };
  65668. /**
  65669. * Removes the internal pipeline assets and detaches the pipeline from the scene cameras
  65670. */
  65671. LensRenderingPipeline.prototype.dispose = function (disableDepthRender) {
  65672. if (disableDepthRender === void 0) { disableDepthRender = false; }
  65673. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  65674. this._chromaticAberrationPostProcess = null;
  65675. this._highlightsPostProcess = null;
  65676. this._depthOfFieldPostProcess = null;
  65677. this._grainTexture.dispose();
  65678. if (disableDepthRender)
  65679. this._scene.disableDepthRenderer();
  65680. };
  65681. // colors shifting and distortion
  65682. LensRenderingPipeline.prototype._createChromaticAberrationPostProcess = function (ratio) {
  65683. var _this = this;
  65684. this._chromaticAberrationPostProcess = new BABYLON.PostProcess("LensChromaticAberration", "chromaticAberration", ["chromatic_aberration", "screen_width", "screen_height"], // uniforms
  65685. [], // samplers
  65686. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  65687. this._chromaticAberrationPostProcess.onApply = function (effect) {
  65688. effect.setFloat('chromatic_aberration', _this._chromaticAberration);
  65689. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  65690. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  65691. };
  65692. };
  65693. // highlights enhancing
  65694. LensRenderingPipeline.prototype._createHighlightsPostProcess = function (ratio) {
  65695. var _this = this;
  65696. this._highlightsPostProcess = new BABYLON.PostProcess("LensHighlights", "lensHighlights", ["gain", "threshold", "screen_width", "screen_height"], // uniforms
  65697. [], // samplers
  65698. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, this._dofPentagon ? "#define PENTAGON\n" : "");
  65699. this._highlightsPostProcess.onApply = function (effect) {
  65700. effect.setFloat('gain', _this._highlightsGain);
  65701. effect.setFloat('threshold', _this._highlightsThreshold);
  65702. effect.setTextureFromPostProcess("textureSampler", _this._chromaticAberrationPostProcess);
  65703. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  65704. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  65705. };
  65706. };
  65707. // colors shifting and distortion
  65708. LensRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (ratio) {
  65709. var _this = this;
  65710. this._depthOfFieldPostProcess = new BABYLON.PostProcess("LensDepthOfField", "depthOfField", [
  65711. "grain_amount", "blur_noise", "screen_width", "screen_height", "distortion", "dof_enabled",
  65712. "screen_distance", "aperture", "darken", "edge_blur", "highlights", "near", "far"
  65713. ], ["depthSampler", "grainSampler", "highlightsSampler"], ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  65714. this._depthOfFieldPostProcess.onApply = function (effect) {
  65715. effect.setTexture("depthSampler", _this._depthTexture);
  65716. effect.setTexture("grainSampler", _this._grainTexture);
  65717. effect.setTextureFromPostProcess("textureSampler", _this._highlightsPostProcess);
  65718. effect.setTextureFromPostProcess("highlightsSampler", _this._depthOfFieldPostProcess);
  65719. effect.setFloat('grain_amount', _this._grainAmount);
  65720. effect.setBool('blur_noise', _this._blurNoise);
  65721. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  65722. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  65723. effect.setFloat('distortion', _this._distortion);
  65724. effect.setBool('dof_enabled', (_this._dofDistance !== -1));
  65725. effect.setFloat('screen_distance', 1.0 / (0.1 - 1.0 / _this._dofDistance));
  65726. effect.setFloat('aperture', _this._dofAperture);
  65727. effect.setFloat('darken', _this._dofDarken);
  65728. effect.setFloat('edge_blur', _this._edgeBlur);
  65729. effect.setBool('highlights', (_this._highlightsGain !== -1));
  65730. if (_this._scene.activeCamera) {
  65731. effect.setFloat('near', _this._scene.activeCamera.minZ);
  65732. effect.setFloat('far', _this._scene.activeCamera.maxZ);
  65733. }
  65734. };
  65735. };
  65736. // creates a black and white random noise texture, 512x512
  65737. LensRenderingPipeline.prototype._createGrainTexture = function () {
  65738. var size = 512;
  65739. this._grainTexture = new BABYLON.DynamicTexture("LensNoiseTexture", size, this._scene, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  65740. this._grainTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  65741. this._grainTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  65742. var context = this._grainTexture.getContext();
  65743. var rand = function (min, max) {
  65744. return Math.random() * (max - min) + min;
  65745. };
  65746. var value;
  65747. for (var x = 0; x < size; x++) {
  65748. for (var y = 0; y < size; y++) {
  65749. value = Math.floor(rand(0.42, 0.58) * 255);
  65750. context.fillStyle = 'rgb(' + value + ', ' + value + ', ' + value + ')';
  65751. context.fillRect(x, y, 1, 1);
  65752. }
  65753. }
  65754. this._grainTexture.update(false);
  65755. };
  65756. return LensRenderingPipeline;
  65757. }(BABYLON.PostProcessRenderPipeline));
  65758. BABYLON.LensRenderingPipeline = LensRenderingPipeline;
  65759. })(BABYLON || (BABYLON = {}));
  65760. //# sourceMappingURL=babylon.lensRenderingPipeline.js.map
  65761. var BABYLON;
  65762. (function (BABYLON) {
  65763. var StandardRenderingPipeline = /** @class */ (function (_super) {
  65764. __extends(StandardRenderingPipeline, _super);
  65765. /**
  65766. * @constructor
  65767. * @param {string} name - The rendering pipeline name
  65768. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  65769. * @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)
  65770. * @param {BABYLON.PostProcess} originalPostProcess - the custom original color post-process. Must be "reusable". Can be null.
  65771. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  65772. */
  65773. function StandardRenderingPipeline(name, scene, ratio, originalPostProcess, cameras) {
  65774. if (originalPostProcess === void 0) { originalPostProcess = null; }
  65775. var _this = _super.call(this, scene.getEngine(), name) || this;
  65776. _this.downSampleX4PostProcess = null;
  65777. _this.brightPassPostProcess = null;
  65778. _this.blurHPostProcesses = [];
  65779. _this.blurVPostProcesses = [];
  65780. _this.textureAdderPostProcess = null;
  65781. _this.volumetricLightPostProcess = null;
  65782. _this.volumetricLightSmoothXPostProcess = null;
  65783. _this.volumetricLightSmoothYPostProcess = null;
  65784. _this.volumetricLightMergePostProces = null;
  65785. _this.volumetricLightFinalPostProcess = null;
  65786. _this.luminancePostProcess = null;
  65787. _this.luminanceDownSamplePostProcesses = [];
  65788. _this.hdrPostProcess = null;
  65789. _this.textureAdderFinalPostProcess = null;
  65790. _this.lensFlareFinalPostProcess = null;
  65791. _this.hdrFinalPostProcess = null;
  65792. _this.lensFlarePostProcess = null;
  65793. _this.lensFlareComposePostProcess = null;
  65794. _this.motionBlurPostProcess = null;
  65795. _this.depthOfFieldPostProcess = null;
  65796. // Values
  65797. _this.brightThreshold = 1.0;
  65798. _this.blurWidth = 512.0;
  65799. _this.horizontalBlur = false;
  65800. _this.exposure = 1.0;
  65801. _this.lensTexture = null;
  65802. _this.volumetricLightCoefficient = 0.2;
  65803. _this.volumetricLightPower = 4.0;
  65804. _this.volumetricLightBlurScale = 64.0;
  65805. _this.sourceLight = null;
  65806. _this.hdrMinimumLuminance = 1.0;
  65807. _this.hdrDecreaseRate = 0.5;
  65808. _this.hdrIncreaseRate = 0.5;
  65809. _this.lensColorTexture = null;
  65810. _this.lensFlareStrength = 20.0;
  65811. _this.lensFlareGhostDispersal = 1.4;
  65812. _this.lensFlareHaloWidth = 0.7;
  65813. _this.lensFlareDistortionStrength = 16.0;
  65814. _this.lensStarTexture = null;
  65815. _this.lensFlareDirtTexture = null;
  65816. _this.depthOfFieldDistance = 10.0;
  65817. _this.depthOfFieldBlurWidth = 64.0;
  65818. _this.motionStrength = 1.0;
  65819. // IAnimatable
  65820. _this.animations = [];
  65821. _this._currentDepthOfFieldSource = null;
  65822. _this._hdrCurrentLuminance = 1.0;
  65823. // Getters and setters
  65824. _this._bloomEnabled = true;
  65825. _this._depthOfFieldEnabled = false;
  65826. _this._vlsEnabled = false;
  65827. _this._lensFlareEnabled = false;
  65828. _this._hdrEnabled = false;
  65829. _this._motionBlurEnabled = false;
  65830. _this._motionBlurSamples = 64.0;
  65831. _this._volumetricLightStepsCount = 50.0;
  65832. _this._cameras = cameras || [];
  65833. // Initialize
  65834. _this._scene = scene;
  65835. _this._basePostProcess = originalPostProcess;
  65836. _this._ratio = ratio;
  65837. // Misc
  65838. _this._floatTextureType = scene.getEngine().getCaps().textureFloatRender ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  65839. // Finish
  65840. scene.postProcessRenderPipelineManager.addPipeline(_this);
  65841. _this._buildPipeline();
  65842. return _this;
  65843. }
  65844. Object.defineProperty(StandardRenderingPipeline.prototype, "BloomEnabled", {
  65845. get: function () {
  65846. return this._bloomEnabled;
  65847. },
  65848. set: function (enabled) {
  65849. if (this._bloomEnabled === enabled) {
  65850. return;
  65851. }
  65852. this._bloomEnabled = enabled;
  65853. this._buildPipeline();
  65854. },
  65855. enumerable: true,
  65856. configurable: true
  65857. });
  65858. Object.defineProperty(StandardRenderingPipeline.prototype, "DepthOfFieldEnabled", {
  65859. get: function () {
  65860. return this._depthOfFieldEnabled;
  65861. },
  65862. set: function (enabled) {
  65863. if (this._depthOfFieldEnabled === enabled) {
  65864. return;
  65865. }
  65866. this._depthOfFieldEnabled = enabled;
  65867. this._buildPipeline();
  65868. },
  65869. enumerable: true,
  65870. configurable: true
  65871. });
  65872. Object.defineProperty(StandardRenderingPipeline.prototype, "LensFlareEnabled", {
  65873. get: function () {
  65874. return this._lensFlareEnabled;
  65875. },
  65876. set: function (enabled) {
  65877. if (this._lensFlareEnabled === enabled) {
  65878. return;
  65879. }
  65880. this._lensFlareEnabled = enabled;
  65881. this._buildPipeline();
  65882. },
  65883. enumerable: true,
  65884. configurable: true
  65885. });
  65886. Object.defineProperty(StandardRenderingPipeline.prototype, "HDREnabled", {
  65887. get: function () {
  65888. return this._hdrEnabled;
  65889. },
  65890. set: function (enabled) {
  65891. if (this._hdrEnabled === enabled) {
  65892. return;
  65893. }
  65894. this._hdrEnabled = enabled;
  65895. this._buildPipeline();
  65896. },
  65897. enumerable: true,
  65898. configurable: true
  65899. });
  65900. Object.defineProperty(StandardRenderingPipeline.prototype, "VLSEnabled", {
  65901. get: function () {
  65902. return this._vlsEnabled;
  65903. },
  65904. set: function (enabled) {
  65905. if (this._vlsEnabled === enabled) {
  65906. return;
  65907. }
  65908. if (enabled) {
  65909. var geometry = this._scene.enableGeometryBufferRenderer();
  65910. if (!geometry) {
  65911. BABYLON.Tools.Warn("Geometry renderer is not supported, cannot create volumetric lights in Standard Rendering Pipeline");
  65912. return;
  65913. }
  65914. }
  65915. this._vlsEnabled = enabled;
  65916. this._buildPipeline();
  65917. },
  65918. enumerable: true,
  65919. configurable: true
  65920. });
  65921. Object.defineProperty(StandardRenderingPipeline.prototype, "MotionBlurEnabled", {
  65922. get: function () {
  65923. return this._motionBlurEnabled;
  65924. },
  65925. set: function (enabled) {
  65926. if (this._motionBlurEnabled === enabled) {
  65927. return;
  65928. }
  65929. this._motionBlurEnabled = enabled;
  65930. this._buildPipeline();
  65931. },
  65932. enumerable: true,
  65933. configurable: true
  65934. });
  65935. Object.defineProperty(StandardRenderingPipeline.prototype, "volumetricLightStepsCount", {
  65936. get: function () {
  65937. return this._volumetricLightStepsCount;
  65938. },
  65939. set: function (count) {
  65940. if (this.volumetricLightPostProcess) {
  65941. this.volumetricLightPostProcess.updateEffect("#define VLS\n#define NB_STEPS " + count.toFixed(1));
  65942. }
  65943. this._volumetricLightStepsCount = count;
  65944. },
  65945. enumerable: true,
  65946. configurable: true
  65947. });
  65948. Object.defineProperty(StandardRenderingPipeline.prototype, "motionBlurSamples", {
  65949. get: function () {
  65950. return this._motionBlurSamples;
  65951. },
  65952. set: function (samples) {
  65953. if (this.motionBlurPostProcess) {
  65954. this.motionBlurPostProcess.updateEffect("#define MOTION_BLUR\n#define MAX_MOTION_SAMPLES " + samples.toFixed(1));
  65955. }
  65956. this._motionBlurSamples = samples;
  65957. },
  65958. enumerable: true,
  65959. configurable: true
  65960. });
  65961. StandardRenderingPipeline.prototype._buildPipeline = function () {
  65962. var _this = this;
  65963. var ratio = this._ratio;
  65964. var scene = this._scene;
  65965. this._disposePostProcesses();
  65966. this._reset();
  65967. // Create pass post-process
  65968. if (!this._basePostProcess) {
  65969. this.originalPostProcess = new BABYLON.PostProcess("HDRPass", "standard", [], [], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define PASS_POST_PROCESS", this._floatTextureType);
  65970. this.originalPostProcess.onApply = function (effect) {
  65971. _this._currentDepthOfFieldSource = _this.originalPostProcess;
  65972. };
  65973. }
  65974. else {
  65975. this.originalPostProcess = this._basePostProcess;
  65976. }
  65977. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPassPostProcess", function () { return _this.originalPostProcess; }, true));
  65978. this._currentDepthOfFieldSource = this.originalPostProcess;
  65979. if (this._vlsEnabled) {
  65980. // Create volumetric light
  65981. this._createVolumetricLightPostProcess(scene, ratio);
  65982. // Create volumetric light final post-process
  65983. 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);
  65984. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLSFinal", function () { return _this.volumetricLightFinalPostProcess; }, true));
  65985. }
  65986. if (this._bloomEnabled) {
  65987. // Create down sample X4 post-process
  65988. this._createDownSampleX4PostProcess(scene, ratio / 2);
  65989. // Create bright pass post-process
  65990. this._createBrightPassPostProcess(scene, ratio / 2);
  65991. // Create gaussian blur post-processes (down sampling blurs)
  65992. this._createBlurPostProcesses(scene, ratio / 4, 1);
  65993. // Create texture adder post-process
  65994. this._createTextureAdderPostProcess(scene, ratio);
  65995. // Create depth-of-field source post-process
  65996. 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);
  65997. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBaseDepthOfFieldSource", function () { return _this.textureAdderFinalPostProcess; }, true));
  65998. }
  65999. if (this._lensFlareEnabled) {
  66000. // Create lens flare post-process
  66001. this._createLensFlarePostProcess(scene, ratio);
  66002. // Create depth-of-field source post-process post lens-flare and disable it now
  66003. 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);
  66004. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPostLensFlareDepthOfFieldSource", function () { return _this.lensFlareFinalPostProcess; }, true));
  66005. }
  66006. if (this._hdrEnabled) {
  66007. // Create luminance
  66008. this._createLuminancePostProcesses(scene, this._floatTextureType);
  66009. // Create HDR
  66010. this._createHdrPostProcess(scene, ratio);
  66011. // Create depth-of-field source post-process post hdr and disable it now
  66012. 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);
  66013. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPostHDReDepthOfFieldSource", function () { return _this.hdrFinalPostProcess; }, true));
  66014. }
  66015. if (this._depthOfFieldEnabled) {
  66016. // Create gaussian blur used by depth-of-field
  66017. this._createBlurPostProcesses(scene, ratio / 2, 3, "depthOfFieldBlurWidth");
  66018. // Create depth-of-field post-process
  66019. this._createDepthOfFieldPostProcess(scene, ratio);
  66020. }
  66021. if (this._motionBlurEnabled) {
  66022. // Create motion blur post-process
  66023. this._createMotionBlurPostProcess(scene, ratio);
  66024. }
  66025. if (this._cameras !== null) {
  66026. this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name, this._cameras);
  66027. }
  66028. };
  66029. // Down Sample X4 Post-Processs
  66030. StandardRenderingPipeline.prototype._createDownSampleX4PostProcess = function (scene, ratio) {
  66031. var _this = this;
  66032. var downSampleX4Offsets = new Array(32);
  66033. 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);
  66034. this.downSampleX4PostProcess.onApply = function (effect) {
  66035. var id = 0;
  66036. var width = _this.downSampleX4PostProcess.width;
  66037. var height = _this.downSampleX4PostProcess.height;
  66038. for (var i = -2; i < 2; i++) {
  66039. for (var j = -2; j < 2; j++) {
  66040. downSampleX4Offsets[id] = (i + 0.5) * (1.0 / width);
  66041. downSampleX4Offsets[id + 1] = (j + 0.5) * (1.0 / height);
  66042. id += 2;
  66043. }
  66044. }
  66045. effect.setArray2("dsOffsets", downSampleX4Offsets);
  66046. };
  66047. // Add to pipeline
  66048. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDownSampleX4", function () { return _this.downSampleX4PostProcess; }, true));
  66049. };
  66050. // Brightpass Post-Process
  66051. StandardRenderingPipeline.prototype._createBrightPassPostProcess = function (scene, ratio) {
  66052. var _this = this;
  66053. var brightOffsets = new Array(8);
  66054. 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);
  66055. this.brightPassPostProcess.onApply = function (effect) {
  66056. var sU = (1.0 / _this.brightPassPostProcess.width);
  66057. var sV = (1.0 / _this.brightPassPostProcess.height);
  66058. brightOffsets[0] = -0.5 * sU;
  66059. brightOffsets[1] = 0.5 * sV;
  66060. brightOffsets[2] = 0.5 * sU;
  66061. brightOffsets[3] = 0.5 * sV;
  66062. brightOffsets[4] = -0.5 * sU;
  66063. brightOffsets[5] = -0.5 * sV;
  66064. brightOffsets[6] = 0.5 * sU;
  66065. brightOffsets[7] = -0.5 * sV;
  66066. effect.setArray2("dsOffsets", brightOffsets);
  66067. effect.setFloat("brightThreshold", _this.brightThreshold);
  66068. };
  66069. // Add to pipeline
  66070. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBrightPass", function () { return _this.brightPassPostProcess; }, true));
  66071. };
  66072. // Create blur H&V post-processes
  66073. StandardRenderingPipeline.prototype._createBlurPostProcesses = function (scene, ratio, indice, blurWidthKey) {
  66074. var _this = this;
  66075. if (blurWidthKey === void 0) { blurWidthKey = "blurWidth"; }
  66076. var engine = scene.getEngine();
  66077. 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);
  66078. 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);
  66079. blurX.onActivateObservable.add(function () {
  66080. var dw = blurX.width / engine.getRenderWidth();
  66081. blurX.kernel = _this[blurWidthKey] * dw;
  66082. });
  66083. blurY.onActivateObservable.add(function () {
  66084. var dw = blurY.height / engine.getRenderHeight();
  66085. blurY.kernel = _this.horizontalBlur ? 64 * dw : _this[blurWidthKey] * dw;
  66086. });
  66087. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBlurH" + indice, function () { return blurX; }, true));
  66088. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBlurV" + indice, function () { return blurY; }, true));
  66089. this.blurHPostProcesses.push(blurX);
  66090. this.blurVPostProcesses.push(blurY);
  66091. };
  66092. // Create texture adder post-process
  66093. StandardRenderingPipeline.prototype._createTextureAdderPostProcess = function (scene, ratio) {
  66094. var _this = this;
  66095. 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);
  66096. this.textureAdderPostProcess.onApply = function (effect) {
  66097. effect.setTextureFromPostProcess("otherSampler", _this._vlsEnabled ? _this._currentDepthOfFieldSource : _this.originalPostProcess);
  66098. effect.setTexture("lensSampler", _this.lensTexture);
  66099. effect.setFloat("exposure", _this.exposure);
  66100. _this._currentDepthOfFieldSource = _this.textureAdderFinalPostProcess;
  66101. };
  66102. // Add to pipeline
  66103. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRTextureAdder", function () { return _this.textureAdderPostProcess; }, true));
  66104. };
  66105. StandardRenderingPipeline.prototype._createVolumetricLightPostProcess = function (scene, ratio) {
  66106. var _this = this;
  66107. var geometryRenderer = scene.enableGeometryBufferRenderer();
  66108. geometryRenderer.enablePosition = true;
  66109. var geometry = geometryRenderer.getGBuffer();
  66110. // Base post-process
  66111. 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));
  66112. var depthValues = BABYLON.Vector2.Zero();
  66113. this.volumetricLightPostProcess.onApply = function (effect) {
  66114. if (_this.sourceLight && _this.sourceLight.getShadowGenerator() && _this._scene.activeCamera) {
  66115. var generator = _this.sourceLight.getShadowGenerator();
  66116. effect.setTexture("shadowMapSampler", generator.getShadowMap());
  66117. effect.setTexture("positionSampler", geometry.textures[2]);
  66118. effect.setColor3("sunColor", _this.sourceLight.diffuse);
  66119. effect.setVector3("sunDirection", _this.sourceLight.getShadowDirection());
  66120. effect.setVector3("cameraPosition", _this._scene.activeCamera.globalPosition);
  66121. effect.setMatrix("shadowViewProjection", generator.getTransformMatrix());
  66122. effect.setFloat("scatteringCoefficient", _this.volumetricLightCoefficient);
  66123. effect.setFloat("scatteringPower", _this.volumetricLightPower);
  66124. depthValues.x = generator.getLight().getDepthMinZ(_this._scene.activeCamera);
  66125. depthValues.y = generator.getLight().getDepthMaxZ(_this._scene.activeCamera);
  66126. effect.setVector2("depthValues", depthValues);
  66127. }
  66128. };
  66129. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLS", function () { return _this.volumetricLightPostProcess; }, true));
  66130. // Smooth
  66131. this._createBlurPostProcesses(scene, ratio / 4, 0, "volumetricLightBlurScale");
  66132. // Merge
  66133. this.volumetricLightMergePostProces = new BABYLON.PostProcess("HDRVLSMerge", "standard", [], ["originalSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define VLSMERGE");
  66134. this.volumetricLightMergePostProces.onApply = function (effect) {
  66135. effect.setTextureFromPostProcess("originalSampler", _this.originalPostProcess);
  66136. _this._currentDepthOfFieldSource = _this.volumetricLightFinalPostProcess;
  66137. };
  66138. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLSMerge", function () { return _this.volumetricLightMergePostProces; }, true));
  66139. };
  66140. // Create luminance
  66141. StandardRenderingPipeline.prototype._createLuminancePostProcesses = function (scene, textureType) {
  66142. var _this = this;
  66143. // Create luminance
  66144. var size = Math.pow(3, StandardRenderingPipeline.LuminanceSteps);
  66145. this.luminancePostProcess = new BABYLON.PostProcess("HDRLuminance", "standard", ["lumOffsets"], [], { width: size, height: size }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define LUMINANCE", textureType);
  66146. var offsets = [];
  66147. this.luminancePostProcess.onApply = function (effect) {
  66148. var sU = (1.0 / _this.luminancePostProcess.width);
  66149. var sV = (1.0 / _this.luminancePostProcess.height);
  66150. offsets[0] = -0.5 * sU;
  66151. offsets[1] = 0.5 * sV;
  66152. offsets[2] = 0.5 * sU;
  66153. offsets[3] = 0.5 * sV;
  66154. offsets[4] = -0.5 * sU;
  66155. offsets[5] = -0.5 * sV;
  66156. offsets[6] = 0.5 * sU;
  66157. offsets[7] = -0.5 * sV;
  66158. effect.setArray2("lumOffsets", offsets);
  66159. };
  66160. // Add to pipeline
  66161. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLuminance", function () { return _this.luminancePostProcess; }, true));
  66162. // Create down sample luminance
  66163. for (var i = StandardRenderingPipeline.LuminanceSteps - 1; i >= 0; i--) {
  66164. var size = Math.pow(3, i);
  66165. var defines = "#define LUMINANCE_DOWN_SAMPLE\n";
  66166. if (i === 0) {
  66167. defines += "#define FINAL_DOWN_SAMPLER";
  66168. }
  66169. var postProcess = new BABYLON.PostProcess("HDRLuminanceDownSample" + i, "standard", ["dsOffsets", "halfDestPixelSize"], [], { width: size, height: size }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, defines, textureType);
  66170. this.luminanceDownSamplePostProcesses.push(postProcess);
  66171. }
  66172. // Create callbacks and add effects
  66173. var lastLuminance = this.luminancePostProcess;
  66174. this.luminanceDownSamplePostProcesses.forEach(function (pp, index) {
  66175. var downSampleOffsets = new Array(18);
  66176. pp.onApply = function (effect) {
  66177. if (!lastLuminance) {
  66178. return;
  66179. }
  66180. var id = 0;
  66181. for (var x = -1; x < 2; x++) {
  66182. for (var y = -1; y < 2; y++) {
  66183. downSampleOffsets[id] = x / lastLuminance.width;
  66184. downSampleOffsets[id + 1] = y / lastLuminance.height;
  66185. id += 2;
  66186. }
  66187. }
  66188. effect.setArray2("dsOffsets", downSampleOffsets);
  66189. effect.setFloat("halfDestPixelSize", 0.5 / lastLuminance.width);
  66190. if (index === _this.luminanceDownSamplePostProcesses.length - 1) {
  66191. lastLuminance = _this.luminancePostProcess;
  66192. }
  66193. else {
  66194. lastLuminance = pp;
  66195. }
  66196. };
  66197. if (index === _this.luminanceDownSamplePostProcesses.length - 1) {
  66198. pp.onAfterRender = function (effect) {
  66199. var pixel = scene.getEngine().readPixels(0, 0, 1, 1);
  66200. 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);
  66201. _this._hdrCurrentLuminance = (pixel[0] * bit_shift.x + pixel[1] * bit_shift.y + pixel[2] * bit_shift.z + pixel[3] * bit_shift.w) / 100.0;
  66202. };
  66203. }
  66204. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLuminanceDownSample" + index, function () { return pp; }, true));
  66205. });
  66206. };
  66207. // Create HDR post-process
  66208. StandardRenderingPipeline.prototype._createHdrPostProcess = function (scene, ratio) {
  66209. var _this = this;
  66210. 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);
  66211. var outputLiminance = 1;
  66212. var time = 0;
  66213. var lastTime = 0;
  66214. this.hdrPostProcess.onApply = function (effect) {
  66215. effect.setTextureFromPostProcess("textureAdderSampler", _this._currentDepthOfFieldSource);
  66216. time += scene.getEngine().getDeltaTime();
  66217. if (outputLiminance < 0) {
  66218. outputLiminance = _this._hdrCurrentLuminance;
  66219. }
  66220. else {
  66221. var dt = (lastTime - time) / 1000.0;
  66222. if (_this._hdrCurrentLuminance < outputLiminance + _this.hdrDecreaseRate * dt) {
  66223. outputLiminance += _this.hdrDecreaseRate * dt;
  66224. }
  66225. else if (_this._hdrCurrentLuminance > outputLiminance - _this.hdrIncreaseRate * dt) {
  66226. outputLiminance -= _this.hdrIncreaseRate * dt;
  66227. }
  66228. else {
  66229. outputLiminance = _this._hdrCurrentLuminance;
  66230. }
  66231. }
  66232. outputLiminance = BABYLON.Scalar.Clamp(outputLiminance, _this.hdrMinimumLuminance, 1e20);
  66233. effect.setFloat("averageLuminance", outputLiminance);
  66234. lastTime = time;
  66235. _this._currentDepthOfFieldSource = _this.hdrFinalPostProcess;
  66236. };
  66237. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDR", function () { return _this.hdrPostProcess; }, true));
  66238. };
  66239. // Create lens flare post-process
  66240. StandardRenderingPipeline.prototype._createLensFlarePostProcess = function (scene, ratio) {
  66241. var _this = this;
  66242. 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);
  66243. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLensFlare", function () { return _this.lensFlarePostProcess; }, true));
  66244. this._createBlurPostProcesses(scene, ratio / 4, 2);
  66245. 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);
  66246. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLensFlareCompose", function () { return _this.lensFlareComposePostProcess; }, true));
  66247. var resolution = new BABYLON.Vector2(0, 0);
  66248. // Lens flare
  66249. this.lensFlarePostProcess.onApply = function (effect) {
  66250. effect.setTextureFromPostProcess("textureSampler", _this._bloomEnabled ? _this.blurHPostProcesses[0] : _this.originalPostProcess);
  66251. effect.setTexture("lensColorSampler", _this.lensColorTexture);
  66252. effect.setFloat("strength", _this.lensFlareStrength);
  66253. effect.setFloat("ghostDispersal", _this.lensFlareGhostDispersal);
  66254. effect.setFloat("haloWidth", _this.lensFlareHaloWidth);
  66255. // Shift
  66256. resolution.x = _this.lensFlarePostProcess.width;
  66257. resolution.y = _this.lensFlarePostProcess.height;
  66258. effect.setVector2("resolution", resolution);
  66259. effect.setFloat("distortionStrength", _this.lensFlareDistortionStrength);
  66260. };
  66261. // Compose
  66262. 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);
  66263. 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);
  66264. this.lensFlareComposePostProcess.onApply = function (effect) {
  66265. if (!_this._scene.activeCamera) {
  66266. return;
  66267. }
  66268. effect.setTextureFromPostProcess("otherSampler", _this._currentDepthOfFieldSource);
  66269. effect.setTexture("lensDirtSampler", _this.lensFlareDirtTexture);
  66270. effect.setTexture("lensStarSampler", _this.lensStarTexture);
  66271. // Lens start rotation matrix
  66272. var camerax = _this._scene.activeCamera.getViewMatrix().getRow(0);
  66273. var cameraz = _this._scene.activeCamera.getViewMatrix().getRow(2);
  66274. 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));
  66275. camRot *= 4.0;
  66276. 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);
  66277. var lensStarMatrix = scaleBias2.multiply(starRotation).multiply(scaleBias1);
  66278. effect.setMatrix("lensStarMatrix", lensStarMatrix);
  66279. _this._currentDepthOfFieldSource = _this.lensFlareFinalPostProcess;
  66280. };
  66281. };
  66282. // Create depth-of-field post-process
  66283. StandardRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (scene, ratio) {
  66284. var _this = this;
  66285. 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);
  66286. this.depthOfFieldPostProcess.onApply = function (effect) {
  66287. effect.setTextureFromPostProcess("otherSampler", _this._currentDepthOfFieldSource);
  66288. effect.setTexture("depthSampler", _this._getDepthTexture());
  66289. effect.setFloat("distance", _this.depthOfFieldDistance);
  66290. };
  66291. // Add to pipeline
  66292. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDepthOfField", function () { return _this.depthOfFieldPostProcess; }, true));
  66293. };
  66294. // Create motion blur post-process
  66295. StandardRenderingPipeline.prototype._createMotionBlurPostProcess = function (scene, ratio) {
  66296. var _this = this;
  66297. 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);
  66298. var motionScale = 0;
  66299. var prevViewProjection = BABYLON.Matrix.Identity();
  66300. var invViewProjection = BABYLON.Matrix.Identity();
  66301. var viewProjection = BABYLON.Matrix.Identity();
  66302. var screenSize = BABYLON.Vector2.Zero();
  66303. this.motionBlurPostProcess.onApply = function (effect) {
  66304. viewProjection = scene.getProjectionMatrix().multiply(scene.getViewMatrix());
  66305. viewProjection.invertToRef(invViewProjection);
  66306. effect.setMatrix("inverseViewProjection", invViewProjection);
  66307. effect.setMatrix("prevViewProjection", prevViewProjection);
  66308. prevViewProjection = viewProjection;
  66309. screenSize.x = _this.motionBlurPostProcess.width;
  66310. screenSize.y = _this.motionBlurPostProcess.height;
  66311. effect.setVector2("screenSize", screenSize);
  66312. motionScale = scene.getEngine().getFps() / 60.0;
  66313. effect.setFloat("motionScale", motionScale);
  66314. effect.setFloat("motionStrength", _this.motionStrength);
  66315. effect.setTexture("depthSampler", _this._getDepthTexture());
  66316. };
  66317. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRMotionBlur", function () { return _this.motionBlurPostProcess; }, true));
  66318. };
  66319. StandardRenderingPipeline.prototype._getDepthTexture = function () {
  66320. if (this._scene.getEngine().getCaps().drawBuffersExtension) {
  66321. var renderer = this._scene.enableGeometryBufferRenderer();
  66322. return renderer.getGBuffer().textures[0];
  66323. }
  66324. return this._scene.enableDepthRenderer().getDepthMap();
  66325. };
  66326. StandardRenderingPipeline.prototype._disposePostProcesses = function () {
  66327. for (var i = 0; i < this._cameras.length; i++) {
  66328. var camera = this._cameras[i];
  66329. if (this.originalPostProcess) {
  66330. this.originalPostProcess.dispose(camera);
  66331. }
  66332. if (this.downSampleX4PostProcess) {
  66333. this.downSampleX4PostProcess.dispose(camera);
  66334. }
  66335. if (this.brightPassPostProcess) {
  66336. this.brightPassPostProcess.dispose(camera);
  66337. }
  66338. if (this.textureAdderPostProcess) {
  66339. this.textureAdderPostProcess.dispose(camera);
  66340. }
  66341. if (this.textureAdderFinalPostProcess) {
  66342. this.textureAdderFinalPostProcess.dispose(camera);
  66343. }
  66344. if (this.volumetricLightPostProcess) {
  66345. this.volumetricLightPostProcess.dispose(camera);
  66346. }
  66347. if (this.volumetricLightSmoothXPostProcess) {
  66348. this.volumetricLightSmoothXPostProcess.dispose(camera);
  66349. }
  66350. if (this.volumetricLightSmoothYPostProcess) {
  66351. this.volumetricLightSmoothYPostProcess.dispose(camera);
  66352. }
  66353. if (this.volumetricLightMergePostProces) {
  66354. this.volumetricLightMergePostProces.dispose(camera);
  66355. }
  66356. if (this.volumetricLightFinalPostProcess) {
  66357. this.volumetricLightFinalPostProcess.dispose(camera);
  66358. }
  66359. if (this.lensFlarePostProcess) {
  66360. this.lensFlarePostProcess.dispose(camera);
  66361. }
  66362. if (this.lensFlareComposePostProcess) {
  66363. this.lensFlareComposePostProcess.dispose(camera);
  66364. }
  66365. for (var j = 0; j < this.luminanceDownSamplePostProcesses.length; j++) {
  66366. this.luminanceDownSamplePostProcesses[j].dispose(camera);
  66367. }
  66368. if (this.luminancePostProcess) {
  66369. this.luminancePostProcess.dispose(camera);
  66370. }
  66371. if (this.hdrPostProcess) {
  66372. this.hdrPostProcess.dispose(camera);
  66373. }
  66374. if (this.hdrFinalPostProcess) {
  66375. this.hdrFinalPostProcess.dispose(camera);
  66376. }
  66377. if (this.depthOfFieldPostProcess) {
  66378. this.depthOfFieldPostProcess.dispose(camera);
  66379. }
  66380. if (this.motionBlurPostProcess) {
  66381. this.motionBlurPostProcess.dispose(camera);
  66382. }
  66383. for (var j = 0; j < this.blurHPostProcesses.length; j++) {
  66384. this.blurHPostProcesses[j].dispose(camera);
  66385. }
  66386. for (var j = 0; j < this.blurVPostProcesses.length; j++) {
  66387. this.blurVPostProcesses[j].dispose(camera);
  66388. }
  66389. }
  66390. this.originalPostProcess = null;
  66391. this.downSampleX4PostProcess = null;
  66392. this.brightPassPostProcess = null;
  66393. this.textureAdderPostProcess = null;
  66394. this.textureAdderFinalPostProcess = null;
  66395. this.volumetricLightPostProcess = null;
  66396. this.volumetricLightSmoothXPostProcess = null;
  66397. this.volumetricLightSmoothYPostProcess = null;
  66398. this.volumetricLightMergePostProces = null;
  66399. this.volumetricLightFinalPostProcess = null;
  66400. this.lensFlarePostProcess = null;
  66401. this.lensFlareComposePostProcess = null;
  66402. this.luminancePostProcess = null;
  66403. this.hdrPostProcess = null;
  66404. this.hdrFinalPostProcess = null;
  66405. this.depthOfFieldPostProcess = null;
  66406. this.motionBlurPostProcess = null;
  66407. this.luminanceDownSamplePostProcesses = [];
  66408. this.blurHPostProcesses = [];
  66409. this.blurVPostProcesses = [];
  66410. };
  66411. // Dispose
  66412. StandardRenderingPipeline.prototype.dispose = function () {
  66413. this._disposePostProcesses();
  66414. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  66415. _super.prototype.dispose.call(this);
  66416. };
  66417. // Serialize rendering pipeline
  66418. StandardRenderingPipeline.prototype.serialize = function () {
  66419. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  66420. serializationObject.customType = "StandardRenderingPipeline";
  66421. return serializationObject;
  66422. };
  66423. /**
  66424. * Static members
  66425. */
  66426. // Parse serialized pipeline
  66427. StandardRenderingPipeline.Parse = function (source, scene, rootUrl) {
  66428. return BABYLON.SerializationHelper.Parse(function () { return new StandardRenderingPipeline(source._name, scene, source._ratio); }, source, scene, rootUrl);
  66429. };
  66430. // Luminance steps
  66431. StandardRenderingPipeline.LuminanceSteps = 6;
  66432. __decorate([
  66433. BABYLON.serialize()
  66434. ], StandardRenderingPipeline.prototype, "brightThreshold", void 0);
  66435. __decorate([
  66436. BABYLON.serialize()
  66437. ], StandardRenderingPipeline.prototype, "blurWidth", void 0);
  66438. __decorate([
  66439. BABYLON.serialize()
  66440. ], StandardRenderingPipeline.prototype, "horizontalBlur", void 0);
  66441. __decorate([
  66442. BABYLON.serialize()
  66443. ], StandardRenderingPipeline.prototype, "exposure", void 0);
  66444. __decorate([
  66445. BABYLON.serializeAsTexture("lensTexture")
  66446. ], StandardRenderingPipeline.prototype, "lensTexture", void 0);
  66447. __decorate([
  66448. BABYLON.serialize()
  66449. ], StandardRenderingPipeline.prototype, "volumetricLightCoefficient", void 0);
  66450. __decorate([
  66451. BABYLON.serialize()
  66452. ], StandardRenderingPipeline.prototype, "volumetricLightPower", void 0);
  66453. __decorate([
  66454. BABYLON.serialize()
  66455. ], StandardRenderingPipeline.prototype, "volumetricLightBlurScale", void 0);
  66456. __decorate([
  66457. BABYLON.serialize()
  66458. ], StandardRenderingPipeline.prototype, "hdrMinimumLuminance", void 0);
  66459. __decorate([
  66460. BABYLON.serialize()
  66461. ], StandardRenderingPipeline.prototype, "hdrDecreaseRate", void 0);
  66462. __decorate([
  66463. BABYLON.serialize()
  66464. ], StandardRenderingPipeline.prototype, "hdrIncreaseRate", void 0);
  66465. __decorate([
  66466. BABYLON.serializeAsTexture("lensColorTexture")
  66467. ], StandardRenderingPipeline.prototype, "lensColorTexture", void 0);
  66468. __decorate([
  66469. BABYLON.serialize()
  66470. ], StandardRenderingPipeline.prototype, "lensFlareStrength", void 0);
  66471. __decorate([
  66472. BABYLON.serialize()
  66473. ], StandardRenderingPipeline.prototype, "lensFlareGhostDispersal", void 0);
  66474. __decorate([
  66475. BABYLON.serialize()
  66476. ], StandardRenderingPipeline.prototype, "lensFlareHaloWidth", void 0);
  66477. __decorate([
  66478. BABYLON.serialize()
  66479. ], StandardRenderingPipeline.prototype, "lensFlareDistortionStrength", void 0);
  66480. __decorate([
  66481. BABYLON.serializeAsTexture("lensStarTexture")
  66482. ], StandardRenderingPipeline.prototype, "lensStarTexture", void 0);
  66483. __decorate([
  66484. BABYLON.serializeAsTexture("lensFlareDirtTexture")
  66485. ], StandardRenderingPipeline.prototype, "lensFlareDirtTexture", void 0);
  66486. __decorate([
  66487. BABYLON.serialize()
  66488. ], StandardRenderingPipeline.prototype, "depthOfFieldDistance", void 0);
  66489. __decorate([
  66490. BABYLON.serialize()
  66491. ], StandardRenderingPipeline.prototype, "depthOfFieldBlurWidth", void 0);
  66492. __decorate([
  66493. BABYLON.serialize()
  66494. ], StandardRenderingPipeline.prototype, "motionStrength", void 0);
  66495. __decorate([
  66496. BABYLON.serialize()
  66497. ], StandardRenderingPipeline.prototype, "_ratio", void 0);
  66498. __decorate([
  66499. BABYLON.serialize()
  66500. ], StandardRenderingPipeline.prototype, "BloomEnabled", null);
  66501. __decorate([
  66502. BABYLON.serialize()
  66503. ], StandardRenderingPipeline.prototype, "DepthOfFieldEnabled", null);
  66504. __decorate([
  66505. BABYLON.serialize()
  66506. ], StandardRenderingPipeline.prototype, "LensFlareEnabled", null);
  66507. __decorate([
  66508. BABYLON.serialize()
  66509. ], StandardRenderingPipeline.prototype, "HDREnabled", null);
  66510. __decorate([
  66511. BABYLON.serialize()
  66512. ], StandardRenderingPipeline.prototype, "VLSEnabled", null);
  66513. __decorate([
  66514. BABYLON.serialize()
  66515. ], StandardRenderingPipeline.prototype, "MotionBlurEnabled", null);
  66516. __decorate([
  66517. BABYLON.serialize()
  66518. ], StandardRenderingPipeline.prototype, "volumetricLightStepsCount", null);
  66519. __decorate([
  66520. BABYLON.serialize()
  66521. ], StandardRenderingPipeline.prototype, "motionBlurSamples", null);
  66522. return StandardRenderingPipeline;
  66523. }(BABYLON.PostProcessRenderPipeline));
  66524. BABYLON.StandardRenderingPipeline = StandardRenderingPipeline;
  66525. })(BABYLON || (BABYLON = {}));
  66526. //# sourceMappingURL=babylon.standardRenderingPipeline.js.map
  66527. var BABYLON;
  66528. (function (BABYLON) {
  66529. var FxaaPostProcess = /** @class */ (function (_super) {
  66530. __extends(FxaaPostProcess, _super);
  66531. function FxaaPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  66532. if (camera === void 0) { camera = null; }
  66533. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  66534. var _this = _super.call(this, name, "fxaa", ["texelSize"], null, options, camera, samplingMode || BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, reusable, null, textureType, "fxaa") || this;
  66535. _this.onApplyObservable.add(function (effect) {
  66536. var texelSize = _this.texelSize;
  66537. effect.setFloat2("texelSize", texelSize.x, texelSize.y);
  66538. });
  66539. return _this;
  66540. }
  66541. return FxaaPostProcess;
  66542. }(BABYLON.PostProcess));
  66543. BABYLON.FxaaPostProcess = FxaaPostProcess;
  66544. })(BABYLON || (BABYLON = {}));
  66545. //# sourceMappingURL=babylon.fxaaPostProcess.js.map
  66546. var BABYLON;
  66547. (function (BABYLON) {
  66548. /**
  66549. * The CircleOfConfusionPostProcess computes the circle of confusion value for each pixel given required lens parameters. See https://en.wikipedia.org/wiki/Circle_of_confusion
  66550. */
  66551. var CircleOfConfusionPostProcess = /** @class */ (function (_super) {
  66552. __extends(CircleOfConfusionPostProcess, _super);
  66553. /**
  66554. * Creates a new instance of @see CircleOfConfusionPostProcess
  66555. * @param name The name of the effect.
  66556. * @param scene The scene the effect belongs to.
  66557. * @param depthTexture The depth texture of the scene to compute the circle of confusion.
  66558. * @param options The required width/height ratio to downsize to before computing the render pass.
  66559. * @param camera The camera to apply the render pass to.
  66560. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  66561. * @param engine The engine which the post process will be applied. (default: current engine)
  66562. * @param reusable If the post process can be reused on the same frame. (default: false)
  66563. * @param textureType Type of textures used when performing the post process. (default: 0)
  66564. */
  66565. function CircleOfConfusionPostProcess(name, scene, depthTexture, options, camera, samplingMode, engine, reusable, textureType) {
  66566. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  66567. var _this = _super.call(this, name, "circleOfConfusion", ["cameraMinMaxZ", "focusDistance", "cocPrecalculation"], ["depthSampler"], options, camera, samplingMode, engine, reusable, null, textureType) || this;
  66568. /**
  66569. * 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.
  66570. */
  66571. _this.lensSize = 50;
  66572. /**
  66573. * F-Stop of the effect's camera. The diamater of the resulting aperture can be computed by lensSize/fStop. (default: 1.4)
  66574. */
  66575. _this.fStop = 1.4;
  66576. /**
  66577. * Distance away from the camera to focus on in scene units/1000 (eg. millimeter). (default: 2000)
  66578. */
  66579. _this.focusDistance = 2000;
  66580. /**
  66581. * Focal length of the effect's camera in scene units/1000 (eg. millimeter). (default: 50)
  66582. */
  66583. _this.focalLength = 50;
  66584. _this.onApplyObservable.add(function (effect) {
  66585. effect.setTexture("depthSampler", depthTexture);
  66586. // Circle of confusion calculation, See https://developer.nvidia.com/gpugems/GPUGems/gpugems_ch23.html
  66587. var aperture = _this.lensSize / _this.fStop;
  66588. var cocPrecalculation = ((aperture * _this.focalLength) / ((_this.focusDistance - _this.focalLength))); // * ((this.focusDistance - pixelDistance)/pixelDistance) [This part is done in shader]
  66589. effect.setFloat('focusDistance', _this.focusDistance);
  66590. effect.setFloat('cocPrecalculation', cocPrecalculation);
  66591. if (scene.activeCamera) {
  66592. effect.setFloat2('cameraMinMaxZ', scene.activeCamera.minZ, scene.activeCamera.maxZ);
  66593. }
  66594. });
  66595. return _this;
  66596. }
  66597. return CircleOfConfusionPostProcess;
  66598. }(BABYLON.PostProcess));
  66599. BABYLON.CircleOfConfusionPostProcess = CircleOfConfusionPostProcess;
  66600. })(BABYLON || (BABYLON = {}));
  66601. //# sourceMappingURL=babylon.circleOfConfusionPostProcess.js.map
  66602. var BABYLON;
  66603. (function (BABYLON) {
  66604. /**
  66605. * The DepthOfFieldMergePostProcess merges blurred images with the original based on the values of the circle of confusion.
  66606. */
  66607. var DepthOfFieldMergePostProcess = /** @class */ (function (_super) {
  66608. __extends(DepthOfFieldMergePostProcess, _super);
  66609. /**
  66610. * Creates a new instance of @see CircleOfConfusionPostProcess
  66611. * @param name The name of the effect.
  66612. * @param original The non-blurred image to be modified
  66613. * @param circleOfConfusion The circle of confusion post process that will determine how blurred each pixel should become.
  66614. * @param blurSteps Incrimental bluring post processes.
  66615. * @param options The required width/height ratio to downsize to before computing the render pass.
  66616. * @param camera The camera to apply the render pass to.
  66617. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  66618. * @param engine The engine which the post process will be applied. (default: current engine)
  66619. * @param reusable If the post process can be reused on the same frame. (default: false)
  66620. * @param textureType Type of textures used when performing the post process. (default: 0)
  66621. */
  66622. function DepthOfFieldMergePostProcess(name, original, circleOfConfusion, blurSteps, options, camera, samplingMode, engine, reusable, textureType) {
  66623. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  66624. var _this = _super.call(this, name, "depthOfFieldMerge", [], ["circleOfConfusionSampler", "originalSampler", "blurStep1", "blurStep2"], options, camera, samplingMode, engine, reusable, "#define BLUR_LEVEL " + blurSteps.length + "\n", textureType) || this;
  66625. _this.onApplyObservable.add(function (effect) {
  66626. effect.setTextureFromPostProcess("circleOfConfusionSampler", circleOfConfusion);
  66627. effect.setTextureFromPostProcess("originalSampler", original);
  66628. blurSteps.forEach(function (step, index) {
  66629. effect.setTextureFromPostProcess("blurStep" + (index + 1), step);
  66630. });
  66631. });
  66632. return _this;
  66633. }
  66634. return DepthOfFieldMergePostProcess;
  66635. }(BABYLON.PostProcess));
  66636. BABYLON.DepthOfFieldMergePostProcess = DepthOfFieldMergePostProcess;
  66637. })(BABYLON || (BABYLON = {}));
  66638. //# sourceMappingURL=babylon.depthOfFieldMergePostProcess.js.map
  66639. var BABYLON;
  66640. (function (BABYLON) {
  66641. /**
  66642. * Specifies the level of max blur that should be applied when using the depth of field effect
  66643. */
  66644. var DepthOfFieldEffectBlurLevel;
  66645. (function (DepthOfFieldEffectBlurLevel) {
  66646. /**
  66647. * Subtle blur
  66648. */
  66649. DepthOfFieldEffectBlurLevel[DepthOfFieldEffectBlurLevel["Low"] = 0] = "Low";
  66650. /**
  66651. * Medium blur
  66652. */
  66653. DepthOfFieldEffectBlurLevel[DepthOfFieldEffectBlurLevel["Medium"] = 1] = "Medium";
  66654. /**
  66655. * Large blur
  66656. */
  66657. DepthOfFieldEffectBlurLevel[DepthOfFieldEffectBlurLevel["High"] = 2] = "High";
  66658. })(DepthOfFieldEffectBlurLevel = BABYLON.DepthOfFieldEffectBlurLevel || (BABYLON.DepthOfFieldEffectBlurLevel = {}));
  66659. ;
  66660. /**
  66661. * The depth of field effect applies a blur to objects that are closer or further from where the camera is focusing.
  66662. */
  66663. var DepthOfFieldEffect = /** @class */ (function (_super) {
  66664. __extends(DepthOfFieldEffect, _super);
  66665. /**
  66666. * Creates a new instance of @see DepthOfFieldEffect
  66667. * @param scene The scene the effect belongs to.
  66668. * @param pipelineTextureType The type of texture to be used when performing the post processing.
  66669. */
  66670. function DepthOfFieldEffect(scene, blurLevel, pipelineTextureType) {
  66671. if (blurLevel === void 0) { blurLevel = DepthOfFieldEffectBlurLevel.Low; }
  66672. if (pipelineTextureType === void 0) { pipelineTextureType = 0; }
  66673. var _this = _super.call(this, scene.getEngine(), "depth of field", function () {
  66674. // Enable and get current depth map
  66675. var depthMap = scene.enableDepthRenderer().getDepthMap();
  66676. // Circle of confusion value for each pixel is used to determine how much to blur that pixel
  66677. _this._circleOfConfusion = new BABYLON.CircleOfConfusionPostProcess("circleOfConfusion", scene, depthMap, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType);
  66678. // Capture circle of confusion texture
  66679. _this._depthOfFieldPass = new BABYLON.PassPostProcess("depthOfFieldPass", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType);
  66680. _this._depthOfFieldPass.autoClear = false;
  66681. // 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)
  66682. // Blur the image but do not blur on sharp far to near distance changes to avoid bleeding artifacts
  66683. // See section 2.6.2 http://fileadmin.cs.lth.se/cs/education/edan35/lectures/12dof.pdf
  66684. _this._depthOfFieldBlurY = [];
  66685. _this._depthOfFieldBlurX = [];
  66686. var blurCount = 1;
  66687. var kernelSize = 15;
  66688. switch (blurLevel) {
  66689. case DepthOfFieldEffectBlurLevel.High: {
  66690. blurCount = 3;
  66691. kernelSize = 51;
  66692. break;
  66693. }
  66694. case DepthOfFieldEffectBlurLevel.Medium: {
  66695. blurCount = 2;
  66696. kernelSize = 31;
  66697. break;
  66698. }
  66699. default: {
  66700. kernelSize = 15;
  66701. blurCount = 1;
  66702. break;
  66703. }
  66704. }
  66705. var adjustedKernelSize = kernelSize / Math.pow(2, blurCount - 1);
  66706. for (var i = 0; i < blurCount; i++) {
  66707. var blurY = new BABYLON.DepthOfFieldBlurPostProcess("verticle blur", scene, new BABYLON.Vector2(0, 1.0), adjustedKernelSize, 1.0 / Math.pow(2, i), null, _this._depthOfFieldPass, i == 0 ? _this._circleOfConfusion : null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType);
  66708. blurY.autoClear = false;
  66709. var blurX = new BABYLON.DepthOfFieldBlurPostProcess("horizontal blur", scene, new BABYLON.Vector2(1.0, 0), adjustedKernelSize, 1.0 / Math.pow(2, i), null, _this._depthOfFieldPass, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType);
  66710. blurX.autoClear = false;
  66711. _this._depthOfFieldBlurY.push(blurY);
  66712. _this._depthOfFieldBlurX.push(blurX);
  66713. }
  66714. // Merge blurred images with original image based on circleOfConfusion
  66715. _this._depthOfFieldMerge = new BABYLON.DepthOfFieldMergePostProcess("depthOfFieldMerge", _this._circleOfConfusion, _this._depthOfFieldPass, _this._depthOfFieldBlurY.slice(1), 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType);
  66716. _this._depthOfFieldMerge.autoClear = false;
  66717. // Set all post processes on the effect.
  66718. var effects = [_this._circleOfConfusion, _this._depthOfFieldPass];
  66719. for (var i = 0; i < _this._depthOfFieldBlurX.length; i++) {
  66720. effects.push(_this._depthOfFieldBlurY[i]);
  66721. effects.push(_this._depthOfFieldBlurX[i]);
  66722. }
  66723. effects.push(_this._depthOfFieldMerge);
  66724. return effects;
  66725. }, true) || this;
  66726. return _this;
  66727. }
  66728. Object.defineProperty(DepthOfFieldEffect.prototype, "focalLength", {
  66729. get: function () {
  66730. return this._circleOfConfusion.focalLength;
  66731. },
  66732. /**
  66733. * The focal the length of the camera used in the effect
  66734. */
  66735. set: function (value) {
  66736. this._circleOfConfusion.focalLength = value;
  66737. },
  66738. enumerable: true,
  66739. configurable: true
  66740. });
  66741. Object.defineProperty(DepthOfFieldEffect.prototype, "fStop", {
  66742. get: function () {
  66743. return this._circleOfConfusion.fStop;
  66744. },
  66745. /**
  66746. * F-Stop of the effect's camera. The diamater of the resulting aperture can be computed by lensSize/fStop. (default: 1.4)
  66747. */
  66748. set: function (value) {
  66749. this._circleOfConfusion.fStop = value;
  66750. },
  66751. enumerable: true,
  66752. configurable: true
  66753. });
  66754. Object.defineProperty(DepthOfFieldEffect.prototype, "focusDistance", {
  66755. get: function () {
  66756. return this._circleOfConfusion.focusDistance;
  66757. },
  66758. /**
  66759. * Distance away from the camera to focus on in scene units/1000 (eg. millimeter). (default: 2000)
  66760. */
  66761. set: function (value) {
  66762. this._circleOfConfusion.focusDistance = value;
  66763. },
  66764. enumerable: true,
  66765. configurable: true
  66766. });
  66767. Object.defineProperty(DepthOfFieldEffect.prototype, "lensSize", {
  66768. get: function () {
  66769. return this._circleOfConfusion.lensSize;
  66770. },
  66771. /**
  66772. * 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.
  66773. */
  66774. set: function (value) {
  66775. this._circleOfConfusion.lensSize = value;
  66776. },
  66777. enumerable: true,
  66778. configurable: true
  66779. });
  66780. /**
  66781. * Disposes each of the internal effects for a given camera.
  66782. * @param camera The camera to dispose the effect on.
  66783. */
  66784. DepthOfFieldEffect.prototype.disposeEffects = function (camera) {
  66785. this._depthOfFieldPass.dispose(camera);
  66786. this._circleOfConfusion.dispose(camera);
  66787. this._depthOfFieldBlurX.forEach(function (element) {
  66788. element.dispose(camera);
  66789. });
  66790. this._depthOfFieldBlurY.forEach(function (element) {
  66791. element.dispose(camera);
  66792. });
  66793. this._depthOfFieldMerge.dispose(camera);
  66794. };
  66795. return DepthOfFieldEffect;
  66796. }(BABYLON.PostProcessRenderEffect));
  66797. BABYLON.DepthOfFieldEffect = DepthOfFieldEffect;
  66798. })(BABYLON || (BABYLON = {}));
  66799. //# sourceMappingURL=babylon.depthOfFieldEffect.js.map
  66800. var BABYLON;
  66801. (function (BABYLON) {
  66802. /**
  66803. * The default rendering pipeline can be added to a scene to apply common post processing effects such as anti-aliasing or depth of field.
  66804. * See https://doc.babylonjs.com/how_to/using_default_rendering_pipeline
  66805. */
  66806. var DefaultRenderingPipeline = /** @class */ (function (_super) {
  66807. __extends(DefaultRenderingPipeline, _super);
  66808. /**
  66809. * @constructor
  66810. * @param {string} name - The rendering pipeline name
  66811. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  66812. * @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)
  66813. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  66814. * @param {boolean} automaticBuild - if false, you will have to manually call prepare() to update the pipeline
  66815. */
  66816. function DefaultRenderingPipeline(name, hdr, scene, cameras, automaticBuild) {
  66817. if (automaticBuild === void 0) { automaticBuild = true; }
  66818. var _this = _super.call(this, scene.getEngine(), name) || this;
  66819. /**
  66820. * ID of the pass post process used for bloom,
  66821. */
  66822. _this.PassPostProcessId = "PassPostProcessEffect";
  66823. /**
  66824. * ID of the highlight post process used for bloom,
  66825. */
  66826. _this.HighLightsPostProcessId = "HighLightsPostProcessEffect";
  66827. /**
  66828. * ID of the blurX post process used for bloom,
  66829. */
  66830. _this.BlurXPostProcessId = "BlurXPostProcessEffect";
  66831. /**
  66832. * ID of the blurY post process used for bloom,
  66833. */
  66834. _this.BlurYPostProcessId = "BlurYPostProcessEffect";
  66835. /**
  66836. * ID of the copy back post process used for bloom,
  66837. */
  66838. _this.CopyBackPostProcessId = "CopyBackPostProcessEffect";
  66839. /**
  66840. * ID of the image processing post process;
  66841. */
  66842. _this.ImageProcessingPostProcessId = "ImageProcessingPostProcessEffect";
  66843. /**
  66844. * ID of the Fast Approximate Anti-Aliasing post process;
  66845. */
  66846. _this.FxaaPostProcessId = "FxaaPostProcessEffect";
  66847. /**
  66848. * ID of the final merge post process;
  66849. */
  66850. _this.FinalMergePostProcessId = "FinalMergePostProcessEffect";
  66851. /**
  66852. * Animations which can be used to tweak settings over a period of time
  66853. */
  66854. _this.animations = [];
  66855. // Values
  66856. _this._bloomEnabled = false;
  66857. _this._depthOfFieldEnabled = false;
  66858. _this._depthOfFieldBlurLevel = BABYLON.DepthOfFieldEffectBlurLevel.Low;
  66859. _this._fxaaEnabled = false;
  66860. _this._imageProcessingEnabled = true;
  66861. _this._bloomScale = 0.6;
  66862. _this._buildAllowed = true;
  66863. /**
  66864. * Specifies the size of the bloom blur kernel, relative to the final output size
  66865. */
  66866. _this.bloomKernel = 64;
  66867. /**
  66868. * Specifies the weight of the bloom in the final rendering
  66869. */
  66870. _this._bloomWeight = 0.15;
  66871. _this._cameras = cameras || [];
  66872. _this._buildAllowed = automaticBuild;
  66873. // Initialize
  66874. _this._scene = scene;
  66875. var caps = _this._scene.getEngine().getCaps();
  66876. _this._hdr = hdr && (caps.textureHalfFloatRender || caps.textureFloatRender);
  66877. // Misc
  66878. if (_this._hdr) {
  66879. if (caps.textureHalfFloatRender) {
  66880. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  66881. }
  66882. else if (caps.textureFloatRender) {
  66883. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  66884. }
  66885. }
  66886. else {
  66887. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  66888. }
  66889. // Attach
  66890. scene.postProcessRenderPipelineManager.addPipeline(_this);
  66891. _this._buildPipeline();
  66892. return _this;
  66893. }
  66894. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomWeight", {
  66895. get: function () {
  66896. return this._bloomWeight;
  66897. },
  66898. /**
  66899. * The strength of the bloom.
  66900. */
  66901. set: function (value) {
  66902. if (this._bloomWeight === value) {
  66903. return;
  66904. }
  66905. this._bloomWeight = value;
  66906. if (this._hdr && this.copyBack) {
  66907. this.copyBack.alphaConstants = new BABYLON.Color4(value, value, value, value);
  66908. }
  66909. },
  66910. enumerable: true,
  66911. configurable: true
  66912. });
  66913. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomScale", {
  66914. get: function () {
  66915. return this._bloomScale;
  66916. },
  66917. /**
  66918. * The scale of the bloom, lower value will provide better performance.
  66919. */
  66920. set: function (value) {
  66921. if (this._bloomScale === value) {
  66922. return;
  66923. }
  66924. this._bloomScale = value;
  66925. this._buildPipeline();
  66926. },
  66927. enumerable: true,
  66928. configurable: true
  66929. });
  66930. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomEnabled", {
  66931. get: function () {
  66932. return this._bloomEnabled;
  66933. },
  66934. /**
  66935. * Enable or disable the bloom from the pipeline
  66936. */
  66937. set: function (enabled) {
  66938. if (this._bloomEnabled === enabled) {
  66939. return;
  66940. }
  66941. this._bloomEnabled = enabled;
  66942. this._buildPipeline();
  66943. },
  66944. enumerable: true,
  66945. configurable: true
  66946. });
  66947. Object.defineProperty(DefaultRenderingPipeline.prototype, "depthOfFieldEnabled", {
  66948. /**
  66949. * If the depth of field is enabled.
  66950. */
  66951. get: function () {
  66952. return this._depthOfFieldEnabled;
  66953. },
  66954. set: function (enabled) {
  66955. if (this._depthOfFieldEnabled === enabled) {
  66956. return;
  66957. }
  66958. this._depthOfFieldEnabled = enabled;
  66959. this._buildPipeline();
  66960. },
  66961. enumerable: true,
  66962. configurable: true
  66963. });
  66964. Object.defineProperty(DefaultRenderingPipeline.prototype, "depthOfFieldBlurLevel", {
  66965. /**
  66966. * Blur level of the depth of field effect. (Higher blur will effect performance)
  66967. */
  66968. get: function () {
  66969. return this._depthOfFieldBlurLevel;
  66970. },
  66971. set: function (value) {
  66972. if (this._depthOfFieldBlurLevel === value) {
  66973. return;
  66974. }
  66975. this._depthOfFieldBlurLevel = value;
  66976. this._buildPipeline();
  66977. },
  66978. enumerable: true,
  66979. configurable: true
  66980. });
  66981. Object.defineProperty(DefaultRenderingPipeline.prototype, "fxaaEnabled", {
  66982. get: function () {
  66983. return this._fxaaEnabled;
  66984. },
  66985. /**
  66986. * If the anti aliasing is enabled.
  66987. */
  66988. set: function (enabled) {
  66989. if (this._fxaaEnabled === enabled) {
  66990. return;
  66991. }
  66992. this._fxaaEnabled = enabled;
  66993. this._buildPipeline();
  66994. },
  66995. enumerable: true,
  66996. configurable: true
  66997. });
  66998. Object.defineProperty(DefaultRenderingPipeline.prototype, "imageProcessingEnabled", {
  66999. get: function () {
  67000. return this._imageProcessingEnabled;
  67001. },
  67002. /**
  67003. * If image processing is enabled.
  67004. */
  67005. set: function (enabled) {
  67006. if (this._imageProcessingEnabled === enabled) {
  67007. return;
  67008. }
  67009. this._imageProcessingEnabled = enabled;
  67010. this._buildPipeline();
  67011. },
  67012. enumerable: true,
  67013. configurable: true
  67014. });
  67015. /**
  67016. * Force the compilation of the entire pipeline.
  67017. */
  67018. DefaultRenderingPipeline.prototype.prepare = function () {
  67019. var previousState = this._buildAllowed;
  67020. this._buildAllowed = true;
  67021. this._buildPipeline();
  67022. this._buildAllowed = previousState;
  67023. };
  67024. DefaultRenderingPipeline.prototype._buildPipeline = function () {
  67025. var _this = this;
  67026. if (!this._buildAllowed) {
  67027. return;
  67028. }
  67029. var engine = this._scene.getEngine();
  67030. this._disposePostProcesses();
  67031. this._reset();
  67032. if (this.depthOfFieldEnabled) {
  67033. this.depthOfField = new BABYLON.DepthOfFieldEffect(this._scene, this._depthOfFieldBlurLevel, this._defaultPipelineTextureType);
  67034. this.addEffect(this.depthOfField);
  67035. }
  67036. if (this.bloomEnabled) {
  67037. this.pass = new BABYLON.PassPostProcess("sceneRenderTarget", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  67038. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.PassPostProcessId, function () { return _this.pass; }, true));
  67039. if (!this._hdr) {
  67040. this.highlights = new BABYLON.HighlightsPostProcess("highlights", this.bloomScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  67041. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.HighLightsPostProcessId, function () { return _this.highlights; }, true));
  67042. this.highlights.autoClear = false;
  67043. this.highlights.alwaysForcePOT = true;
  67044. }
  67045. 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);
  67046. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.BlurXPostProcessId, function () { return _this.blurX; }, true));
  67047. this.blurX.alwaysForcePOT = true;
  67048. this.blurX.autoClear = false;
  67049. this.blurX.onActivateObservable.add(function () {
  67050. var dw = _this.blurX.width / engine.getRenderWidth(true);
  67051. _this.blurX.kernel = _this.bloomKernel * dw;
  67052. });
  67053. 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);
  67054. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.BlurYPostProcessId, function () { return _this.blurY; }, true));
  67055. this.blurY.alwaysForcePOT = true;
  67056. this.blurY.autoClear = false;
  67057. this.blurY.onActivateObservable.add(function () {
  67058. var dh = _this.blurY.height / engine.getRenderHeight(true);
  67059. _this.blurY.kernel = _this.bloomKernel * dh;
  67060. });
  67061. this.copyBack = new BABYLON.PassPostProcess("bloomBlendBlit", this.bloomScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  67062. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.CopyBackPostProcessId, function () { return _this.copyBack; }, true));
  67063. this.copyBack.alwaysForcePOT = true;
  67064. if (this._hdr) {
  67065. this.copyBack.alphaMode = BABYLON.Engine.ALPHA_INTERPOLATE;
  67066. var w = this.bloomWeight;
  67067. this.copyBack.alphaConstants = new BABYLON.Color4(w, w, w, w);
  67068. }
  67069. else {
  67070. this.copyBack.alphaMode = BABYLON.Engine.ALPHA_SCREENMODE;
  67071. }
  67072. this.copyBack.autoClear = false;
  67073. }
  67074. if (this._imageProcessingEnabled) {
  67075. this.imageProcessing = new BABYLON.ImageProcessingPostProcess("imageProcessing", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  67076. if (this._hdr) {
  67077. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.ImageProcessingPostProcessId, function () { return _this.imageProcessing; }, true));
  67078. }
  67079. else {
  67080. this._scene.imageProcessingConfiguration.applyByPostProcess = false;
  67081. }
  67082. }
  67083. if (this.fxaaEnabled) {
  67084. this.fxaa = new BABYLON.FxaaPostProcess("fxaa", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  67085. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.FxaaPostProcessId, function () { return _this.fxaa; }, true));
  67086. this.fxaa.autoClear = !this.bloomEnabled && (!this._hdr || !this.imageProcessing);
  67087. }
  67088. else if (this._hdr && this.imageProcessing) {
  67089. this.finalMerge = this.imageProcessing;
  67090. }
  67091. else {
  67092. this.finalMerge = new BABYLON.PassPostProcess("finalMerge", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  67093. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.FinalMergePostProcessId, function () { return _this.finalMerge; }, true));
  67094. this.finalMerge.autoClear = !this.bloomEnabled && (!this._hdr || !this.imageProcessing);
  67095. }
  67096. if (this.bloomEnabled) {
  67097. if (this._hdr) {
  67098. this.copyBack.shareOutputWith(this.blurX);
  67099. if (this.imageProcessing) {
  67100. this.imageProcessing.shareOutputWith(this.pass);
  67101. this.imageProcessing.autoClear = false;
  67102. }
  67103. else if (this.fxaa) {
  67104. this.fxaa.shareOutputWith(this.pass);
  67105. }
  67106. else {
  67107. this.finalMerge.shareOutputWith(this.pass);
  67108. }
  67109. }
  67110. else {
  67111. if (this.fxaa) {
  67112. this.fxaa.shareOutputWith(this.pass);
  67113. }
  67114. else {
  67115. this.finalMerge.shareOutputWith(this.pass);
  67116. }
  67117. }
  67118. }
  67119. if (this._cameras !== null) {
  67120. this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name, this._cameras);
  67121. }
  67122. };
  67123. DefaultRenderingPipeline.prototype._disposePostProcesses = function () {
  67124. for (var i = 0; i < this._cameras.length; i++) {
  67125. var camera = this._cameras[i];
  67126. if (this.pass) {
  67127. this.pass.dispose(camera);
  67128. }
  67129. if (this.highlights) {
  67130. this.highlights.dispose(camera);
  67131. }
  67132. if (this.blurX) {
  67133. this.blurX.dispose(camera);
  67134. }
  67135. if (this.blurY) {
  67136. this.blurY.dispose(camera);
  67137. }
  67138. if (this.copyBack) {
  67139. this.copyBack.dispose(camera);
  67140. }
  67141. if (this.imageProcessing) {
  67142. this.imageProcessing.dispose(camera);
  67143. }
  67144. if (this.fxaa) {
  67145. this.fxaa.dispose(camera);
  67146. }
  67147. if (this.finalMerge) {
  67148. this.finalMerge.dispose(camera);
  67149. }
  67150. if (this.depthOfField) {
  67151. this.depthOfField.disposeEffects(camera);
  67152. }
  67153. }
  67154. this.pass = null;
  67155. this.highlights = null;
  67156. this.blurX = null;
  67157. this.blurY = null;
  67158. this.copyBack = null;
  67159. this.imageProcessing = null;
  67160. this.fxaa = null;
  67161. this.finalMerge = null;
  67162. this.depthOfField = null;
  67163. };
  67164. /**
  67165. * Dispose of the pipeline and stop all post processes
  67166. */
  67167. DefaultRenderingPipeline.prototype.dispose = function () {
  67168. this._disposePostProcesses();
  67169. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  67170. _super.prototype.dispose.call(this);
  67171. };
  67172. /**
  67173. * Serialize the rendering pipeline (Used when exporting)
  67174. * @returns the serialized object
  67175. */
  67176. DefaultRenderingPipeline.prototype.serialize = function () {
  67177. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  67178. serializationObject.customType = "DefaultRenderingPipeline";
  67179. return serializationObject;
  67180. };
  67181. /**
  67182. * Parse the serialized pipeline
  67183. * @param source Source pipeline.
  67184. * @param scene The scene to load the pipeline to.
  67185. * @param rootUrl The URL of the serialized pipeline.
  67186. * @returns An instantiated pipeline from the serialized object.
  67187. */
  67188. DefaultRenderingPipeline.Parse = function (source, scene, rootUrl) {
  67189. return BABYLON.SerializationHelper.Parse(function () { return new DefaultRenderingPipeline(source._name, source._name._hdr, scene); }, source, scene, rootUrl);
  67190. };
  67191. __decorate([
  67192. BABYLON.serialize()
  67193. ], DefaultRenderingPipeline.prototype, "bloomKernel", void 0);
  67194. __decorate([
  67195. BABYLON.serialize()
  67196. ], DefaultRenderingPipeline.prototype, "_bloomWeight", void 0);
  67197. __decorate([
  67198. BABYLON.serialize()
  67199. ], DefaultRenderingPipeline.prototype, "_hdr", void 0);
  67200. __decorate([
  67201. BABYLON.serialize()
  67202. ], DefaultRenderingPipeline.prototype, "bloomWeight", null);
  67203. __decorate([
  67204. BABYLON.serialize()
  67205. ], DefaultRenderingPipeline.prototype, "bloomScale", null);
  67206. __decorate([
  67207. BABYLON.serialize()
  67208. ], DefaultRenderingPipeline.prototype, "bloomEnabled", null);
  67209. __decorate([
  67210. BABYLON.serialize()
  67211. ], DefaultRenderingPipeline.prototype, "depthOfFieldEnabled", null);
  67212. __decorate([
  67213. BABYLON.serialize()
  67214. ], DefaultRenderingPipeline.prototype, "depthOfFieldBlurLevel", null);
  67215. __decorate([
  67216. BABYLON.serialize()
  67217. ], DefaultRenderingPipeline.prototype, "fxaaEnabled", null);
  67218. __decorate([
  67219. BABYLON.serialize()
  67220. ], DefaultRenderingPipeline.prototype, "imageProcessingEnabled", null);
  67221. return DefaultRenderingPipeline;
  67222. }(BABYLON.PostProcessRenderPipeline));
  67223. BABYLON.DefaultRenderingPipeline = DefaultRenderingPipeline;
  67224. })(BABYLON || (BABYLON = {}));
  67225. //# sourceMappingURL=babylon.defaultRenderingPipeline.js.map
  67226. var BABYLON;
  67227. (function (BABYLON) {
  67228. /**
  67229. * This renderer is helpfull to fill one of the render target with a geometry buffer.
  67230. */
  67231. var GeometryBufferRenderer = /** @class */ (function () {
  67232. /**
  67233. * Creates a new G Buffer for the scene. @see GeometryBufferRenderer
  67234. * @param scene The scene the buffer belongs to
  67235. * @param ratio How big is the buffer related to the main canvas.
  67236. */
  67237. function GeometryBufferRenderer(scene, ratio) {
  67238. if (ratio === void 0) { ratio = 1; }
  67239. this._enablePosition = false;
  67240. this._scene = scene;
  67241. this._ratio = ratio;
  67242. // Render target
  67243. this._createRenderTargets();
  67244. }
  67245. Object.defineProperty(GeometryBufferRenderer.prototype, "renderList", {
  67246. /**
  67247. * Set the render list (meshes to be rendered) used in the G buffer.
  67248. */
  67249. set: function (meshes) {
  67250. this._multiRenderTarget.renderList = meshes;
  67251. },
  67252. enumerable: true,
  67253. configurable: true
  67254. });
  67255. Object.defineProperty(GeometryBufferRenderer.prototype, "isSupported", {
  67256. /**
  67257. * Gets wether or not G buffer are supported by the running hardware.
  67258. * This requires draw buffer supports
  67259. */
  67260. get: function () {
  67261. return this._multiRenderTarget.isSupported;
  67262. },
  67263. enumerable: true,
  67264. configurable: true
  67265. });
  67266. Object.defineProperty(GeometryBufferRenderer.prototype, "enablePosition", {
  67267. /**
  67268. * Gets wether or not position are enabled for the G buffer.
  67269. */
  67270. get: function () {
  67271. return this._enablePosition;
  67272. },
  67273. /**
  67274. * Sets wether or not position are enabled for the G buffer.
  67275. */
  67276. set: function (enable) {
  67277. this._enablePosition = enable;
  67278. this.dispose();
  67279. this._createRenderTargets();
  67280. },
  67281. enumerable: true,
  67282. configurable: true
  67283. });
  67284. Object.defineProperty(GeometryBufferRenderer.prototype, "scene", {
  67285. /**
  67286. * Gets the scene associated with the buffer.
  67287. */
  67288. get: function () {
  67289. return this._scene;
  67290. },
  67291. enumerable: true,
  67292. configurable: true
  67293. });
  67294. Object.defineProperty(GeometryBufferRenderer.prototype, "ratio", {
  67295. /**
  67296. * Gets the ratio used by the buffer during its creation.
  67297. * How big is the buffer related to the main canvas.
  67298. */
  67299. get: function () {
  67300. return this._ratio;
  67301. },
  67302. enumerable: true,
  67303. configurable: true
  67304. });
  67305. /**
  67306. * Checks wether everything is ready to render a submesh to the G buffer.
  67307. * @param subMesh the submesh to check readiness for
  67308. * @param useInstances is the mesh drawn using instance or not
  67309. * @returns true if ready otherwise false
  67310. */
  67311. GeometryBufferRenderer.prototype.isReady = function (subMesh, useInstances) {
  67312. var material = subMesh.getMaterial();
  67313. if (material && material.disableDepthWrite) {
  67314. return false;
  67315. }
  67316. var defines = [];
  67317. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  67318. var mesh = subMesh.getMesh();
  67319. // Alpha test
  67320. if (material && material.needAlphaTesting()) {
  67321. defines.push("#define ALPHATEST");
  67322. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  67323. attribs.push(BABYLON.VertexBuffer.UVKind);
  67324. defines.push("#define UV1");
  67325. }
  67326. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  67327. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  67328. defines.push("#define UV2");
  67329. }
  67330. }
  67331. // Buffers
  67332. if (this._enablePosition) {
  67333. defines.push("#define POSITION");
  67334. }
  67335. // Bones
  67336. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  67337. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  67338. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  67339. if (mesh.numBoneInfluencers > 4) {
  67340. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  67341. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  67342. }
  67343. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  67344. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  67345. }
  67346. else {
  67347. defines.push("#define NUM_BONE_INFLUENCERS 0");
  67348. }
  67349. // Instances
  67350. if (useInstances) {
  67351. defines.push("#define INSTANCES");
  67352. attribs.push("world0");
  67353. attribs.push("world1");
  67354. attribs.push("world2");
  67355. attribs.push("world3");
  67356. }
  67357. // Get correct effect
  67358. var join = defines.join("\n");
  67359. if (this._cachedDefines !== join) {
  67360. this._cachedDefines = join;
  67361. this._effect = this._scene.getEngine().createEffect("geometry", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "view"], ["diffuseSampler"], join, undefined, undefined, undefined, { buffersCount: this._enablePosition ? 3 : 2 });
  67362. }
  67363. return this._effect.isReady();
  67364. };
  67365. /**
  67366. * Gets the current underlying G Buffer.
  67367. * @returns the buffer
  67368. */
  67369. GeometryBufferRenderer.prototype.getGBuffer = function () {
  67370. return this._multiRenderTarget;
  67371. };
  67372. Object.defineProperty(GeometryBufferRenderer.prototype, "samples", {
  67373. /**
  67374. * Gets the number of samples used to render the buffer (anti aliasing).
  67375. */
  67376. get: function () {
  67377. return this._multiRenderTarget.samples;
  67378. },
  67379. /**
  67380. * Sets the number of samples used to render the buffer (anti aliasing).
  67381. */
  67382. set: function (value) {
  67383. this._multiRenderTarget.samples = value;
  67384. },
  67385. enumerable: true,
  67386. configurable: true
  67387. });
  67388. /**
  67389. * Disposes the renderer and frees up associated resources.
  67390. */
  67391. GeometryBufferRenderer.prototype.dispose = function () {
  67392. this.getGBuffer().dispose();
  67393. };
  67394. GeometryBufferRenderer.prototype._createRenderTargets = function () {
  67395. var _this = this;
  67396. var engine = this._scene.getEngine();
  67397. var count = this._enablePosition ? 3 : 2;
  67398. 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 });
  67399. if (!this.isSupported) {
  67400. return;
  67401. }
  67402. this._multiRenderTarget.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  67403. this._multiRenderTarget.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  67404. this._multiRenderTarget.refreshRate = 1;
  67405. this._multiRenderTarget.renderParticles = false;
  67406. this._multiRenderTarget.renderList = null;
  67407. // set default depth value to 1.0 (far away)
  67408. this._multiRenderTarget.onClearObservable.add(function (engine) {
  67409. engine.clear(new BABYLON.Color4(0.0, 0.0, 0.0, 1.0), true, true, true);
  67410. });
  67411. // Custom render function
  67412. var renderSubMesh = function (subMesh) {
  67413. var mesh = subMesh.getRenderingMesh();
  67414. var scene = _this._scene;
  67415. var engine = scene.getEngine();
  67416. var material = subMesh.getMaterial();
  67417. if (!material) {
  67418. return;
  67419. }
  67420. // Culling
  67421. engine.setState(material.backFaceCulling, 0, false, scene.useRightHandedSystem);
  67422. // Managing instances
  67423. var batch = mesh._getInstancesRenderList(subMesh._id);
  67424. if (batch.mustReturn) {
  67425. return;
  67426. }
  67427. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  67428. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  67429. engine.enableEffect(_this._effect);
  67430. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  67431. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  67432. _this._effect.setMatrix("view", scene.getViewMatrix());
  67433. // Alpha test
  67434. if (material && material.needAlphaTesting()) {
  67435. var alphaTexture = material.getAlphaTestTexture();
  67436. if (alphaTexture) {
  67437. _this._effect.setTexture("diffuseSampler", alphaTexture);
  67438. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  67439. }
  67440. }
  67441. // Bones
  67442. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  67443. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  67444. }
  67445. // Draw
  67446. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  67447. }
  67448. };
  67449. this._multiRenderTarget.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  67450. var index;
  67451. if (depthOnlySubMeshes.length) {
  67452. engine.setColorWrite(false);
  67453. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  67454. renderSubMesh(depthOnlySubMeshes.data[index]);
  67455. }
  67456. engine.setColorWrite(true);
  67457. }
  67458. for (index = 0; index < opaqueSubMeshes.length; index++) {
  67459. renderSubMesh(opaqueSubMeshes.data[index]);
  67460. }
  67461. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  67462. renderSubMesh(alphaTestSubMeshes.data[index]);
  67463. }
  67464. };
  67465. };
  67466. return GeometryBufferRenderer;
  67467. }());
  67468. BABYLON.GeometryBufferRenderer = GeometryBufferRenderer;
  67469. })(BABYLON || (BABYLON = {}));
  67470. //# sourceMappingURL=babylon.geometryBufferRenderer.js.map
  67471. var BABYLON;
  67472. (function (BABYLON) {
  67473. var RefractionPostProcess = /** @class */ (function (_super) {
  67474. __extends(RefractionPostProcess, _super);
  67475. function RefractionPostProcess(name, refractionTextureUrl, color, depth, colorLevel, options, camera, samplingMode, engine, reusable) {
  67476. var _this = _super.call(this, name, "refraction", ["baseColor", "depth", "colorLevel"], ["refractionSampler"], options, camera, samplingMode, engine, reusable) || this;
  67477. _this.color = color;
  67478. _this.depth = depth;
  67479. _this.colorLevel = colorLevel;
  67480. _this._ownRefractionTexture = true;
  67481. _this.onActivateObservable.add(function (cam) {
  67482. _this._refTexture = _this._refTexture || new BABYLON.Texture(refractionTextureUrl, cam.getScene());
  67483. });
  67484. _this.onApplyObservable.add(function (effect) {
  67485. effect.setColor3("baseColor", _this.color);
  67486. effect.setFloat("depth", _this.depth);
  67487. effect.setFloat("colorLevel", _this.colorLevel);
  67488. effect.setTexture("refractionSampler", _this._refTexture);
  67489. });
  67490. return _this;
  67491. }
  67492. Object.defineProperty(RefractionPostProcess.prototype, "refractionTexture", {
  67493. /**
  67494. * Gets or sets the refraction texture
  67495. * Please note that you are responsible for disposing the texture if you set it manually
  67496. */
  67497. get: function () {
  67498. return this._refTexture;
  67499. },
  67500. set: function (value) {
  67501. if (this._refTexture && this._ownRefractionTexture) {
  67502. this._refTexture.dispose();
  67503. }
  67504. this._refTexture = value;
  67505. this._ownRefractionTexture = false;
  67506. },
  67507. enumerable: true,
  67508. configurable: true
  67509. });
  67510. // Methods
  67511. RefractionPostProcess.prototype.dispose = function (camera) {
  67512. if (this._refTexture && this._ownRefractionTexture) {
  67513. this._refTexture.dispose();
  67514. this._refTexture = null;
  67515. }
  67516. _super.prototype.dispose.call(this, camera);
  67517. };
  67518. return RefractionPostProcess;
  67519. }(BABYLON.PostProcess));
  67520. BABYLON.RefractionPostProcess = RefractionPostProcess;
  67521. })(BABYLON || (BABYLON = {}));
  67522. //# sourceMappingURL=babylon.refractionPostProcess.js.map
  67523. var BABYLON;
  67524. (function (BABYLON) {
  67525. var BlackAndWhitePostProcess = /** @class */ (function (_super) {
  67526. __extends(BlackAndWhitePostProcess, _super);
  67527. function BlackAndWhitePostProcess(name, options, camera, samplingMode, engine, reusable) {
  67528. var _this = _super.call(this, name, "blackAndWhite", ["degree"], null, options, camera, samplingMode, engine, reusable) || this;
  67529. _this.degree = 1;
  67530. _this.onApplyObservable.add(function (effect) {
  67531. effect.setFloat("degree", _this.degree);
  67532. });
  67533. return _this;
  67534. }
  67535. return BlackAndWhitePostProcess;
  67536. }(BABYLON.PostProcess));
  67537. BABYLON.BlackAndWhitePostProcess = BlackAndWhitePostProcess;
  67538. })(BABYLON || (BABYLON = {}));
  67539. //# sourceMappingURL=babylon.blackAndWhitePostProcess.js.map
  67540. var BABYLON;
  67541. (function (BABYLON) {
  67542. var ConvolutionPostProcess = /** @class */ (function (_super) {
  67543. __extends(ConvolutionPostProcess, _super);
  67544. function ConvolutionPostProcess(name, kernel, options, camera, samplingMode, engine, reusable) {
  67545. var _this = _super.call(this, name, "convolution", ["kernel", "screenSize"], null, options, camera, samplingMode, engine, reusable) || this;
  67546. _this.kernel = kernel;
  67547. _this.onApply = function (effect) {
  67548. effect.setFloat2("screenSize", _this.width, _this.height);
  67549. effect.setArray("kernel", _this.kernel);
  67550. };
  67551. return _this;
  67552. }
  67553. // Statics
  67554. // Based on http://en.wikipedia.org/wiki/Kernel_(image_processing)
  67555. ConvolutionPostProcess.EdgeDetect0Kernel = [1, 0, -1, 0, 0, 0, -1, 0, 1];
  67556. ConvolutionPostProcess.EdgeDetect1Kernel = [0, 1, 0, 1, -4, 1, 0, 1, 0];
  67557. ConvolutionPostProcess.EdgeDetect2Kernel = [-1, -1, -1, -1, 8, -1, -1, -1, -1];
  67558. ConvolutionPostProcess.SharpenKernel = [0, -1, 0, -1, 5, -1, 0, -1, 0];
  67559. ConvolutionPostProcess.EmbossKernel = [-2, -1, 0, -1, 1, 1, 0, 1, 2];
  67560. ConvolutionPostProcess.GaussianKernel = [0, 1, 0, 1, 1, 1, 0, 1, 0];
  67561. return ConvolutionPostProcess;
  67562. }(BABYLON.PostProcess));
  67563. BABYLON.ConvolutionPostProcess = ConvolutionPostProcess;
  67564. })(BABYLON || (BABYLON = {}));
  67565. //# sourceMappingURL=babylon.convolutionPostProcess.js.map
  67566. var BABYLON;
  67567. (function (BABYLON) {
  67568. var FilterPostProcess = /** @class */ (function (_super) {
  67569. __extends(FilterPostProcess, _super);
  67570. function FilterPostProcess(name, kernelMatrix, options, camera, samplingMode, engine, reusable) {
  67571. var _this = _super.call(this, name, "filter", ["kernelMatrix"], null, options, camera, samplingMode, engine, reusable) || this;
  67572. _this.kernelMatrix = kernelMatrix;
  67573. _this.onApply = function (effect) {
  67574. effect.setMatrix("kernelMatrix", _this.kernelMatrix);
  67575. };
  67576. return _this;
  67577. }
  67578. return FilterPostProcess;
  67579. }(BABYLON.PostProcess));
  67580. BABYLON.FilterPostProcess = FilterPostProcess;
  67581. })(BABYLON || (BABYLON = {}));
  67582. //# sourceMappingURL=babylon.filterPostProcess.js.map
  67583. var BABYLON;
  67584. (function (BABYLON) {
  67585. // Inspired by http://http.developer.nvidia.com/GPUGems3/gpugems3_ch13.html
  67586. var VolumetricLightScatteringPostProcess = /** @class */ (function (_super) {
  67587. __extends(VolumetricLightScatteringPostProcess, _super);
  67588. /**
  67589. * @constructor
  67590. * @param {string} name - The post-process name
  67591. * @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)
  67592. * @param {BABYLON.Camera} camera - The camera that the post-process will be attached to
  67593. * @param {BABYLON.Mesh} mesh - The mesh used to create the light scattering
  67594. * @param {number} samples - The post-process quality, default 100
  67595. * @param {number} samplingMode - The post-process filtering mode
  67596. * @param {BABYLON.Engine} engine - The babylon engine
  67597. * @param {boolean} reusable - If the post-process is reusable
  67598. * @param {BABYLON.Scene} scene - The constructor needs a scene reference to initialize internal components. If "camera" is null (RenderPipelineà, "scene" must be provided
  67599. */
  67600. function VolumetricLightScatteringPostProcess(name, ratio, camera, mesh, samples, samplingMode, engine, reusable, scene) {
  67601. if (samples === void 0) { samples = 100; }
  67602. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  67603. 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;
  67604. _this._screenCoordinates = BABYLON.Vector2.Zero();
  67605. /**
  67606. * Custom position of the mesh. Used if "useCustomMeshPosition" is set to "true"
  67607. * @type {Vector3}
  67608. */
  67609. _this.customMeshPosition = BABYLON.Vector3.Zero();
  67610. /**
  67611. * Set if the post-process should use a custom position for the light source (true) or the internal mesh position (false)
  67612. * @type {boolean}
  67613. */
  67614. _this.useCustomMeshPosition = false;
  67615. /**
  67616. * If the post-process should inverse the light scattering direction
  67617. * @type {boolean}
  67618. */
  67619. _this.invert = true;
  67620. /**
  67621. * Array containing the excluded meshes not rendered in the internal pass
  67622. */
  67623. _this.excludedMeshes = new Array();
  67624. /**
  67625. * Controls the overall intensity of the post-process
  67626. * @type {number}
  67627. */
  67628. _this.exposure = 0.3;
  67629. /**
  67630. * Dissipates each sample's contribution in range [0, 1]
  67631. * @type {number}
  67632. */
  67633. _this.decay = 0.96815;
  67634. /**
  67635. * Controls the overall intensity of each sample
  67636. * @type {number}
  67637. */
  67638. _this.weight = 0.58767;
  67639. /**
  67640. * Controls the density of each sample
  67641. * @type {number}
  67642. */
  67643. _this.density = 0.926;
  67644. scene = ((camera === null) ? scene : camera.getScene()); // parameter "scene" can be null.
  67645. engine = scene.getEngine();
  67646. _this._viewPort = new BABYLON.Viewport(0, 0, 1, 1).toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  67647. // Configure mesh
  67648. _this.mesh = ((mesh !== null) ? mesh : VolumetricLightScatteringPostProcess.CreateDefaultMesh("VolumetricLightScatteringMesh", scene));
  67649. // Configure
  67650. _this._createPass(scene, ratio.passRatio || ratio);
  67651. _this.onActivate = function (camera) {
  67652. if (!_this.isSupported) {
  67653. _this.dispose(camera);
  67654. }
  67655. _this.onActivate = null;
  67656. };
  67657. _this.onApplyObservable.add(function (effect) {
  67658. _this._updateMeshScreenCoordinates(scene);
  67659. effect.setTexture("lightScatteringSampler", _this._volumetricLightScatteringRTT);
  67660. effect.setFloat("exposure", _this.exposure);
  67661. effect.setFloat("decay", _this.decay);
  67662. effect.setFloat("weight", _this.weight);
  67663. effect.setFloat("density", _this.density);
  67664. effect.setVector2("meshPositionOnScreen", _this._screenCoordinates);
  67665. });
  67666. return _this;
  67667. }
  67668. Object.defineProperty(VolumetricLightScatteringPostProcess.prototype, "useDiffuseColor", {
  67669. get: function () {
  67670. BABYLON.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
  67671. return false;
  67672. },
  67673. set: function (useDiffuseColor) {
  67674. BABYLON.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
  67675. },
  67676. enumerable: true,
  67677. configurable: true
  67678. });
  67679. VolumetricLightScatteringPostProcess.prototype.getClassName = function () {
  67680. return "VolumetricLightScatteringPostProcess";
  67681. };
  67682. VolumetricLightScatteringPostProcess.prototype._isReady = function (subMesh, useInstances) {
  67683. var mesh = subMesh.getMesh();
  67684. // Render this.mesh as default
  67685. if (mesh === this.mesh && mesh.material) {
  67686. return mesh.material.isReady(mesh);
  67687. }
  67688. var defines = [];
  67689. var attribs = [BABYLON.VertexBuffer.PositionKind];
  67690. var material = subMesh.getMaterial();
  67691. // Alpha test
  67692. if (material) {
  67693. if (material.needAlphaTesting()) {
  67694. defines.push("#define ALPHATEST");
  67695. }
  67696. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  67697. attribs.push(BABYLON.VertexBuffer.UVKind);
  67698. defines.push("#define UV1");
  67699. }
  67700. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  67701. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  67702. defines.push("#define UV2");
  67703. }
  67704. }
  67705. // Bones
  67706. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  67707. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  67708. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  67709. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  67710. defines.push("#define BonesPerMesh " + (mesh.skeleton ? (mesh.skeleton.bones.length + 1) : 0));
  67711. }
  67712. else {
  67713. defines.push("#define NUM_BONE_INFLUENCERS 0");
  67714. }
  67715. // Instances
  67716. if (useInstances) {
  67717. defines.push("#define INSTANCES");
  67718. attribs.push("world0");
  67719. attribs.push("world1");
  67720. attribs.push("world2");
  67721. attribs.push("world3");
  67722. }
  67723. // Get correct effect
  67724. var join = defines.join("\n");
  67725. if (this._cachedDefines !== join) {
  67726. this._cachedDefines = join;
  67727. this._volumetricLightScatteringPass = mesh.getScene().getEngine().createEffect({ vertexElement: "depth", fragmentElement: "volumetricLightScatteringPass" }, attribs, ["world", "mBones", "viewProjection", "diffuseMatrix"], ["diffuseSampler"], join);
  67728. }
  67729. return this._volumetricLightScatteringPass.isReady();
  67730. };
  67731. /**
  67732. * Sets the new light position for light scattering effect
  67733. * @param {BABYLON.Vector3} The new custom light position
  67734. */
  67735. VolumetricLightScatteringPostProcess.prototype.setCustomMeshPosition = function (position) {
  67736. this.customMeshPosition = position;
  67737. };
  67738. /**
  67739. * Returns the light position for light scattering effect
  67740. * @return {BABYLON.Vector3} The custom light position
  67741. */
  67742. VolumetricLightScatteringPostProcess.prototype.getCustomMeshPosition = function () {
  67743. return this.customMeshPosition;
  67744. };
  67745. /**
  67746. * Disposes the internal assets and detaches the post-process from the camera
  67747. */
  67748. VolumetricLightScatteringPostProcess.prototype.dispose = function (camera) {
  67749. var rttIndex = camera.getScene().customRenderTargets.indexOf(this._volumetricLightScatteringRTT);
  67750. if (rttIndex !== -1) {
  67751. camera.getScene().customRenderTargets.splice(rttIndex, 1);
  67752. }
  67753. this._volumetricLightScatteringRTT.dispose();
  67754. _super.prototype.dispose.call(this, camera);
  67755. };
  67756. /**
  67757. * Returns the render target texture used by the post-process
  67758. * @return {BABYLON.RenderTargetTexture} The render target texture used by the post-process
  67759. */
  67760. VolumetricLightScatteringPostProcess.prototype.getPass = function () {
  67761. return this._volumetricLightScatteringRTT;
  67762. };
  67763. // Private methods
  67764. VolumetricLightScatteringPostProcess.prototype._meshExcluded = function (mesh) {
  67765. if (this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  67766. return true;
  67767. }
  67768. return false;
  67769. };
  67770. VolumetricLightScatteringPostProcess.prototype._createPass = function (scene, ratio) {
  67771. var _this = this;
  67772. var engine = scene.getEngine();
  67773. this._volumetricLightScatteringRTT = new BABYLON.RenderTargetTexture("volumetricLightScatteringMap", { width: engine.getRenderWidth() * ratio, height: engine.getRenderHeight() * ratio }, scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  67774. this._volumetricLightScatteringRTT.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  67775. this._volumetricLightScatteringRTT.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  67776. this._volumetricLightScatteringRTT.renderList = null;
  67777. this._volumetricLightScatteringRTT.renderParticles = false;
  67778. var camera = this.getCamera();
  67779. if (camera) {
  67780. camera.customRenderTargets.push(this._volumetricLightScatteringRTT);
  67781. }
  67782. else {
  67783. scene.customRenderTargets.push(this._volumetricLightScatteringRTT);
  67784. }
  67785. // Custom render function for submeshes
  67786. var renderSubMesh = function (subMesh) {
  67787. var mesh = subMesh.getRenderingMesh();
  67788. if (_this._meshExcluded(mesh)) {
  67789. return;
  67790. }
  67791. var material = subMesh.getMaterial();
  67792. if (!material) {
  67793. return;
  67794. }
  67795. var scene = mesh.getScene();
  67796. var engine = scene.getEngine();
  67797. // Culling
  67798. engine.setState(material.backFaceCulling);
  67799. // Managing instances
  67800. var batch = mesh._getInstancesRenderList(subMesh._id);
  67801. if (batch.mustReturn) {
  67802. return;
  67803. }
  67804. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  67805. if (_this._isReady(subMesh, hardwareInstancedRendering)) {
  67806. var effect = _this._volumetricLightScatteringPass;
  67807. if (mesh === _this.mesh) {
  67808. if (subMesh.effect) {
  67809. effect = subMesh.effect;
  67810. }
  67811. else {
  67812. effect = material.getEffect();
  67813. }
  67814. }
  67815. engine.enableEffect(effect);
  67816. mesh._bind(subMesh, effect, BABYLON.Material.TriangleFillMode);
  67817. if (mesh === _this.mesh) {
  67818. material.bind(mesh.getWorldMatrix(), mesh);
  67819. }
  67820. else {
  67821. _this._volumetricLightScatteringPass.setMatrix("viewProjection", scene.getTransformMatrix());
  67822. // Alpha test
  67823. if (material && material.needAlphaTesting()) {
  67824. var alphaTexture = material.getAlphaTestTexture();
  67825. _this._volumetricLightScatteringPass.setTexture("diffuseSampler", alphaTexture);
  67826. if (alphaTexture) {
  67827. _this._volumetricLightScatteringPass.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  67828. }
  67829. }
  67830. // Bones
  67831. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  67832. _this._volumetricLightScatteringPass.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  67833. }
  67834. }
  67835. // Draw
  67836. mesh._processRendering(subMesh, _this._volumetricLightScatteringPass, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return effect.setMatrix("world", world); });
  67837. }
  67838. };
  67839. // Render target texture callbacks
  67840. var savedSceneClearColor;
  67841. var sceneClearColor = new BABYLON.Color4(0.0, 0.0, 0.0, 1.0);
  67842. this._volumetricLightScatteringRTT.onBeforeRenderObservable.add(function () {
  67843. savedSceneClearColor = scene.clearColor;
  67844. scene.clearColor = sceneClearColor;
  67845. });
  67846. this._volumetricLightScatteringRTT.onAfterRenderObservable.add(function () {
  67847. scene.clearColor = savedSceneClearColor;
  67848. });
  67849. this._volumetricLightScatteringRTT.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  67850. var engine = scene.getEngine();
  67851. var index;
  67852. if (depthOnlySubMeshes.length) {
  67853. engine.setColorWrite(false);
  67854. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  67855. renderSubMesh(depthOnlySubMeshes.data[index]);
  67856. }
  67857. engine.setColorWrite(true);
  67858. }
  67859. for (index = 0; index < opaqueSubMeshes.length; index++) {
  67860. renderSubMesh(opaqueSubMeshes.data[index]);
  67861. }
  67862. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  67863. renderSubMesh(alphaTestSubMeshes.data[index]);
  67864. }
  67865. if (transparentSubMeshes.length) {
  67866. // Sort sub meshes
  67867. for (index = 0; index < transparentSubMeshes.length; index++) {
  67868. var submesh = transparentSubMeshes.data[index];
  67869. var boundingInfo = submesh.getBoundingInfo();
  67870. if (boundingInfo && scene.activeCamera) {
  67871. submesh._alphaIndex = submesh.getMesh().alphaIndex;
  67872. submesh._distanceToCamera = boundingInfo.boundingSphere.centerWorld.subtract(scene.activeCamera.position).length();
  67873. }
  67874. }
  67875. var sortedArray = transparentSubMeshes.data.slice(0, transparentSubMeshes.length);
  67876. sortedArray.sort(function (a, b) {
  67877. // Alpha index first
  67878. if (a._alphaIndex > b._alphaIndex) {
  67879. return 1;
  67880. }
  67881. if (a._alphaIndex < b._alphaIndex) {
  67882. return -1;
  67883. }
  67884. // Then distance to camera
  67885. if (a._distanceToCamera < b._distanceToCamera) {
  67886. return 1;
  67887. }
  67888. if (a._distanceToCamera > b._distanceToCamera) {
  67889. return -1;
  67890. }
  67891. return 0;
  67892. });
  67893. // Render sub meshes
  67894. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  67895. for (index = 0; index < sortedArray.length; index++) {
  67896. renderSubMesh(sortedArray[index]);
  67897. }
  67898. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  67899. }
  67900. };
  67901. };
  67902. VolumetricLightScatteringPostProcess.prototype._updateMeshScreenCoordinates = function (scene) {
  67903. var transform = scene.getTransformMatrix();
  67904. var meshPosition;
  67905. if (this.useCustomMeshPosition) {
  67906. meshPosition = this.customMeshPosition;
  67907. }
  67908. else if (this.attachedNode) {
  67909. meshPosition = this.attachedNode.position;
  67910. }
  67911. else {
  67912. meshPosition = this.mesh.parent ? this.mesh.getAbsolutePosition() : this.mesh.position;
  67913. }
  67914. var pos = BABYLON.Vector3.Project(meshPosition, BABYLON.Matrix.Identity(), transform, this._viewPort);
  67915. this._screenCoordinates.x = pos.x / this._viewPort.width;
  67916. this._screenCoordinates.y = pos.y / this._viewPort.height;
  67917. if (this.invert)
  67918. this._screenCoordinates.y = 1.0 - this._screenCoordinates.y;
  67919. };
  67920. // Static methods
  67921. /**
  67922. * Creates a default mesh for the Volumeric Light Scattering post-process
  67923. * @param {string} The mesh name
  67924. * @param {BABYLON.Scene} The scene where to create the mesh
  67925. * @return {BABYLON.Mesh} the default mesh
  67926. */
  67927. VolumetricLightScatteringPostProcess.CreateDefaultMesh = function (name, scene) {
  67928. var mesh = BABYLON.Mesh.CreatePlane(name, 1, scene);
  67929. mesh.billboardMode = BABYLON.AbstractMesh.BILLBOARDMODE_ALL;
  67930. var material = new BABYLON.StandardMaterial(name + "Material", scene);
  67931. material.emissiveColor = new BABYLON.Color3(1, 1, 1);
  67932. mesh.material = material;
  67933. return mesh;
  67934. };
  67935. __decorate([
  67936. BABYLON.serializeAsVector3()
  67937. ], VolumetricLightScatteringPostProcess.prototype, "customMeshPosition", void 0);
  67938. __decorate([
  67939. BABYLON.serialize()
  67940. ], VolumetricLightScatteringPostProcess.prototype, "useCustomMeshPosition", void 0);
  67941. __decorate([
  67942. BABYLON.serialize()
  67943. ], VolumetricLightScatteringPostProcess.prototype, "invert", void 0);
  67944. __decorate([
  67945. BABYLON.serializeAsMeshReference()
  67946. ], VolumetricLightScatteringPostProcess.prototype, "mesh", void 0);
  67947. __decorate([
  67948. BABYLON.serialize()
  67949. ], VolumetricLightScatteringPostProcess.prototype, "excludedMeshes", void 0);
  67950. __decorate([
  67951. BABYLON.serialize()
  67952. ], VolumetricLightScatteringPostProcess.prototype, "exposure", void 0);
  67953. __decorate([
  67954. BABYLON.serialize()
  67955. ], VolumetricLightScatteringPostProcess.prototype, "decay", void 0);
  67956. __decorate([
  67957. BABYLON.serialize()
  67958. ], VolumetricLightScatteringPostProcess.prototype, "weight", void 0);
  67959. __decorate([
  67960. BABYLON.serialize()
  67961. ], VolumetricLightScatteringPostProcess.prototype, "density", void 0);
  67962. return VolumetricLightScatteringPostProcess;
  67963. }(BABYLON.PostProcess));
  67964. BABYLON.VolumetricLightScatteringPostProcess = VolumetricLightScatteringPostProcess;
  67965. })(BABYLON || (BABYLON = {}));
  67966. //# sourceMappingURL=babylon.volumetricLightScatteringPostProcess.js.map
  67967. //
  67968. // This post-process allows the modification of rendered colors by using
  67969. // a 'look-up table' (LUT). This effect is also called Color Grading.
  67970. //
  67971. // The object needs to be provided an url to a texture containing the color
  67972. // look-up table: the texture must be 256 pixels wide and 16 pixels high.
  67973. // Use an image editing software to tweak the LUT to match your needs.
  67974. //
  67975. // For an example of a color LUT, see here:
  67976. // http://udn.epicgames.com/Three/rsrc/Three/ColorGrading/RGBTable16x1.png
  67977. // For explanations on color grading, see here:
  67978. // http://udn.epicgames.com/Three/ColorGrading.html
  67979. //
  67980. var BABYLON;
  67981. (function (BABYLON) {
  67982. var ColorCorrectionPostProcess = /** @class */ (function (_super) {
  67983. __extends(ColorCorrectionPostProcess, _super);
  67984. function ColorCorrectionPostProcess(name, colorTableUrl, options, camera, samplingMode, engine, reusable) {
  67985. var _this = _super.call(this, name, 'colorCorrection', null, ['colorTable'], options, camera, samplingMode, engine, reusable) || this;
  67986. _this._colorTableTexture = new BABYLON.Texture(colorTableUrl, camera.getScene(), true, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  67987. _this._colorTableTexture.anisotropicFilteringLevel = 1;
  67988. _this._colorTableTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  67989. _this._colorTableTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  67990. _this.onApply = function (effect) {
  67991. effect.setTexture("colorTable", _this._colorTableTexture);
  67992. };
  67993. return _this;
  67994. }
  67995. return ColorCorrectionPostProcess;
  67996. }(BABYLON.PostProcess));
  67997. BABYLON.ColorCorrectionPostProcess = ColorCorrectionPostProcess;
  67998. })(BABYLON || (BABYLON = {}));
  67999. //# sourceMappingURL=babylon.colorCorrectionPostProcess.js.map
  68000. var BABYLON;
  68001. (function (BABYLON) {
  68002. var TonemappingOperator;
  68003. (function (TonemappingOperator) {
  68004. TonemappingOperator[TonemappingOperator["Hable"] = 0] = "Hable";
  68005. TonemappingOperator[TonemappingOperator["Reinhard"] = 1] = "Reinhard";
  68006. TonemappingOperator[TonemappingOperator["HejiDawson"] = 2] = "HejiDawson";
  68007. TonemappingOperator[TonemappingOperator["Photographic"] = 3] = "Photographic";
  68008. })(TonemappingOperator = BABYLON.TonemappingOperator || (BABYLON.TonemappingOperator = {}));
  68009. ;
  68010. var TonemapPostProcess = /** @class */ (function (_super) {
  68011. __extends(TonemapPostProcess, _super);
  68012. function TonemapPostProcess(name, _operator, exposureAdjustment, camera, samplingMode, engine, textureFormat) {
  68013. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  68014. if (textureFormat === void 0) { textureFormat = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  68015. var _this = _super.call(this, name, "tonemap", ["_ExposureAdjustment"], null, 1.0, camera, samplingMode, engine, true, null, textureFormat) || this;
  68016. _this._operator = _operator;
  68017. _this.exposureAdjustment = exposureAdjustment;
  68018. var defines = "#define ";
  68019. if (_this._operator === TonemappingOperator.Hable)
  68020. defines += "HABLE_TONEMAPPING";
  68021. else if (_this._operator === TonemappingOperator.Reinhard)
  68022. defines += "REINHARD_TONEMAPPING";
  68023. else if (_this._operator === TonemappingOperator.HejiDawson)
  68024. defines += "OPTIMIZED_HEJIDAWSON_TONEMAPPING";
  68025. else if (_this._operator === TonemappingOperator.Photographic)
  68026. defines += "PHOTOGRAPHIC_TONEMAPPING";
  68027. //sadly a second call to create the effect.
  68028. _this.updateEffect(defines);
  68029. _this.onApply = function (effect) {
  68030. effect.setFloat("_ExposureAdjustment", _this.exposureAdjustment);
  68031. };
  68032. return _this;
  68033. }
  68034. return TonemapPostProcess;
  68035. }(BABYLON.PostProcess));
  68036. BABYLON.TonemapPostProcess = TonemapPostProcess;
  68037. })(BABYLON || (BABYLON = {}));
  68038. //# sourceMappingURL=babylon.tonemapPostProcess.js.map
  68039. var BABYLON;
  68040. (function (BABYLON) {
  68041. var DisplayPassPostProcess = /** @class */ (function (_super) {
  68042. __extends(DisplayPassPostProcess, _super);
  68043. function DisplayPassPostProcess(name, options, camera, samplingMode, engine, reusable) {
  68044. return _super.call(this, name, "displayPass", ["passSampler"], ["passSampler"], options, camera, samplingMode, engine, reusable) || this;
  68045. }
  68046. return DisplayPassPostProcess;
  68047. }(BABYLON.PostProcess));
  68048. BABYLON.DisplayPassPostProcess = DisplayPassPostProcess;
  68049. })(BABYLON || (BABYLON = {}));
  68050. //# sourceMappingURL=babylon.displayPassPostProcess.js.map
  68051. var BABYLON;
  68052. (function (BABYLON) {
  68053. var HighlightsPostProcess = /** @class */ (function (_super) {
  68054. __extends(HighlightsPostProcess, _super);
  68055. function HighlightsPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  68056. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  68057. return _super.call(this, name, "highlights", null, null, options, camera, samplingMode, engine, reusable, null, textureType) || this;
  68058. }
  68059. return HighlightsPostProcess;
  68060. }(BABYLON.PostProcess));
  68061. BABYLON.HighlightsPostProcess = HighlightsPostProcess;
  68062. })(BABYLON || (BABYLON = {}));
  68063. //# sourceMappingURL=babylon.highlightsPostProcess.js.map
  68064. var BABYLON;
  68065. (function (BABYLON) {
  68066. var ImageProcessingPostProcess = /** @class */ (function (_super) {
  68067. __extends(ImageProcessingPostProcess, _super);
  68068. function ImageProcessingPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, imageProcessingConfiguration) {
  68069. if (camera === void 0) { camera = null; }
  68070. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  68071. var _this = _super.call(this, name, "imageProcessing", [], [], options, camera, samplingMode, engine, reusable, null, textureType, "postprocess", null, true) || this;
  68072. _this._fromLinearSpace = true;
  68073. /**
  68074. * Defines cache preventing GC.
  68075. */
  68076. _this._defines = {
  68077. IMAGEPROCESSING: false,
  68078. VIGNETTE: false,
  68079. VIGNETTEBLENDMODEMULTIPLY: false,
  68080. VIGNETTEBLENDMODEOPAQUE: false,
  68081. TONEMAPPING: false,
  68082. CONTRAST: false,
  68083. COLORCURVES: false,
  68084. COLORGRADING: false,
  68085. COLORGRADING3D: false,
  68086. FROMLINEARSPACE: false,
  68087. SAMPLER3DGREENDEPTH: false,
  68088. SAMPLER3DBGRMAP: false,
  68089. IMAGEPROCESSINGPOSTPROCESS: false,
  68090. EXPOSURE: false,
  68091. };
  68092. // Setup the configuration as forced by the constructor. This would then not force the
  68093. // scene materials output in linear space and let untouched the default forward pass.
  68094. if (imageProcessingConfiguration) {
  68095. imageProcessingConfiguration.applyByPostProcess = true;
  68096. _this._attachImageProcessingConfiguration(imageProcessingConfiguration, true);
  68097. // This will cause the shader to be compiled
  68098. _this.fromLinearSpace = false;
  68099. }
  68100. else {
  68101. _this._attachImageProcessingConfiguration(null, true);
  68102. _this.imageProcessingConfiguration.applyByPostProcess = true;
  68103. }
  68104. _this.onApply = function (effect) {
  68105. _this.imageProcessingConfiguration.bind(effect, _this.aspectRatio);
  68106. };
  68107. return _this;
  68108. }
  68109. Object.defineProperty(ImageProcessingPostProcess.prototype, "imageProcessingConfiguration", {
  68110. /**
  68111. * Gets the image processing configuration used either in this material.
  68112. */
  68113. get: function () {
  68114. return this._imageProcessingConfiguration;
  68115. },
  68116. /**
  68117. * Sets the Default image processing configuration used either in the this material.
  68118. *
  68119. * If sets to null, the scene one is in use.
  68120. */
  68121. set: function (value) {
  68122. this._attachImageProcessingConfiguration(value);
  68123. },
  68124. enumerable: true,
  68125. configurable: true
  68126. });
  68127. /**
  68128. * Attaches a new image processing configuration to the PBR Material.
  68129. * @param configuration
  68130. */
  68131. ImageProcessingPostProcess.prototype._attachImageProcessingConfiguration = function (configuration, doNotBuild) {
  68132. var _this = this;
  68133. if (doNotBuild === void 0) { doNotBuild = false; }
  68134. if (configuration === this._imageProcessingConfiguration) {
  68135. return;
  68136. }
  68137. // Detaches observer.
  68138. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  68139. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  68140. }
  68141. // Pick the scene configuration if needed.
  68142. if (!configuration) {
  68143. var scene = null;
  68144. var engine = this.getEngine();
  68145. var camera = this.getCamera();
  68146. if (camera) {
  68147. scene = camera.getScene();
  68148. }
  68149. else if (engine && engine.scenes) {
  68150. var scenes = engine.scenes;
  68151. scene = scenes[scenes.length - 1];
  68152. }
  68153. else {
  68154. scene = BABYLON.Engine.LastCreatedScene;
  68155. }
  68156. this._imageProcessingConfiguration = scene.imageProcessingConfiguration;
  68157. }
  68158. else {
  68159. this._imageProcessingConfiguration = configuration;
  68160. }
  68161. // Attaches observer.
  68162. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  68163. _this._updateParameters();
  68164. });
  68165. // Ensure the effect will be rebuilt.
  68166. if (!doNotBuild) {
  68167. this._updateParameters();
  68168. }
  68169. };
  68170. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorCurves", {
  68171. /**
  68172. * Gets Color curves setup used in the effect if colorCurvesEnabled is set to true .
  68173. */
  68174. get: function () {
  68175. return this.imageProcessingConfiguration.colorCurves;
  68176. },
  68177. /**
  68178. * Sets Color curves setup used in the effect if colorCurvesEnabled is set to true .
  68179. */
  68180. set: function (value) {
  68181. this.imageProcessingConfiguration.colorCurves = value;
  68182. },
  68183. enumerable: true,
  68184. configurable: true
  68185. });
  68186. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorCurvesEnabled", {
  68187. /**
  68188. * Gets wether the color curves effect is enabled.
  68189. */
  68190. get: function () {
  68191. return this.imageProcessingConfiguration.colorCurvesEnabled;
  68192. },
  68193. /**
  68194. * Sets wether the color curves effect is enabled.
  68195. */
  68196. set: function (value) {
  68197. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  68198. },
  68199. enumerable: true,
  68200. configurable: true
  68201. });
  68202. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorGradingTexture", {
  68203. /**
  68204. * Gets Color grading LUT texture used in the effect if colorGradingEnabled is set to true.
  68205. */
  68206. get: function () {
  68207. return this.imageProcessingConfiguration.colorGradingTexture;
  68208. },
  68209. /**
  68210. * Sets Color grading LUT texture used in the effect if colorGradingEnabled is set to true.
  68211. */
  68212. set: function (value) {
  68213. this.imageProcessingConfiguration.colorGradingTexture = value;
  68214. },
  68215. enumerable: true,
  68216. configurable: true
  68217. });
  68218. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorGradingEnabled", {
  68219. /**
  68220. * Gets wether the color grading effect is enabled.
  68221. */
  68222. get: function () {
  68223. return this.imageProcessingConfiguration.colorGradingEnabled;
  68224. },
  68225. /**
  68226. * Gets wether the color grading effect is enabled.
  68227. */
  68228. set: function (value) {
  68229. this.imageProcessingConfiguration.colorGradingEnabled = value;
  68230. },
  68231. enumerable: true,
  68232. configurable: true
  68233. });
  68234. Object.defineProperty(ImageProcessingPostProcess.prototype, "exposure", {
  68235. /**
  68236. * Gets exposure used in the effect.
  68237. */
  68238. get: function () {
  68239. return this.imageProcessingConfiguration.exposure;
  68240. },
  68241. /**
  68242. * Sets exposure used in the effect.
  68243. */
  68244. set: function (value) {
  68245. this.imageProcessingConfiguration.exposure = value;
  68246. },
  68247. enumerable: true,
  68248. configurable: true
  68249. });
  68250. Object.defineProperty(ImageProcessingPostProcess.prototype, "toneMappingEnabled", {
  68251. /**
  68252. * Gets wether tonemapping is enabled or not.
  68253. */
  68254. get: function () {
  68255. return this._imageProcessingConfiguration.toneMappingEnabled;
  68256. },
  68257. /**
  68258. * Sets wether tonemapping is enabled or not
  68259. */
  68260. set: function (value) {
  68261. this._imageProcessingConfiguration.toneMappingEnabled = value;
  68262. },
  68263. enumerable: true,
  68264. configurable: true
  68265. });
  68266. ;
  68267. ;
  68268. Object.defineProperty(ImageProcessingPostProcess.prototype, "contrast", {
  68269. /**
  68270. * Gets contrast used in the effect.
  68271. */
  68272. get: function () {
  68273. return this.imageProcessingConfiguration.contrast;
  68274. },
  68275. /**
  68276. * Sets contrast used in the effect.
  68277. */
  68278. set: function (value) {
  68279. this.imageProcessingConfiguration.contrast = value;
  68280. },
  68281. enumerable: true,
  68282. configurable: true
  68283. });
  68284. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteStretch", {
  68285. /**
  68286. * Gets Vignette stretch size.
  68287. */
  68288. get: function () {
  68289. return this.imageProcessingConfiguration.vignetteStretch;
  68290. },
  68291. /**
  68292. * Sets Vignette stretch size.
  68293. */
  68294. set: function (value) {
  68295. this.imageProcessingConfiguration.vignetteStretch = value;
  68296. },
  68297. enumerable: true,
  68298. configurable: true
  68299. });
  68300. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCentreX", {
  68301. /**
  68302. * Gets Vignette centre X Offset.
  68303. */
  68304. get: function () {
  68305. return this.imageProcessingConfiguration.vignetteCentreX;
  68306. },
  68307. /**
  68308. * Sets Vignette centre X Offset.
  68309. */
  68310. set: function (value) {
  68311. this.imageProcessingConfiguration.vignetteCentreX = value;
  68312. },
  68313. enumerable: true,
  68314. configurable: true
  68315. });
  68316. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCentreY", {
  68317. /**
  68318. * Gets Vignette centre Y Offset.
  68319. */
  68320. get: function () {
  68321. return this.imageProcessingConfiguration.vignetteCentreY;
  68322. },
  68323. /**
  68324. * Sets Vignette centre Y Offset.
  68325. */
  68326. set: function (value) {
  68327. this.imageProcessingConfiguration.vignetteCentreY = value;
  68328. },
  68329. enumerable: true,
  68330. configurable: true
  68331. });
  68332. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteWeight", {
  68333. /**
  68334. * Gets Vignette weight or intensity of the vignette effect.
  68335. */
  68336. get: function () {
  68337. return this.imageProcessingConfiguration.vignetteWeight;
  68338. },
  68339. /**
  68340. * Sets Vignette weight or intensity of the vignette effect.
  68341. */
  68342. set: function (value) {
  68343. this.imageProcessingConfiguration.vignetteWeight = value;
  68344. },
  68345. enumerable: true,
  68346. configurable: true
  68347. });
  68348. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteColor", {
  68349. /**
  68350. * Gets Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  68351. * if vignetteEnabled is set to true.
  68352. */
  68353. get: function () {
  68354. return this.imageProcessingConfiguration.vignetteColor;
  68355. },
  68356. /**
  68357. * Sets Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  68358. * if vignetteEnabled is set to true.
  68359. */
  68360. set: function (value) {
  68361. this.imageProcessingConfiguration.vignetteColor = value;
  68362. },
  68363. enumerable: true,
  68364. configurable: true
  68365. });
  68366. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCameraFov", {
  68367. /**
  68368. * Gets Camera field of view used by the Vignette effect.
  68369. */
  68370. get: function () {
  68371. return this.imageProcessingConfiguration.vignetteCameraFov;
  68372. },
  68373. /**
  68374. * Sets Camera field of view used by the Vignette effect.
  68375. */
  68376. set: function (value) {
  68377. this.imageProcessingConfiguration.vignetteCameraFov = value;
  68378. },
  68379. enumerable: true,
  68380. configurable: true
  68381. });
  68382. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteBlendMode", {
  68383. /**
  68384. * Gets the vignette blend mode allowing different kind of effect.
  68385. */
  68386. get: function () {
  68387. return this.imageProcessingConfiguration.vignetteBlendMode;
  68388. },
  68389. /**
  68390. * Sets the vignette blend mode allowing different kind of effect.
  68391. */
  68392. set: function (value) {
  68393. this.imageProcessingConfiguration.vignetteBlendMode = value;
  68394. },
  68395. enumerable: true,
  68396. configurable: true
  68397. });
  68398. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteEnabled", {
  68399. /**
  68400. * Gets wether the vignette effect is enabled.
  68401. */
  68402. get: function () {
  68403. return this.imageProcessingConfiguration.vignetteEnabled;
  68404. },
  68405. /**
  68406. * Sets wether the vignette effect is enabled.
  68407. */
  68408. set: function (value) {
  68409. this.imageProcessingConfiguration.vignetteEnabled = value;
  68410. },
  68411. enumerable: true,
  68412. configurable: true
  68413. });
  68414. Object.defineProperty(ImageProcessingPostProcess.prototype, "fromLinearSpace", {
  68415. /**
  68416. * Gets wether the input of the processing is in Gamma or Linear Space.
  68417. */
  68418. get: function () {
  68419. return this._fromLinearSpace;
  68420. },
  68421. /**
  68422. * Sets wether the input of the processing is in Gamma or Linear Space.
  68423. */
  68424. set: function (value) {
  68425. if (this._fromLinearSpace === value) {
  68426. return;
  68427. }
  68428. this._fromLinearSpace = value;
  68429. this._updateParameters();
  68430. },
  68431. enumerable: true,
  68432. configurable: true
  68433. });
  68434. ImageProcessingPostProcess.prototype.getClassName = function () {
  68435. return "ImageProcessingPostProcess";
  68436. };
  68437. ImageProcessingPostProcess.prototype._updateParameters = function () {
  68438. this._defines.FROMLINEARSPACE = this._fromLinearSpace;
  68439. this.imageProcessingConfiguration.prepareDefines(this._defines, true);
  68440. var defines = "";
  68441. for (var define in this._defines) {
  68442. if (this._defines[define]) {
  68443. defines += "#define " + define + ";\r\n";
  68444. }
  68445. }
  68446. var samplers = ["textureSampler"];
  68447. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, this._defines);
  68448. var uniforms = ["scale"];
  68449. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, this._defines);
  68450. this.updateEffect(defines, uniforms, samplers);
  68451. };
  68452. ImageProcessingPostProcess.prototype.dispose = function (camera) {
  68453. _super.prototype.dispose.call(this, camera);
  68454. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  68455. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  68456. }
  68457. this.imageProcessingConfiguration.applyByPostProcess = false;
  68458. };
  68459. __decorate([
  68460. BABYLON.serialize()
  68461. ], ImageProcessingPostProcess.prototype, "_fromLinearSpace", void 0);
  68462. return ImageProcessingPostProcess;
  68463. }(BABYLON.PostProcess));
  68464. BABYLON.ImageProcessingPostProcess = ImageProcessingPostProcess;
  68465. })(BABYLON || (BABYLON = {}));
  68466. //# sourceMappingURL=babylon.imageProcessingPostProcess.js.map
  68467. var BABYLON;
  68468. (function (BABYLON) {
  68469. /**
  68470. * The Blur Post Process which blurs an image based on a kernel and direction.
  68471. * Can be used twice in x and y directions to perform a guassian blur in two passes.
  68472. */
  68473. var BlurPostProcess = /** @class */ (function (_super) {
  68474. __extends(BlurPostProcess, _super);
  68475. /**
  68476. * Creates a new instance of @see BlurPostProcess
  68477. * @param name The name of the effect.
  68478. * @param direction The direction in which to blur the image.
  68479. * @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.
  68480. * @param options The required width/height ratio to downsize to before computing the render pass. (Use 1.0 for full size)
  68481. * @param camera The camera to apply the render pass to.
  68482. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  68483. * @param engine The engine which the post process will be applied. (default: current engine)
  68484. * @param reusable If the post process can be reused on the same frame. (default: false)
  68485. * @param textureType Type of textures used when performing the post process. (default: 0)
  68486. */
  68487. function BlurPostProcess(name, /** The direction in which to blur the image. */ direction, kernel, options, camera, samplingMode, engine, reusable, textureType, defines) {
  68488. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  68489. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  68490. if (defines === void 0) { defines = ""; }
  68491. 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;
  68492. _this.direction = direction;
  68493. _this._packedFloat = false;
  68494. _this._staticDefines = "";
  68495. _this._staticDefines = defines;
  68496. _this.onApplyObservable.add(function (effect) {
  68497. effect.setFloat2('delta', (1 / _this.width) * _this.direction.x, (1 / _this.height) * _this.direction.y);
  68498. });
  68499. _this.kernel = kernel;
  68500. return _this;
  68501. }
  68502. Object.defineProperty(BlurPostProcess.prototype, "kernel", {
  68503. /**
  68504. * Gets the length in pixels of the blur sample region
  68505. */
  68506. get: function () {
  68507. return this._idealKernel;
  68508. },
  68509. /**
  68510. * Sets the length in pixels of the blur sample region
  68511. */
  68512. set: function (v) {
  68513. if (this._idealKernel === v) {
  68514. return;
  68515. }
  68516. v = Math.max(v, 1);
  68517. this._idealKernel = v;
  68518. this._kernel = this._nearestBestKernel(v);
  68519. this._updateParameters();
  68520. },
  68521. enumerable: true,
  68522. configurable: true
  68523. });
  68524. Object.defineProperty(BlurPostProcess.prototype, "packedFloat", {
  68525. /**
  68526. * Gets wether or not the blur is unpacking/repacking floats
  68527. */
  68528. get: function () {
  68529. return this._packedFloat;
  68530. },
  68531. /**
  68532. * Sets wether or not the blur needs to unpack/repack floats
  68533. */
  68534. set: function (v) {
  68535. if (this._packedFloat === v) {
  68536. return;
  68537. }
  68538. this._packedFloat = v;
  68539. this._updateParameters();
  68540. },
  68541. enumerable: true,
  68542. configurable: true
  68543. });
  68544. BlurPostProcess.prototype._updateParameters = function () {
  68545. // Generate sampling offsets and weights
  68546. var N = this._kernel;
  68547. var centerIndex = (N - 1) / 2;
  68548. // Generate Gaussian sampling weights over kernel
  68549. var offsets = [];
  68550. var weights = [];
  68551. var totalWeight = 0;
  68552. for (var i = 0; i < N; i++) {
  68553. var u = i / (N - 1);
  68554. var w = this._gaussianWeight(u * 2.0 - 1);
  68555. offsets[i] = (i - centerIndex);
  68556. weights[i] = w;
  68557. totalWeight += w;
  68558. }
  68559. // Normalize weights
  68560. for (var i = 0; i < weights.length; i++) {
  68561. weights[i] /= totalWeight;
  68562. }
  68563. // Optimize: combine samples to take advantage of hardware linear sampling
  68564. // Walk from left to center, combining pairs (symmetrically)
  68565. var linearSamplingWeights = [];
  68566. var linearSamplingOffsets = [];
  68567. var linearSamplingMap = [];
  68568. for (var i = 0; i <= centerIndex; i += 2) {
  68569. var j = Math.min(i + 1, Math.floor(centerIndex));
  68570. var singleCenterSample = i === j;
  68571. if (singleCenterSample) {
  68572. linearSamplingMap.push({ o: offsets[i], w: weights[i] });
  68573. }
  68574. else {
  68575. var sharedCell = j === centerIndex;
  68576. var weightLinear = (weights[i] + weights[j] * (sharedCell ? .5 : 1.));
  68577. var offsetLinear = offsets[i] + 1 / (1 + weights[i] / weights[j]);
  68578. if (offsetLinear === 0) {
  68579. linearSamplingMap.push({ o: offsets[i], w: weights[i] });
  68580. linearSamplingMap.push({ o: offsets[i + 1], w: weights[i + 1] });
  68581. }
  68582. else {
  68583. linearSamplingMap.push({ o: offsetLinear, w: weightLinear });
  68584. linearSamplingMap.push({ o: -offsetLinear, w: weightLinear });
  68585. }
  68586. }
  68587. }
  68588. for (var i = 0; i < linearSamplingMap.length; i++) {
  68589. linearSamplingOffsets[i] = linearSamplingMap[i].o;
  68590. linearSamplingWeights[i] = linearSamplingMap[i].w;
  68591. }
  68592. // Replace with optimized
  68593. offsets = linearSamplingOffsets;
  68594. weights = linearSamplingWeights;
  68595. // Generate shaders
  68596. var maxVaryingRows = this.getEngine().getCaps().maxVaryingVectors;
  68597. var freeVaryingVec2 = Math.max(maxVaryingRows, 0.) - 1; // Because of sampleCenter
  68598. var varyingCount = Math.min(offsets.length, freeVaryingVec2);
  68599. var defines = "";
  68600. defines += this._staticDefines;
  68601. for (var i = 0; i < varyingCount; i++) {
  68602. defines += "#define KERNEL_OFFSET" + i + " " + this._glslFloat(offsets[i]) + "\r\n";
  68603. defines += "#define KERNEL_WEIGHT" + i + " " + this._glslFloat(weights[i]) + "\r\n";
  68604. }
  68605. var depCount = 0;
  68606. for (var i = freeVaryingVec2; i < offsets.length; i++) {
  68607. defines += "#define KERNEL_DEP_OFFSET" + depCount + " " + this._glslFloat(offsets[i]) + "\r\n";
  68608. defines += "#define KERNEL_DEP_WEIGHT" + depCount + " " + this._glslFloat(weights[i]) + "\r\n";
  68609. depCount++;
  68610. }
  68611. if (this.packedFloat) {
  68612. defines += "#define PACKEDFLOAT 1";
  68613. }
  68614. this.updateEffect(defines, null, null, {
  68615. varyingCount: varyingCount,
  68616. depCount: depCount
  68617. });
  68618. };
  68619. /**
  68620. * Best kernels are odd numbers that when divided by 2, their integer part is even, so 5, 9 or 13.
  68621. * Other odd kernels optimize correctly but require proportionally more samples, even kernels are
  68622. * possible but will produce minor visual artifacts. Since each new kernel requires a new shader we
  68623. * want to minimize kernel changes, having gaps between physical kernels is helpful in that regard.
  68624. * The gaps between physical kernels are compensated for in the weighting of the samples
  68625. * @param idealKernel Ideal blur kernel.
  68626. * @return Nearest best kernel.
  68627. */
  68628. BlurPostProcess.prototype._nearestBestKernel = function (idealKernel) {
  68629. var v = Math.round(idealKernel);
  68630. for (var _i = 0, _a = [v, v - 1, v + 1, v - 2, v + 2]; _i < _a.length; _i++) {
  68631. var k = _a[_i];
  68632. if (((k % 2) !== 0) && ((Math.floor(k / 2) % 2) === 0) && k > 0) {
  68633. return Math.max(k, 3);
  68634. }
  68635. }
  68636. return Math.max(v, 3);
  68637. };
  68638. /**
  68639. * Calculates the value of a Gaussian distribution with sigma 3 at a given point.
  68640. * @param x The point on the Gaussian distribution to sample.
  68641. * @return the value of the Gaussian function at x.
  68642. */
  68643. BlurPostProcess.prototype._gaussianWeight = function (x) {
  68644. //reference: Engine/ImageProcessingBlur.cpp #dcc760
  68645. // We are evaluating the Gaussian (normal) distribution over a kernel parameter space of [-1,1],
  68646. // so we truncate at three standard deviations by setting stddev (sigma) to 1/3.
  68647. // The choice of 3-sigma truncation is common but arbitrary, and means that the signal is
  68648. // truncated at around 1.3% of peak strength.
  68649. //the distribution is scaled to account for the difference between the actual kernel size and the requested kernel size
  68650. var sigma = (1 / 3);
  68651. var denominator = Math.sqrt(2.0 * Math.PI) * sigma;
  68652. var exponent = -((x * x) / (2.0 * sigma * sigma));
  68653. var weight = (1.0 / denominator) * Math.exp(exponent);
  68654. return weight;
  68655. };
  68656. /**
  68657. * Generates a string that can be used as a floating point number in GLSL.
  68658. * @param x Value to print.
  68659. * @param decimalFigures Number of decimal places to print the number to (excluding trailing 0s).
  68660. * @return GLSL float string.
  68661. */
  68662. BlurPostProcess.prototype._glslFloat = function (x, decimalFigures) {
  68663. if (decimalFigures === void 0) { decimalFigures = 8; }
  68664. return x.toFixed(decimalFigures).replace(/0+$/, '');
  68665. };
  68666. return BlurPostProcess;
  68667. }(BABYLON.PostProcess));
  68668. BABYLON.BlurPostProcess = BlurPostProcess;
  68669. })(BABYLON || (BABYLON = {}));
  68670. //# sourceMappingURL=babylon.blurPostProcess.js.map
  68671. var BABYLON;
  68672. (function (BABYLON) {
  68673. var Bone = /** @class */ (function (_super) {
  68674. __extends(Bone, _super);
  68675. function Bone(name, skeleton, parentBone, localMatrix, restPose, baseMatrix, index) {
  68676. if (parentBone === void 0) { parentBone = null; }
  68677. if (localMatrix === void 0) { localMatrix = null; }
  68678. if (restPose === void 0) { restPose = null; }
  68679. if (baseMatrix === void 0) { baseMatrix = null; }
  68680. if (index === void 0) { index = null; }
  68681. var _this = _super.call(this, name, skeleton.getScene()) || this;
  68682. _this.name = name;
  68683. _this.children = new Array();
  68684. _this.animations = new Array();
  68685. // Set this value to map this bone to a different index in the transform matrices.
  68686. // Set this value to -1 to exclude the bone from the transform matrices.
  68687. _this._index = null;
  68688. _this._worldTransform = new BABYLON.Matrix();
  68689. _this._absoluteTransform = new BABYLON.Matrix();
  68690. _this._invertedAbsoluteTransform = new BABYLON.Matrix();
  68691. _this._scaleMatrix = BABYLON.Matrix.Identity();
  68692. _this._scaleVector = BABYLON.Vector3.One();
  68693. _this._negateScaleChildren = BABYLON.Vector3.One();
  68694. _this._scalingDeterminant = 1;
  68695. _this._skeleton = skeleton;
  68696. _this._localMatrix = localMatrix ? localMatrix : BABYLON.Matrix.Identity();
  68697. _this._restPose = restPose ? restPose : _this._localMatrix.clone();
  68698. _this._baseMatrix = baseMatrix ? baseMatrix : _this._localMatrix.clone();
  68699. _this._index = index;
  68700. skeleton.bones.push(_this);
  68701. _this.setParent(parentBone, false);
  68702. _this._updateDifferenceMatrix();
  68703. return _this;
  68704. }
  68705. Object.defineProperty(Bone.prototype, "_matrix", {
  68706. get: function () {
  68707. return this._localMatrix;
  68708. },
  68709. set: function (val) {
  68710. if (this._localMatrix) {
  68711. this._localMatrix.copyFrom(val);
  68712. }
  68713. else {
  68714. this._localMatrix = val;
  68715. }
  68716. },
  68717. enumerable: true,
  68718. configurable: true
  68719. });
  68720. // Members
  68721. Bone.prototype.getSkeleton = function () {
  68722. return this._skeleton;
  68723. };
  68724. Bone.prototype.getParent = function () {
  68725. return this._parent;
  68726. };
  68727. Bone.prototype.setParent = function (parent, updateDifferenceMatrix) {
  68728. if (updateDifferenceMatrix === void 0) { updateDifferenceMatrix = true; }
  68729. if (this._parent === parent) {
  68730. return;
  68731. }
  68732. if (this._parent) {
  68733. var index = this._parent.children.indexOf(this);
  68734. if (index !== -1) {
  68735. this._parent.children.splice(index, 1);
  68736. }
  68737. }
  68738. this._parent = parent;
  68739. if (this._parent) {
  68740. this._parent.children.push(this);
  68741. }
  68742. if (updateDifferenceMatrix) {
  68743. this._updateDifferenceMatrix();
  68744. }
  68745. };
  68746. Bone.prototype.getLocalMatrix = function () {
  68747. return this._localMatrix;
  68748. };
  68749. Bone.prototype.getBaseMatrix = function () {
  68750. return this._baseMatrix;
  68751. };
  68752. Bone.prototype.getRestPose = function () {
  68753. return this._restPose;
  68754. };
  68755. Bone.prototype.returnToRest = function () {
  68756. this.updateMatrix(this._restPose.clone());
  68757. };
  68758. Bone.prototype.getWorldMatrix = function () {
  68759. return this._worldTransform;
  68760. };
  68761. Bone.prototype.getInvertedAbsoluteTransform = function () {
  68762. return this._invertedAbsoluteTransform;
  68763. };
  68764. Bone.prototype.getAbsoluteTransform = function () {
  68765. return this._absoluteTransform;
  68766. };
  68767. Object.defineProperty(Bone.prototype, "position", {
  68768. // Properties (matches AbstractMesh properties)
  68769. get: function () {
  68770. return this.getPosition();
  68771. },
  68772. set: function (newPosition) {
  68773. this.setPosition(newPosition);
  68774. },
  68775. enumerable: true,
  68776. configurable: true
  68777. });
  68778. Object.defineProperty(Bone.prototype, "rotation", {
  68779. get: function () {
  68780. return this.getRotation();
  68781. },
  68782. set: function (newRotation) {
  68783. this.setRotation(newRotation);
  68784. },
  68785. enumerable: true,
  68786. configurable: true
  68787. });
  68788. Object.defineProperty(Bone.prototype, "rotationQuaternion", {
  68789. get: function () {
  68790. return this.getRotationQuaternion();
  68791. },
  68792. set: function (newRotation) {
  68793. this.setRotationQuaternion(newRotation);
  68794. },
  68795. enumerable: true,
  68796. configurable: true
  68797. });
  68798. Object.defineProperty(Bone.prototype, "scaling", {
  68799. get: function () {
  68800. return this.getScale();
  68801. },
  68802. set: function (newScaling) {
  68803. this.setScale(newScaling.x, newScaling.y, newScaling.z);
  68804. },
  68805. enumerable: true,
  68806. configurable: true
  68807. });
  68808. // Methods
  68809. Bone.prototype.updateMatrix = function (matrix, updateDifferenceMatrix) {
  68810. if (updateDifferenceMatrix === void 0) { updateDifferenceMatrix = true; }
  68811. this._baseMatrix = matrix.clone();
  68812. this._localMatrix = matrix.clone();
  68813. this._skeleton._markAsDirty();
  68814. if (updateDifferenceMatrix) {
  68815. this._updateDifferenceMatrix();
  68816. }
  68817. };
  68818. Bone.prototype._updateDifferenceMatrix = function (rootMatrix) {
  68819. if (!rootMatrix) {
  68820. rootMatrix = this._baseMatrix;
  68821. }
  68822. if (this._parent) {
  68823. rootMatrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  68824. }
  68825. else {
  68826. this._absoluteTransform.copyFrom(rootMatrix);
  68827. }
  68828. this._absoluteTransform.invertToRef(this._invertedAbsoluteTransform);
  68829. for (var index = 0; index < this.children.length; index++) {
  68830. this.children[index]._updateDifferenceMatrix();
  68831. }
  68832. this._scalingDeterminant = (this._absoluteTransform.determinant() < 0 ? -1 : 1);
  68833. };
  68834. Bone.prototype.markAsDirty = function () {
  68835. this._currentRenderId++;
  68836. this._skeleton._markAsDirty();
  68837. };
  68838. Bone.prototype.copyAnimationRange = function (source, rangeName, frameOffset, rescaleAsRequired, skelDimensionsRatio) {
  68839. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  68840. if (skelDimensionsRatio === void 0) { skelDimensionsRatio = null; }
  68841. // all animation may be coming from a library skeleton, so may need to create animation
  68842. if (this.animations.length === 0) {
  68843. this.animations.push(new BABYLON.Animation(this.name, "_matrix", source.animations[0].framePerSecond, BABYLON.Animation.ANIMATIONTYPE_MATRIX, 0));
  68844. this.animations[0].setKeys([]);
  68845. }
  68846. // get animation info / verify there is such a range from the source bone
  68847. var sourceRange = source.animations[0].getRange(rangeName);
  68848. if (!sourceRange) {
  68849. return false;
  68850. }
  68851. var from = sourceRange.from;
  68852. var to = sourceRange.to;
  68853. var sourceKeys = source.animations[0].getKeys();
  68854. // rescaling prep
  68855. var sourceBoneLength = source.length;
  68856. var sourceParent = source.getParent();
  68857. var parent = this.getParent();
  68858. var parentScalingReqd = rescaleAsRequired && sourceParent && sourceBoneLength && this.length && sourceBoneLength !== this.length;
  68859. var parentRatio = parentScalingReqd && parent && sourceParent ? parent.length / sourceParent.length : 1;
  68860. var dimensionsScalingReqd = rescaleAsRequired && !parent && skelDimensionsRatio && (skelDimensionsRatio.x !== 1 || skelDimensionsRatio.y !== 1 || skelDimensionsRatio.z !== 1);
  68861. var destKeys = this.animations[0].getKeys();
  68862. // loop vars declaration
  68863. var orig;
  68864. var origTranslation;
  68865. var mat;
  68866. for (var key = 0, nKeys = sourceKeys.length; key < nKeys; key++) {
  68867. orig = sourceKeys[key];
  68868. if (orig.frame >= from && orig.frame <= to) {
  68869. if (rescaleAsRequired) {
  68870. mat = orig.value.clone();
  68871. // scale based on parent ratio, when bone has parent
  68872. if (parentScalingReqd) {
  68873. origTranslation = mat.getTranslation();
  68874. mat.setTranslation(origTranslation.scaleInPlace(parentRatio));
  68875. // scale based on skeleton dimension ratio when root bone, and value is passed
  68876. }
  68877. else if (dimensionsScalingReqd && skelDimensionsRatio) {
  68878. origTranslation = mat.getTranslation();
  68879. mat.setTranslation(origTranslation.multiplyInPlace(skelDimensionsRatio));
  68880. // use original when root bone, and no data for skelDimensionsRatio
  68881. }
  68882. else {
  68883. mat = orig.value;
  68884. }
  68885. }
  68886. else {
  68887. mat = orig.value;
  68888. }
  68889. destKeys.push({ frame: orig.frame + frameOffset, value: mat });
  68890. }
  68891. }
  68892. this.animations[0].createRange(rangeName, from + frameOffset, to + frameOffset);
  68893. return true;
  68894. };
  68895. /**
  68896. * Translate the bone in local or world space.
  68897. * @param vec The amount to translate the bone.
  68898. * @param space The space that the translation is in.
  68899. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  68900. */
  68901. Bone.prototype.translate = function (vec, space, mesh) {
  68902. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  68903. var lm = this.getLocalMatrix();
  68904. if (space == BABYLON.Space.LOCAL) {
  68905. lm.m[12] += vec.x;
  68906. lm.m[13] += vec.y;
  68907. lm.m[14] += vec.z;
  68908. }
  68909. else {
  68910. var wm = null;
  68911. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  68912. if (mesh) {
  68913. wm = mesh.getWorldMatrix();
  68914. }
  68915. this._skeleton.computeAbsoluteTransforms();
  68916. var tmat = Bone._tmpMats[0];
  68917. var tvec = Bone._tmpVecs[0];
  68918. if (this._parent) {
  68919. if (mesh && wm) {
  68920. tmat.copyFrom(this._parent.getAbsoluteTransform());
  68921. tmat.multiplyToRef(wm, tmat);
  68922. }
  68923. else {
  68924. tmat.copyFrom(this._parent.getAbsoluteTransform());
  68925. }
  68926. }
  68927. tmat.m[12] = 0;
  68928. tmat.m[13] = 0;
  68929. tmat.m[14] = 0;
  68930. tmat.invert();
  68931. BABYLON.Vector3.TransformCoordinatesToRef(vec, tmat, tvec);
  68932. lm.m[12] += tvec.x;
  68933. lm.m[13] += tvec.y;
  68934. lm.m[14] += tvec.z;
  68935. }
  68936. this.markAsDirty();
  68937. };
  68938. /**
  68939. * Set the postion of the bone in local or world space.
  68940. * @param position The position to set the bone.
  68941. * @param space The space that the position is in.
  68942. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  68943. */
  68944. Bone.prototype.setPosition = function (position, space, mesh) {
  68945. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  68946. var lm = this.getLocalMatrix();
  68947. if (space == BABYLON.Space.LOCAL) {
  68948. lm.m[12] = position.x;
  68949. lm.m[13] = position.y;
  68950. lm.m[14] = position.z;
  68951. }
  68952. else {
  68953. var wm = null;
  68954. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  68955. if (mesh) {
  68956. wm = mesh.getWorldMatrix();
  68957. }
  68958. this._skeleton.computeAbsoluteTransforms();
  68959. var tmat = Bone._tmpMats[0];
  68960. var vec = Bone._tmpVecs[0];
  68961. if (this._parent) {
  68962. if (mesh && wm) {
  68963. tmat.copyFrom(this._parent.getAbsoluteTransform());
  68964. tmat.multiplyToRef(wm, tmat);
  68965. }
  68966. else {
  68967. tmat.copyFrom(this._parent.getAbsoluteTransform());
  68968. }
  68969. }
  68970. tmat.invert();
  68971. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, vec);
  68972. lm.m[12] = vec.x;
  68973. lm.m[13] = vec.y;
  68974. lm.m[14] = vec.z;
  68975. }
  68976. this.markAsDirty();
  68977. };
  68978. /**
  68979. * Set the absolute postion of the bone (world space).
  68980. * @param position The position to set the bone.
  68981. * @param mesh The mesh that this bone is attached to.
  68982. */
  68983. Bone.prototype.setAbsolutePosition = function (position, mesh) {
  68984. this.setPosition(position, BABYLON.Space.WORLD, mesh);
  68985. };
  68986. /**
  68987. * Set the scale of the bone on the x, y and z axes.
  68988. * @param x The scale of the bone on the x axis.
  68989. * @param x The scale of the bone on the y axis.
  68990. * @param z The scale of the bone on the z axis.
  68991. * @param scaleChildren Set this to true if children of the bone should be scaled.
  68992. */
  68993. Bone.prototype.setScale = function (x, y, z, scaleChildren) {
  68994. if (scaleChildren === void 0) { scaleChildren = false; }
  68995. if (this.animations[0] && !this.animations[0].hasRunningRuntimeAnimations) {
  68996. if (!scaleChildren) {
  68997. this._negateScaleChildren.x = 1 / x;
  68998. this._negateScaleChildren.y = 1 / y;
  68999. this._negateScaleChildren.z = 1 / z;
  69000. }
  69001. this._syncScaleVector();
  69002. }
  69003. this.scale(x / this._scaleVector.x, y / this._scaleVector.y, z / this._scaleVector.z, scaleChildren);
  69004. };
  69005. /**
  69006. * Scale the bone on the x, y and z axes.
  69007. * @param x The amount to scale the bone on the x axis.
  69008. * @param x The amount to scale the bone on the y axis.
  69009. * @param z The amount to scale the bone on the z axis.
  69010. * @param scaleChildren Set this to true if children of the bone should be scaled.
  69011. */
  69012. Bone.prototype.scale = function (x, y, z, scaleChildren) {
  69013. if (scaleChildren === void 0) { scaleChildren = false; }
  69014. var locMat = this.getLocalMatrix();
  69015. var origLocMat = Bone._tmpMats[0];
  69016. origLocMat.copyFrom(locMat);
  69017. var origLocMatInv = Bone._tmpMats[1];
  69018. origLocMatInv.copyFrom(origLocMat);
  69019. origLocMatInv.invert();
  69020. var scaleMat = Bone._tmpMats[2];
  69021. BABYLON.Matrix.FromValuesToRef(x, 0, 0, 0, 0, y, 0, 0, 0, 0, z, 0, 0, 0, 0, 1, scaleMat);
  69022. this._scaleMatrix.multiplyToRef(scaleMat, this._scaleMatrix);
  69023. this._scaleVector.x *= x;
  69024. this._scaleVector.y *= y;
  69025. this._scaleVector.z *= z;
  69026. locMat.multiplyToRef(origLocMatInv, locMat);
  69027. locMat.multiplyToRef(scaleMat, locMat);
  69028. locMat.multiplyToRef(origLocMat, locMat);
  69029. var parent = this.getParent();
  69030. if (parent) {
  69031. locMat.multiplyToRef(parent.getAbsoluteTransform(), this.getAbsoluteTransform());
  69032. }
  69033. else {
  69034. this.getAbsoluteTransform().copyFrom(locMat);
  69035. }
  69036. var len = this.children.length;
  69037. scaleMat.invert();
  69038. for (var i = 0; i < len; i++) {
  69039. var child = this.children[i];
  69040. var cm = child.getLocalMatrix();
  69041. cm.multiplyToRef(scaleMat, cm);
  69042. var lm = child.getLocalMatrix();
  69043. lm.m[12] *= x;
  69044. lm.m[13] *= y;
  69045. lm.m[14] *= z;
  69046. }
  69047. this.computeAbsoluteTransforms();
  69048. if (scaleChildren) {
  69049. for (var i = 0; i < len; i++) {
  69050. this.children[i].scale(x, y, z, scaleChildren);
  69051. }
  69052. }
  69053. this.markAsDirty();
  69054. };
  69055. /**
  69056. * Set the yaw, pitch, and roll of the bone in local or world space.
  69057. * @param yaw The rotation of the bone on the y axis.
  69058. * @param pitch The rotation of the bone on the x axis.
  69059. * @param roll The rotation of the bone on the z axis.
  69060. * @param space The space that the axes of rotation are in.
  69061. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  69062. */
  69063. Bone.prototype.setYawPitchRoll = function (yaw, pitch, roll, space, mesh) {
  69064. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  69065. var rotMat = Bone._tmpMats[0];
  69066. BABYLON.Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, rotMat);
  69067. var rotMatInv = Bone._tmpMats[1];
  69068. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  69069. rotMatInv.multiplyToRef(rotMat, rotMat);
  69070. this._rotateWithMatrix(rotMat, space, mesh);
  69071. };
  69072. /**
  69073. * Rotate the bone on an axis in local or world space.
  69074. * @param axis The axis to rotate the bone on.
  69075. * @param amount The amount to rotate the bone.
  69076. * @param space The space that the axis is in.
  69077. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  69078. */
  69079. Bone.prototype.rotate = function (axis, amount, space, mesh) {
  69080. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  69081. var rmat = Bone._tmpMats[0];
  69082. rmat.m[12] = 0;
  69083. rmat.m[13] = 0;
  69084. rmat.m[14] = 0;
  69085. BABYLON.Matrix.RotationAxisToRef(axis, amount, rmat);
  69086. this._rotateWithMatrix(rmat, space, mesh);
  69087. };
  69088. /**
  69089. * Set the rotation of the bone to a particular axis angle in local or world space.
  69090. * @param axis The axis to rotate the bone on.
  69091. * @param angle The angle that the bone should be rotated to.
  69092. * @param space The space that the axis is in.
  69093. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  69094. */
  69095. Bone.prototype.setAxisAngle = function (axis, angle, space, mesh) {
  69096. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  69097. var rotMat = Bone._tmpMats[0];
  69098. BABYLON.Matrix.RotationAxisToRef(axis, angle, rotMat);
  69099. var rotMatInv = Bone._tmpMats[1];
  69100. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  69101. rotMatInv.multiplyToRef(rotMat, rotMat);
  69102. this._rotateWithMatrix(rotMat, space, mesh);
  69103. };
  69104. /**
  69105. * Set the euler rotation of the bone in local of world space.
  69106. * @param rotation The euler rotation that the bone should be set to.
  69107. * @param space The space that the rotation is in.
  69108. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  69109. */
  69110. Bone.prototype.setRotation = function (rotation, space, mesh) {
  69111. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  69112. this.setYawPitchRoll(rotation.y, rotation.x, rotation.z, space, mesh);
  69113. };
  69114. /**
  69115. * Set the quaternion rotation of the bone in local of world space.
  69116. * @param quat The quaternion rotation that the bone should be set to.
  69117. * @param space The space that the rotation is in.
  69118. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  69119. */
  69120. Bone.prototype.setRotationQuaternion = function (quat, space, mesh) {
  69121. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  69122. var rotMatInv = Bone._tmpMats[0];
  69123. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  69124. var rotMat = Bone._tmpMats[1];
  69125. BABYLON.Matrix.FromQuaternionToRef(quat, rotMat);
  69126. rotMatInv.multiplyToRef(rotMat, rotMat);
  69127. this._rotateWithMatrix(rotMat, space, mesh);
  69128. };
  69129. /**
  69130. * Set the rotation matrix of the bone in local of world space.
  69131. * @param rotMat The rotation matrix that the bone should be set to.
  69132. * @param space The space that the rotation is in.
  69133. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  69134. */
  69135. Bone.prototype.setRotationMatrix = function (rotMat, space, mesh) {
  69136. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  69137. var rotMatInv = Bone._tmpMats[0];
  69138. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  69139. var rotMat2 = Bone._tmpMats[1];
  69140. rotMat2.copyFrom(rotMat);
  69141. rotMatInv.multiplyToRef(rotMat, rotMat2);
  69142. this._rotateWithMatrix(rotMat2, space, mesh);
  69143. };
  69144. Bone.prototype._rotateWithMatrix = function (rmat, space, mesh) {
  69145. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  69146. var lmat = this.getLocalMatrix();
  69147. var lx = lmat.m[12];
  69148. var ly = lmat.m[13];
  69149. var lz = lmat.m[14];
  69150. var parent = this.getParent();
  69151. var parentScale = Bone._tmpMats[3];
  69152. var parentScaleInv = Bone._tmpMats[4];
  69153. if (parent) {
  69154. if (space == BABYLON.Space.WORLD) {
  69155. if (mesh) {
  69156. parentScale.copyFrom(mesh.getWorldMatrix());
  69157. parent.getAbsoluteTransform().multiplyToRef(parentScale, parentScale);
  69158. }
  69159. else {
  69160. parentScale.copyFrom(parent.getAbsoluteTransform());
  69161. }
  69162. }
  69163. else {
  69164. parentScale = parent._scaleMatrix;
  69165. }
  69166. parentScaleInv.copyFrom(parentScale);
  69167. parentScaleInv.invert();
  69168. lmat.multiplyToRef(parentScale, lmat);
  69169. lmat.multiplyToRef(rmat, lmat);
  69170. lmat.multiplyToRef(parentScaleInv, lmat);
  69171. }
  69172. else {
  69173. if (space == BABYLON.Space.WORLD && mesh) {
  69174. parentScale.copyFrom(mesh.getWorldMatrix());
  69175. parentScaleInv.copyFrom(parentScale);
  69176. parentScaleInv.invert();
  69177. lmat.multiplyToRef(parentScale, lmat);
  69178. lmat.multiplyToRef(rmat, lmat);
  69179. lmat.multiplyToRef(parentScaleInv, lmat);
  69180. }
  69181. else {
  69182. lmat.multiplyToRef(rmat, lmat);
  69183. }
  69184. }
  69185. lmat.m[12] = lx;
  69186. lmat.m[13] = ly;
  69187. lmat.m[14] = lz;
  69188. this.computeAbsoluteTransforms();
  69189. this.markAsDirty();
  69190. };
  69191. Bone.prototype._getNegativeRotationToRef = function (rotMatInv, space, mesh) {
  69192. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  69193. if (space == BABYLON.Space.WORLD) {
  69194. var scaleMatrix = Bone._tmpMats[2];
  69195. scaleMatrix.copyFrom(this._scaleMatrix);
  69196. rotMatInv.copyFrom(this.getAbsoluteTransform());
  69197. if (mesh) {
  69198. rotMatInv.multiplyToRef(mesh.getWorldMatrix(), rotMatInv);
  69199. var meshScale = Bone._tmpMats[3];
  69200. BABYLON.Matrix.ScalingToRef(mesh.scaling.x, mesh.scaling.y, mesh.scaling.z, meshScale);
  69201. scaleMatrix.multiplyToRef(meshScale, scaleMatrix);
  69202. }
  69203. rotMatInv.invert();
  69204. scaleMatrix.m[0] *= this._scalingDeterminant;
  69205. rotMatInv.multiplyToRef(scaleMatrix, rotMatInv);
  69206. }
  69207. else {
  69208. rotMatInv.copyFrom(this.getLocalMatrix());
  69209. rotMatInv.invert();
  69210. var scaleMatrix = Bone._tmpMats[2];
  69211. scaleMatrix.copyFrom(this._scaleMatrix);
  69212. if (this._parent) {
  69213. var pscaleMatrix = Bone._tmpMats[3];
  69214. pscaleMatrix.copyFrom(this._parent._scaleMatrix);
  69215. pscaleMatrix.invert();
  69216. pscaleMatrix.multiplyToRef(rotMatInv, rotMatInv);
  69217. }
  69218. else {
  69219. scaleMatrix.m[0] *= this._scalingDeterminant;
  69220. }
  69221. rotMatInv.multiplyToRef(scaleMatrix, rotMatInv);
  69222. }
  69223. };
  69224. /**
  69225. * Get the scale of the bone
  69226. * @returns the scale of the bone
  69227. */
  69228. Bone.prototype.getScale = function () {
  69229. return this._scaleVector.clone();
  69230. };
  69231. /**
  69232. * Copy the scale of the bone to a vector3.
  69233. * @param result The vector3 to copy the scale to
  69234. */
  69235. Bone.prototype.getScaleToRef = function (result) {
  69236. result.copyFrom(this._scaleVector);
  69237. };
  69238. /**
  69239. * Get the position of the bone in local or world space.
  69240. * @param space The space that the returned position is in.
  69241. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  69242. * @returns The position of the bone
  69243. */
  69244. Bone.prototype.getPosition = function (space, mesh) {
  69245. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  69246. if (mesh === void 0) { mesh = null; }
  69247. var pos = BABYLON.Vector3.Zero();
  69248. this.getPositionToRef(space, mesh, pos);
  69249. return pos;
  69250. };
  69251. /**
  69252. * Copy the position of the bone to a vector3 in local or world space.
  69253. * @param space The space that the returned position is in.
  69254. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  69255. * @param result The vector3 to copy the position to.
  69256. */
  69257. Bone.prototype.getPositionToRef = function (space, mesh, result) {
  69258. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  69259. if (space == BABYLON.Space.LOCAL) {
  69260. var lm = this.getLocalMatrix();
  69261. result.x = lm.m[12];
  69262. result.y = lm.m[13];
  69263. result.z = lm.m[14];
  69264. }
  69265. else {
  69266. var wm = null;
  69267. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  69268. if (mesh) {
  69269. wm = mesh.getWorldMatrix();
  69270. }
  69271. this._skeleton.computeAbsoluteTransforms();
  69272. var tmat = Bone._tmpMats[0];
  69273. if (mesh && wm) {
  69274. tmat.copyFrom(this.getAbsoluteTransform());
  69275. tmat.multiplyToRef(wm, tmat);
  69276. }
  69277. else {
  69278. tmat = this.getAbsoluteTransform();
  69279. }
  69280. result.x = tmat.m[12];
  69281. result.y = tmat.m[13];
  69282. result.z = tmat.m[14];
  69283. }
  69284. };
  69285. /**
  69286. * Get the absolute position of the bone (world space).
  69287. * @param mesh The mesh that this bone is attached to.
  69288. * @returns The absolute position of the bone
  69289. */
  69290. Bone.prototype.getAbsolutePosition = function (mesh) {
  69291. if (mesh === void 0) { mesh = null; }
  69292. var pos = BABYLON.Vector3.Zero();
  69293. this.getPositionToRef(BABYLON.Space.WORLD, mesh, pos);
  69294. return pos;
  69295. };
  69296. /**
  69297. * Copy the absolute position of the bone (world space) to the result param.
  69298. * @param mesh The mesh that this bone is attached to.
  69299. * @param result The vector3 to copy the absolute position to.
  69300. */
  69301. Bone.prototype.getAbsolutePositionToRef = function (mesh, result) {
  69302. this.getPositionToRef(BABYLON.Space.WORLD, mesh, result);
  69303. };
  69304. /**
  69305. * Compute the absolute transforms of this bone and its children.
  69306. */
  69307. Bone.prototype.computeAbsoluteTransforms = function () {
  69308. if (this._parent) {
  69309. this._localMatrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  69310. }
  69311. else {
  69312. this._absoluteTransform.copyFrom(this._localMatrix);
  69313. var poseMatrix = this._skeleton.getPoseMatrix();
  69314. if (poseMatrix) {
  69315. this._absoluteTransform.multiplyToRef(poseMatrix, this._absoluteTransform);
  69316. }
  69317. }
  69318. var children = this.children;
  69319. var len = children.length;
  69320. for (var i = 0; i < len; i++) {
  69321. children[i].computeAbsoluteTransforms();
  69322. }
  69323. };
  69324. Bone.prototype._syncScaleVector = function () {
  69325. var lm = this.getLocalMatrix();
  69326. var xsq = (lm.m[0] * lm.m[0] + lm.m[1] * lm.m[1] + lm.m[2] * lm.m[2]);
  69327. var ysq = (lm.m[4] * lm.m[4] + lm.m[5] * lm.m[5] + lm.m[6] * lm.m[6]);
  69328. var zsq = (lm.m[8] * lm.m[8] + lm.m[9] * lm.m[9] + lm.m[10] * lm.m[10]);
  69329. var xs = lm.m[0] * lm.m[1] * lm.m[2] * lm.m[3] < 0 ? -1 : 1;
  69330. var ys = lm.m[4] * lm.m[5] * lm.m[6] * lm.m[7] < 0 ? -1 : 1;
  69331. var zs = lm.m[8] * lm.m[9] * lm.m[10] * lm.m[11] < 0 ? -1 : 1;
  69332. this._scaleVector.x = xs * Math.sqrt(xsq);
  69333. this._scaleVector.y = ys * Math.sqrt(ysq);
  69334. this._scaleVector.z = zs * Math.sqrt(zsq);
  69335. if (this._parent) {
  69336. this._scaleVector.x /= this._parent._negateScaleChildren.x;
  69337. this._scaleVector.y /= this._parent._negateScaleChildren.y;
  69338. this._scaleVector.z /= this._parent._negateScaleChildren.z;
  69339. }
  69340. 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);
  69341. };
  69342. /**
  69343. * Get the world direction from an axis that is in the local space of the bone.
  69344. * @param localAxis The local direction that is used to compute the world direction.
  69345. * @param mesh The mesh that this bone is attached to.
  69346. * @returns The world direction
  69347. */
  69348. Bone.prototype.getDirection = function (localAxis, mesh) {
  69349. if (mesh === void 0) { mesh = null; }
  69350. var result = BABYLON.Vector3.Zero();
  69351. this.getDirectionToRef(localAxis, mesh, result);
  69352. return result;
  69353. };
  69354. /**
  69355. * Copy the world direction to a vector3 from an axis that is in the local space of the bone.
  69356. * @param localAxis The local direction that is used to compute the world direction.
  69357. * @param mesh The mesh that this bone is attached to.
  69358. * @param result The vector3 that the world direction will be copied to.
  69359. */
  69360. Bone.prototype.getDirectionToRef = function (localAxis, mesh, result) {
  69361. if (mesh === void 0) { mesh = null; }
  69362. var wm = null;
  69363. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  69364. if (mesh) {
  69365. wm = mesh.getWorldMatrix();
  69366. }
  69367. this._skeleton.computeAbsoluteTransforms();
  69368. var mat = Bone._tmpMats[0];
  69369. mat.copyFrom(this.getAbsoluteTransform());
  69370. if (mesh && wm) {
  69371. mat.multiplyToRef(wm, mat);
  69372. }
  69373. BABYLON.Vector3.TransformNormalToRef(localAxis, mat, result);
  69374. result.normalize();
  69375. };
  69376. /**
  69377. * Get the euler rotation of the bone in local or world space.
  69378. * @param space The space that the rotation should be in.
  69379. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  69380. * @returns The euler rotation
  69381. */
  69382. Bone.prototype.getRotation = function (space, mesh) {
  69383. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  69384. if (mesh === void 0) { mesh = null; }
  69385. var result = BABYLON.Vector3.Zero();
  69386. this.getRotationToRef(space, mesh, result);
  69387. return result;
  69388. };
  69389. /**
  69390. * Copy the euler rotation of the bone to a vector3. The rotation can be in either local or world space.
  69391. * @param space The space that the rotation should be in.
  69392. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  69393. * @param result The vector3 that the rotation should be copied to.
  69394. */
  69395. Bone.prototype.getRotationToRef = function (space, mesh, result) {
  69396. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  69397. if (mesh === void 0) { mesh = null; }
  69398. var quat = Bone._tmpQuat;
  69399. this.getRotationQuaternionToRef(space, mesh, quat);
  69400. quat.toEulerAnglesToRef(result);
  69401. };
  69402. /**
  69403. * Get the quaternion rotation of the bone in either local or world space.
  69404. * @param space The space that the rotation should be in.
  69405. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  69406. * @returns The quaternion rotation
  69407. */
  69408. Bone.prototype.getRotationQuaternion = function (space, mesh) {
  69409. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  69410. if (mesh === void 0) { mesh = null; }
  69411. var result = BABYLON.Quaternion.Identity();
  69412. this.getRotationQuaternionToRef(space, mesh, result);
  69413. return result;
  69414. };
  69415. /**
  69416. * Copy the quaternion rotation of the bone to a quaternion. The rotation can be in either local or world space.
  69417. * @param space The space that the rotation should be in.
  69418. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  69419. * @param result The quaternion that the rotation should be copied to.
  69420. */
  69421. Bone.prototype.getRotationQuaternionToRef = function (space, mesh, result) {
  69422. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  69423. if (mesh === void 0) { mesh = null; }
  69424. if (space == BABYLON.Space.LOCAL) {
  69425. this.getLocalMatrix().decompose(Bone._tmpVecs[0], result, Bone._tmpVecs[1]);
  69426. }
  69427. else {
  69428. var mat = Bone._tmpMats[0];
  69429. var amat = this.getAbsoluteTransform();
  69430. if (mesh) {
  69431. amat.multiplyToRef(mesh.getWorldMatrix(), mat);
  69432. }
  69433. else {
  69434. mat.copyFrom(amat);
  69435. }
  69436. mat.m[0] *= this._scalingDeterminant;
  69437. mat.m[1] *= this._scalingDeterminant;
  69438. mat.m[2] *= this._scalingDeterminant;
  69439. mat.decompose(Bone._tmpVecs[0], result, Bone._tmpVecs[1]);
  69440. }
  69441. };
  69442. /**
  69443. * Get the rotation matrix of the bone in local or world space.
  69444. * @param space The space that the rotation should be in.
  69445. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  69446. * @returns The rotation matrix
  69447. */
  69448. Bone.prototype.getRotationMatrix = function (space, mesh) {
  69449. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  69450. var result = BABYLON.Matrix.Identity();
  69451. this.getRotationMatrixToRef(space, mesh, result);
  69452. return result;
  69453. };
  69454. /**
  69455. * Copy the rotation matrix of the bone to a matrix. The rotation can be in either local or world space.
  69456. * @param space The space that the rotation should be in.
  69457. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  69458. * @param result The quaternion that the rotation should be copied to.
  69459. */
  69460. Bone.prototype.getRotationMatrixToRef = function (space, mesh, result) {
  69461. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  69462. if (space == BABYLON.Space.LOCAL) {
  69463. this.getLocalMatrix().getRotationMatrixToRef(result);
  69464. }
  69465. else {
  69466. var mat = Bone._tmpMats[0];
  69467. var amat = this.getAbsoluteTransform();
  69468. if (mesh) {
  69469. amat.multiplyToRef(mesh.getWorldMatrix(), mat);
  69470. }
  69471. else {
  69472. mat.copyFrom(amat);
  69473. }
  69474. mat.m[0] *= this._scalingDeterminant;
  69475. mat.m[1] *= this._scalingDeterminant;
  69476. mat.m[2] *= this._scalingDeterminant;
  69477. mat.getRotationMatrixToRef(result);
  69478. }
  69479. };
  69480. /**
  69481. * Get the world position of a point that is in the local space of the bone.
  69482. * @param position The local position
  69483. * @param mesh The mesh that this bone is attached to.
  69484. * @returns The world position
  69485. */
  69486. Bone.prototype.getAbsolutePositionFromLocal = function (position, mesh) {
  69487. if (mesh === void 0) { mesh = null; }
  69488. var result = BABYLON.Vector3.Zero();
  69489. this.getAbsolutePositionFromLocalToRef(position, mesh, result);
  69490. return result;
  69491. };
  69492. /**
  69493. * Get the world position of a point that is in the local space of the bone and copy it to the result param.
  69494. * @param position The local position
  69495. * @param mesh The mesh that this bone is attached to.
  69496. * @param result The vector3 that the world position should be copied to.
  69497. */
  69498. Bone.prototype.getAbsolutePositionFromLocalToRef = function (position, mesh, result) {
  69499. if (mesh === void 0) { mesh = null; }
  69500. var wm = null;
  69501. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  69502. if (mesh) {
  69503. wm = mesh.getWorldMatrix();
  69504. }
  69505. this._skeleton.computeAbsoluteTransforms();
  69506. var tmat = Bone._tmpMats[0];
  69507. if (mesh && wm) {
  69508. tmat.copyFrom(this.getAbsoluteTransform());
  69509. tmat.multiplyToRef(wm, tmat);
  69510. }
  69511. else {
  69512. tmat = this.getAbsoluteTransform();
  69513. }
  69514. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, result);
  69515. };
  69516. /**
  69517. * Get the local position of a point that is in world space.
  69518. * @param position The world position
  69519. * @param mesh The mesh that this bone is attached to.
  69520. * @returns The local position
  69521. */
  69522. Bone.prototype.getLocalPositionFromAbsolute = function (position, mesh) {
  69523. if (mesh === void 0) { mesh = null; }
  69524. var result = BABYLON.Vector3.Zero();
  69525. this.getLocalPositionFromAbsoluteToRef(position, mesh, result);
  69526. return result;
  69527. };
  69528. /**
  69529. * Get the local position of a point that is in world space and copy it to the result param.
  69530. * @param position The world position
  69531. * @param mesh The mesh that this bone is attached to.
  69532. * @param result The vector3 that the local position should be copied to.
  69533. */
  69534. Bone.prototype.getLocalPositionFromAbsoluteToRef = function (position, mesh, result) {
  69535. if (mesh === void 0) { mesh = null; }
  69536. var wm = null;
  69537. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  69538. if (mesh) {
  69539. wm = mesh.getWorldMatrix();
  69540. }
  69541. this._skeleton.computeAbsoluteTransforms();
  69542. var tmat = Bone._tmpMats[0];
  69543. tmat.copyFrom(this.getAbsoluteTransform());
  69544. if (mesh && wm) {
  69545. tmat.multiplyToRef(wm, tmat);
  69546. }
  69547. tmat.invert();
  69548. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, result);
  69549. };
  69550. Bone._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  69551. Bone._tmpQuat = BABYLON.Quaternion.Identity();
  69552. Bone._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  69553. return Bone;
  69554. }(BABYLON.Node));
  69555. BABYLON.Bone = Bone;
  69556. })(BABYLON || (BABYLON = {}));
  69557. //# sourceMappingURL=babylon.bone.js.map
  69558. var BABYLON;
  69559. (function (BABYLON) {
  69560. var BoneIKController = /** @class */ (function () {
  69561. function BoneIKController(mesh, bone, options) {
  69562. this.targetPosition = BABYLON.Vector3.Zero();
  69563. this.poleTargetPosition = BABYLON.Vector3.Zero();
  69564. this.poleTargetLocalOffset = BABYLON.Vector3.Zero();
  69565. this.poleAngle = 0;
  69566. this.slerpAmount = 1;
  69567. this._bone1Quat = BABYLON.Quaternion.Identity();
  69568. this._bone1Mat = BABYLON.Matrix.Identity();
  69569. this._bone2Ang = Math.PI;
  69570. this._maxAngle = Math.PI;
  69571. this._rightHandedSystem = false;
  69572. this._bendAxis = BABYLON.Vector3.Right();
  69573. this._slerping = false;
  69574. this._adjustRoll = 0;
  69575. this._bone2 = bone;
  69576. this._bone1 = bone.getParent();
  69577. if (!this._bone1) {
  69578. return;
  69579. }
  69580. this.mesh = mesh;
  69581. var bonePos = bone.getPosition();
  69582. if (bone.getAbsoluteTransform().determinant() > 0) {
  69583. this._rightHandedSystem = true;
  69584. this._bendAxis.x = 0;
  69585. this._bendAxis.y = 0;
  69586. this._bendAxis.z = -1;
  69587. if (bonePos.x > bonePos.y && bonePos.x > bonePos.z) {
  69588. this._adjustRoll = Math.PI * .5;
  69589. this._bendAxis.z = 1;
  69590. }
  69591. }
  69592. if (this._bone1.length) {
  69593. var boneScale1 = this._bone1.getScale();
  69594. var boneScale2 = this._bone2.getScale();
  69595. this._bone1Length = this._bone1.length * boneScale1.y * this.mesh.scaling.y;
  69596. this._bone2Length = this._bone2.length * boneScale2.y * this.mesh.scaling.y;
  69597. }
  69598. else if (this._bone1.children[0]) {
  69599. mesh.computeWorldMatrix(true);
  69600. var pos1 = this._bone2.children[0].getAbsolutePosition(mesh);
  69601. var pos2 = this._bone2.getAbsolutePosition(mesh);
  69602. var pos3 = this._bone1.getAbsolutePosition(mesh);
  69603. this._bone1Length = BABYLON.Vector3.Distance(pos1, pos2);
  69604. this._bone2Length = BABYLON.Vector3.Distance(pos2, pos3);
  69605. }
  69606. this._bone1.getRotationMatrixToRef(BABYLON.Space.WORLD, mesh, this._bone1Mat);
  69607. this.maxAngle = Math.PI;
  69608. if (options) {
  69609. if (options.targetMesh) {
  69610. this.targetMesh = options.targetMesh;
  69611. this.targetMesh.computeWorldMatrix(true);
  69612. }
  69613. if (options.poleTargetMesh) {
  69614. this.poleTargetMesh = options.poleTargetMesh;
  69615. this.poleTargetMesh.computeWorldMatrix(true);
  69616. }
  69617. else if (options.poleTargetBone) {
  69618. this.poleTargetBone = options.poleTargetBone;
  69619. }
  69620. else if (this._bone1.getParent()) {
  69621. this.poleTargetBone = this._bone1.getParent();
  69622. }
  69623. if (options.poleTargetLocalOffset) {
  69624. this.poleTargetLocalOffset.copyFrom(options.poleTargetLocalOffset);
  69625. }
  69626. if (options.poleAngle) {
  69627. this.poleAngle = options.poleAngle;
  69628. }
  69629. if (options.bendAxis) {
  69630. this._bendAxis.copyFrom(options.bendAxis);
  69631. }
  69632. if (options.maxAngle) {
  69633. this.maxAngle = options.maxAngle;
  69634. }
  69635. if (options.slerpAmount) {
  69636. this.slerpAmount = options.slerpAmount;
  69637. }
  69638. }
  69639. }
  69640. Object.defineProperty(BoneIKController.prototype, "maxAngle", {
  69641. get: function () {
  69642. return this._maxAngle;
  69643. },
  69644. set: function (value) {
  69645. this._setMaxAngle(value);
  69646. },
  69647. enumerable: true,
  69648. configurable: true
  69649. });
  69650. BoneIKController.prototype._setMaxAngle = function (ang) {
  69651. if (ang < 0) {
  69652. ang = 0;
  69653. }
  69654. if (ang > Math.PI || ang == undefined) {
  69655. ang = Math.PI;
  69656. }
  69657. this._maxAngle = ang;
  69658. var a = this._bone1Length;
  69659. var b = this._bone2Length;
  69660. this._maxReach = Math.sqrt(a * a + b * b - 2 * a * b * Math.cos(ang));
  69661. };
  69662. BoneIKController.prototype.update = function () {
  69663. var bone1 = this._bone1;
  69664. if (!bone1) {
  69665. return;
  69666. }
  69667. var target = this.targetPosition;
  69668. var poleTarget = this.poleTargetPosition;
  69669. var mat1 = BoneIKController._tmpMats[0];
  69670. var mat2 = BoneIKController._tmpMats[1];
  69671. if (this.targetMesh) {
  69672. target.copyFrom(this.targetMesh.getAbsolutePosition());
  69673. }
  69674. if (this.poleTargetBone) {
  69675. this.poleTargetBone.getAbsolutePositionFromLocalToRef(this.poleTargetLocalOffset, this.mesh, poleTarget);
  69676. }
  69677. else if (this.poleTargetMesh) {
  69678. BABYLON.Vector3.TransformCoordinatesToRef(this.poleTargetLocalOffset, this.poleTargetMesh.getWorldMatrix(), poleTarget);
  69679. }
  69680. var bonePos = BoneIKController._tmpVecs[0];
  69681. var zaxis = BoneIKController._tmpVecs[1];
  69682. var xaxis = BoneIKController._tmpVecs[2];
  69683. var yaxis = BoneIKController._tmpVecs[3];
  69684. var upAxis = BoneIKController._tmpVecs[4];
  69685. var _tmpQuat = BoneIKController._tmpQuat;
  69686. bone1.getAbsolutePositionToRef(this.mesh, bonePos);
  69687. poleTarget.subtractToRef(bonePos, upAxis);
  69688. if (upAxis.x == 0 && upAxis.y == 0 && upAxis.z == 0) {
  69689. upAxis.y = 1;
  69690. }
  69691. else {
  69692. upAxis.normalize();
  69693. }
  69694. target.subtractToRef(bonePos, yaxis);
  69695. yaxis.normalize();
  69696. BABYLON.Vector3.CrossToRef(yaxis, upAxis, zaxis);
  69697. zaxis.normalize();
  69698. BABYLON.Vector3.CrossToRef(yaxis, zaxis, xaxis);
  69699. xaxis.normalize();
  69700. BABYLON.Matrix.FromXYZAxesToRef(xaxis, yaxis, zaxis, mat1);
  69701. var a = this._bone1Length;
  69702. var b = this._bone2Length;
  69703. var c = BABYLON.Vector3.Distance(bonePos, target);
  69704. if (this._maxReach > 0) {
  69705. c = Math.min(this._maxReach, c);
  69706. }
  69707. var acosa = (b * b + c * c - a * a) / (2 * b * c);
  69708. var acosb = (c * c + a * a - b * b) / (2 * c * a);
  69709. if (acosa > 1) {
  69710. acosa = 1;
  69711. }
  69712. if (acosb > 1) {
  69713. acosb = 1;
  69714. }
  69715. if (acosa < -1) {
  69716. acosa = -1;
  69717. }
  69718. if (acosb < -1) {
  69719. acosb = -1;
  69720. }
  69721. var angA = Math.acos(acosa);
  69722. var angB = Math.acos(acosb);
  69723. var angC = -angA - angB;
  69724. if (this._rightHandedSystem) {
  69725. BABYLON.Matrix.RotationYawPitchRollToRef(0, 0, this._adjustRoll, mat2);
  69726. mat2.multiplyToRef(mat1, mat1);
  69727. BABYLON.Matrix.RotationAxisToRef(this._bendAxis, angB, mat2);
  69728. mat2.multiplyToRef(mat1, mat1);
  69729. }
  69730. else {
  69731. var _tmpVec = BoneIKController._tmpVecs[5];
  69732. _tmpVec.copyFrom(this._bendAxis);
  69733. _tmpVec.x *= -1;
  69734. BABYLON.Matrix.RotationAxisToRef(_tmpVec, -angB, mat2);
  69735. mat2.multiplyToRef(mat1, mat1);
  69736. }
  69737. if (this.poleAngle) {
  69738. BABYLON.Matrix.RotationAxisToRef(yaxis, this.poleAngle, mat2);
  69739. mat1.multiplyToRef(mat2, mat1);
  69740. }
  69741. if (this._bone1) {
  69742. if (this.slerpAmount < 1) {
  69743. if (!this._slerping) {
  69744. BABYLON.Quaternion.FromRotationMatrixToRef(this._bone1Mat, this._bone1Quat);
  69745. }
  69746. BABYLON.Quaternion.FromRotationMatrixToRef(mat1, _tmpQuat);
  69747. BABYLON.Quaternion.SlerpToRef(this._bone1Quat, _tmpQuat, this.slerpAmount, this._bone1Quat);
  69748. angC = this._bone2Ang * (1.0 - this.slerpAmount) + angC * this.slerpAmount;
  69749. this._bone1.setRotationQuaternion(this._bone1Quat, BABYLON.Space.WORLD, this.mesh);
  69750. this._slerping = true;
  69751. }
  69752. else {
  69753. this._bone1.setRotationMatrix(mat1, BABYLON.Space.WORLD, this.mesh);
  69754. this._bone1Mat.copyFrom(mat1);
  69755. this._slerping = false;
  69756. }
  69757. }
  69758. this._bone2.setAxisAngle(this._bendAxis, angC, BABYLON.Space.LOCAL);
  69759. this._bone2Ang = angC;
  69760. };
  69761. BoneIKController._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  69762. BoneIKController._tmpQuat = BABYLON.Quaternion.Identity();
  69763. BoneIKController._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  69764. return BoneIKController;
  69765. }());
  69766. BABYLON.BoneIKController = BoneIKController;
  69767. })(BABYLON || (BABYLON = {}));
  69768. //# sourceMappingURL=babylon.boneIKController.js.map
  69769. var BABYLON;
  69770. (function (BABYLON) {
  69771. var BoneLookController = /** @class */ (function () {
  69772. /**
  69773. * Create a BoneLookController
  69774. * @param mesh the mesh that the bone belongs to
  69775. * @param bone the bone that will be looking to the target
  69776. * @param target the target Vector3 to look at
  69777. * @param settings optional settings:
  69778. * - maxYaw: the maximum angle the bone will yaw to
  69779. * - minYaw: the minimum angle the bone will yaw to
  69780. * - maxPitch: the maximum angle the bone will pitch to
  69781. * - minPitch: the minimum angle the bone will yaw to
  69782. * - slerpAmount: set the between 0 and 1 to make the bone slerp to the target.
  69783. * - upAxis: the up axis of the coordinate system
  69784. * - upAxisSpace: the space that the up axis is in - BABYLON.Space.BONE, BABYLON.Space.LOCAL (default), or BABYLON.Space.WORLD.
  69785. * - yawAxis: set yawAxis if the bone does not yaw on the y axis
  69786. * - pitchAxis: set pitchAxis if the bone does not pitch on the x axis
  69787. * - adjustYaw: used to make an adjustment to the yaw of the bone
  69788. * - adjustPitch: used to make an adjustment to the pitch of the bone
  69789. * - adjustRoll: used to make an adjustment to the roll of the bone
  69790. **/
  69791. function BoneLookController(mesh, bone, target, options) {
  69792. /**
  69793. * The up axis of the coordinate system that is used when the bone is rotated.
  69794. */
  69795. this.upAxis = BABYLON.Vector3.Up();
  69796. /**
  69797. * The space that the up axis is in - BABYLON.Space.BONE, BABYLON.Space.LOCAL (default), or BABYLON.Space.WORLD.
  69798. */
  69799. this.upAxisSpace = BABYLON.Space.LOCAL;
  69800. /**
  69801. * Used to make an adjustment to the yaw of the bone.
  69802. */
  69803. this.adjustYaw = 0;
  69804. /**
  69805. * Used to make an adjustment to the pitch of the bone.
  69806. */
  69807. this.adjustPitch = 0;
  69808. /**
  69809. * Used to make an adjustment to the roll of the bone.
  69810. */
  69811. this.adjustRoll = 0;
  69812. /**
  69813. * 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).
  69814. */
  69815. this.slerpAmount = 1;
  69816. this._boneQuat = BABYLON.Quaternion.Identity();
  69817. this._slerping = false;
  69818. this._firstFrameSkipped = false;
  69819. this._fowardAxis = BABYLON.Vector3.Forward();
  69820. this.mesh = mesh;
  69821. this.bone = bone;
  69822. this.target = target;
  69823. if (options) {
  69824. if (options.adjustYaw) {
  69825. this.adjustYaw = options.adjustYaw;
  69826. }
  69827. if (options.adjustPitch) {
  69828. this.adjustPitch = options.adjustPitch;
  69829. }
  69830. if (options.adjustRoll) {
  69831. this.adjustRoll = options.adjustRoll;
  69832. }
  69833. if (options.maxYaw != null) {
  69834. this.maxYaw = options.maxYaw;
  69835. }
  69836. else {
  69837. this.maxYaw = Math.PI;
  69838. }
  69839. if (options.minYaw != null) {
  69840. this.minYaw = options.minYaw;
  69841. }
  69842. else {
  69843. this.minYaw = -Math.PI;
  69844. }
  69845. if (options.maxPitch != null) {
  69846. this.maxPitch = options.maxPitch;
  69847. }
  69848. else {
  69849. this.maxPitch = Math.PI;
  69850. }
  69851. if (options.minPitch != null) {
  69852. this.minPitch = options.minPitch;
  69853. }
  69854. else {
  69855. this.minPitch = -Math.PI;
  69856. }
  69857. if (options.slerpAmount != null) {
  69858. this.slerpAmount = options.slerpAmount;
  69859. }
  69860. if (options.upAxis != null) {
  69861. this.upAxis = options.upAxis;
  69862. }
  69863. if (options.upAxisSpace != null) {
  69864. this.upAxisSpace = options.upAxisSpace;
  69865. }
  69866. if (options.yawAxis != null || options.pitchAxis != null) {
  69867. var newYawAxis = BABYLON.Axis.Y;
  69868. var newPitchAxis = BABYLON.Axis.X;
  69869. if (options.yawAxis != null) {
  69870. newYawAxis = options.yawAxis.clone();
  69871. newYawAxis.normalize();
  69872. }
  69873. if (options.pitchAxis != null) {
  69874. newPitchAxis = options.pitchAxis.clone();
  69875. newPitchAxis.normalize();
  69876. }
  69877. var newRollAxis = BABYLON.Vector3.Cross(newPitchAxis, newYawAxis);
  69878. this._transformYawPitch = BABYLON.Matrix.Identity();
  69879. BABYLON.Matrix.FromXYZAxesToRef(newPitchAxis, newYawAxis, newRollAxis, this._transformYawPitch);
  69880. this._transformYawPitchInv = this._transformYawPitch.clone();
  69881. this._transformYawPitch.invert();
  69882. }
  69883. }
  69884. if (!bone.getParent() && this.upAxisSpace == BABYLON.Space.BONE) {
  69885. this.upAxisSpace = BABYLON.Space.LOCAL;
  69886. }
  69887. }
  69888. Object.defineProperty(BoneLookController.prototype, "minYaw", {
  69889. /**
  69890. * Get/set the minimum yaw angle that the bone can look to.
  69891. */
  69892. get: function () {
  69893. return this._minYaw;
  69894. },
  69895. set: function (value) {
  69896. this._minYaw = value;
  69897. this._minYawSin = Math.sin(value);
  69898. this._minYawCos = Math.cos(value);
  69899. if (this._maxYaw != null) {
  69900. this._midYawConstraint = this._getAngleDiff(this._minYaw, this._maxYaw) * .5 + this._minYaw;
  69901. this._yawRange = this._maxYaw - this._minYaw;
  69902. }
  69903. },
  69904. enumerable: true,
  69905. configurable: true
  69906. });
  69907. Object.defineProperty(BoneLookController.prototype, "maxYaw", {
  69908. /**
  69909. * Get/set the maximum yaw angle that the bone can look to.
  69910. */
  69911. get: function () {
  69912. return this._maxYaw;
  69913. },
  69914. set: function (value) {
  69915. this._maxYaw = value;
  69916. this._maxYawSin = Math.sin(value);
  69917. this._maxYawCos = Math.cos(value);
  69918. if (this._minYaw != null) {
  69919. this._midYawConstraint = this._getAngleDiff(this._minYaw, this._maxYaw) * .5 + this._minYaw;
  69920. this._yawRange = this._maxYaw - this._minYaw;
  69921. }
  69922. },
  69923. enumerable: true,
  69924. configurable: true
  69925. });
  69926. Object.defineProperty(BoneLookController.prototype, "minPitch", {
  69927. /**
  69928. * Get/set the minimum pitch angle that the bone can look to.
  69929. */
  69930. get: function () {
  69931. return this._minPitch;
  69932. },
  69933. set: function (value) {
  69934. this._minPitch = value;
  69935. this._minPitchTan = Math.tan(value);
  69936. },
  69937. enumerable: true,
  69938. configurable: true
  69939. });
  69940. Object.defineProperty(BoneLookController.prototype, "maxPitch", {
  69941. /**
  69942. * Get/set the maximum pitch angle that the bone can look to.
  69943. */
  69944. get: function () {
  69945. return this._maxPitch;
  69946. },
  69947. set: function (value) {
  69948. this._maxPitch = value;
  69949. this._maxPitchTan = Math.tan(value);
  69950. },
  69951. enumerable: true,
  69952. configurable: true
  69953. });
  69954. /**
  69955. * Update the bone to look at the target. This should be called before the scene is rendered (use scene.registerBeforeRender()).
  69956. */
  69957. BoneLookController.prototype.update = function () {
  69958. //skip the first frame when slerping so that the mesh rotation is correct
  69959. if (this.slerpAmount < 1 && !this._firstFrameSkipped) {
  69960. this._firstFrameSkipped = true;
  69961. return;
  69962. }
  69963. var bone = this.bone;
  69964. var bonePos = BoneLookController._tmpVecs[0];
  69965. bone.getAbsolutePositionToRef(this.mesh, bonePos);
  69966. var target = this.target;
  69967. var _tmpMat1 = BoneLookController._tmpMats[0];
  69968. var _tmpMat2 = BoneLookController._tmpMats[1];
  69969. var mesh = this.mesh;
  69970. var parentBone = bone.getParent();
  69971. var upAxis = BoneLookController._tmpVecs[1];
  69972. upAxis.copyFrom(this.upAxis);
  69973. if (this.upAxisSpace == BABYLON.Space.BONE && parentBone) {
  69974. if (this._transformYawPitch) {
  69975. BABYLON.Vector3.TransformCoordinatesToRef(upAxis, this._transformYawPitchInv, upAxis);
  69976. }
  69977. parentBone.getDirectionToRef(upAxis, this.mesh, upAxis);
  69978. }
  69979. else if (this.upAxisSpace == BABYLON.Space.LOCAL) {
  69980. mesh.getDirectionToRef(upAxis, upAxis);
  69981. if (mesh.scaling.x != 1 || mesh.scaling.y != 1 || mesh.scaling.z != 1) {
  69982. upAxis.normalize();
  69983. }
  69984. }
  69985. var checkYaw = false;
  69986. var checkPitch = false;
  69987. if (this._maxYaw != Math.PI || this._minYaw != -Math.PI) {
  69988. checkYaw = true;
  69989. }
  69990. if (this._maxPitch != Math.PI || this._minPitch != -Math.PI) {
  69991. checkPitch = true;
  69992. }
  69993. if (checkYaw || checkPitch) {
  69994. var spaceMat = BoneLookController._tmpMats[2];
  69995. var spaceMatInv = BoneLookController._tmpMats[3];
  69996. if (this.upAxisSpace == BABYLON.Space.BONE && upAxis.y == 1 && parentBone) {
  69997. parentBone.getRotationMatrixToRef(BABYLON.Space.WORLD, this.mesh, spaceMat);
  69998. }
  69999. else if (this.upAxisSpace == BABYLON.Space.LOCAL && upAxis.y == 1 && !parentBone) {
  70000. spaceMat.copyFrom(mesh.getWorldMatrix());
  70001. }
  70002. else {
  70003. var forwardAxis = BoneLookController._tmpVecs[2];
  70004. forwardAxis.copyFrom(this._fowardAxis);
  70005. if (this._transformYawPitch) {
  70006. BABYLON.Vector3.TransformCoordinatesToRef(forwardAxis, this._transformYawPitchInv, forwardAxis);
  70007. }
  70008. if (parentBone) {
  70009. parentBone.getDirectionToRef(forwardAxis, this.mesh, forwardAxis);
  70010. }
  70011. else {
  70012. mesh.getDirectionToRef(forwardAxis, forwardAxis);
  70013. }
  70014. var rightAxis = BABYLON.Vector3.Cross(upAxis, forwardAxis);
  70015. rightAxis.normalize();
  70016. var forwardAxis = BABYLON.Vector3.Cross(rightAxis, upAxis);
  70017. BABYLON.Matrix.FromXYZAxesToRef(rightAxis, upAxis, forwardAxis, spaceMat);
  70018. }
  70019. spaceMat.invertToRef(spaceMatInv);
  70020. var xzlen = null;
  70021. if (checkPitch) {
  70022. var localTarget = BoneLookController._tmpVecs[3];
  70023. target.subtractToRef(bonePos, localTarget);
  70024. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMatInv, localTarget);
  70025. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  70026. var pitch = Math.atan2(localTarget.y, xzlen);
  70027. var newPitch = pitch;
  70028. if (pitch > this._maxPitch) {
  70029. localTarget.y = this._maxPitchTan * xzlen;
  70030. newPitch = this._maxPitch;
  70031. }
  70032. else if (pitch < this._minPitch) {
  70033. localTarget.y = this._minPitchTan * xzlen;
  70034. newPitch = this._minPitch;
  70035. }
  70036. if (pitch != newPitch) {
  70037. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMat, localTarget);
  70038. localTarget.addInPlace(bonePos);
  70039. target = localTarget;
  70040. }
  70041. }
  70042. if (checkYaw) {
  70043. var localTarget = BoneLookController._tmpVecs[4];
  70044. target.subtractToRef(bonePos, localTarget);
  70045. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMatInv, localTarget);
  70046. var yaw = Math.atan2(localTarget.x, localTarget.z);
  70047. var newYaw = yaw;
  70048. if (yaw > this._maxYaw || yaw < this._minYaw) {
  70049. if (xzlen == null) {
  70050. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  70051. }
  70052. if (this._yawRange > Math.PI) {
  70053. if (this._isAngleBetween(yaw, this._maxYaw, this._midYawConstraint)) {
  70054. localTarget.z = this._maxYawCos * xzlen;
  70055. localTarget.x = this._maxYawSin * xzlen;
  70056. newYaw = this._maxYaw;
  70057. }
  70058. else if (this._isAngleBetween(yaw, this._midYawConstraint, this._minYaw)) {
  70059. localTarget.z = this._minYawCos * xzlen;
  70060. localTarget.x = this._minYawSin * xzlen;
  70061. newYaw = this._minYaw;
  70062. }
  70063. }
  70064. else {
  70065. if (yaw > this._maxYaw) {
  70066. localTarget.z = this._maxYawCos * xzlen;
  70067. localTarget.x = this._maxYawSin * xzlen;
  70068. newYaw = this._maxYaw;
  70069. }
  70070. else if (yaw < this._minYaw) {
  70071. localTarget.z = this._minYawCos * xzlen;
  70072. localTarget.x = this._minYawSin * xzlen;
  70073. newYaw = this._minYaw;
  70074. }
  70075. }
  70076. }
  70077. if (this._slerping && this._yawRange > Math.PI) {
  70078. //are we going to be crossing into the min/max region?
  70079. var boneFwd = BoneLookController._tmpVecs[8];
  70080. boneFwd.copyFrom(BABYLON.Axis.Z);
  70081. if (this._transformYawPitch) {
  70082. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, this._transformYawPitchInv, boneFwd);
  70083. }
  70084. var boneRotMat = BoneLookController._tmpMats[4];
  70085. this._boneQuat.toRotationMatrix(boneRotMat);
  70086. this.mesh.getWorldMatrix().multiplyToRef(boneRotMat, boneRotMat);
  70087. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, boneRotMat, boneFwd);
  70088. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, spaceMatInv, boneFwd);
  70089. var boneYaw = Math.atan2(boneFwd.x, boneFwd.z);
  70090. var angBtwTar = this._getAngleBetween(boneYaw, yaw);
  70091. var angBtwMidYaw = this._getAngleBetween(boneYaw, this._midYawConstraint);
  70092. if (angBtwTar > angBtwMidYaw) {
  70093. if (xzlen == null) {
  70094. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  70095. }
  70096. var angBtwMax = this._getAngleBetween(boneYaw, this._maxYaw);
  70097. var angBtwMin = this._getAngleBetween(boneYaw, this._minYaw);
  70098. if (angBtwMin < angBtwMax) {
  70099. newYaw = boneYaw + Math.PI * .75;
  70100. localTarget.z = Math.cos(newYaw) * xzlen;
  70101. localTarget.x = Math.sin(newYaw) * xzlen;
  70102. }
  70103. else {
  70104. newYaw = boneYaw - Math.PI * .75;
  70105. localTarget.z = Math.cos(newYaw) * xzlen;
  70106. localTarget.x = Math.sin(newYaw) * xzlen;
  70107. }
  70108. }
  70109. }
  70110. if (yaw != newYaw) {
  70111. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMat, localTarget);
  70112. localTarget.addInPlace(bonePos);
  70113. target = localTarget;
  70114. }
  70115. }
  70116. }
  70117. var zaxis = BoneLookController._tmpVecs[5];
  70118. var xaxis = BoneLookController._tmpVecs[6];
  70119. var yaxis = BoneLookController._tmpVecs[7];
  70120. var _tmpQuat = BoneLookController._tmpQuat;
  70121. target.subtractToRef(bonePos, zaxis);
  70122. zaxis.normalize();
  70123. BABYLON.Vector3.CrossToRef(upAxis, zaxis, xaxis);
  70124. xaxis.normalize();
  70125. BABYLON.Vector3.CrossToRef(zaxis, xaxis, yaxis);
  70126. yaxis.normalize();
  70127. BABYLON.Matrix.FromXYZAxesToRef(xaxis, yaxis, zaxis, _tmpMat1);
  70128. if (xaxis.x === 0 && xaxis.y === 0 && xaxis.z === 0) {
  70129. return;
  70130. }
  70131. if (yaxis.x === 0 && yaxis.y === 0 && yaxis.z === 0) {
  70132. return;
  70133. }
  70134. if (zaxis.x === 0 && zaxis.y === 0 && zaxis.z === 0) {
  70135. return;
  70136. }
  70137. if (this.adjustYaw || this.adjustPitch || this.adjustRoll) {
  70138. BABYLON.Matrix.RotationYawPitchRollToRef(this.adjustYaw, this.adjustPitch, this.adjustRoll, _tmpMat2);
  70139. _tmpMat2.multiplyToRef(_tmpMat1, _tmpMat1);
  70140. }
  70141. if (this.slerpAmount < 1) {
  70142. if (!this._slerping) {
  70143. this.bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, this.mesh, this._boneQuat);
  70144. }
  70145. if (this._transformYawPitch) {
  70146. this._transformYawPitch.multiplyToRef(_tmpMat1, _tmpMat1);
  70147. }
  70148. BABYLON.Quaternion.FromRotationMatrixToRef(_tmpMat1, _tmpQuat);
  70149. BABYLON.Quaternion.SlerpToRef(this._boneQuat, _tmpQuat, this.slerpAmount, this._boneQuat);
  70150. this.bone.setRotationQuaternion(this._boneQuat, BABYLON.Space.WORLD, this.mesh);
  70151. this._slerping = true;
  70152. }
  70153. else {
  70154. if (this._transformYawPitch) {
  70155. this._transformYawPitch.multiplyToRef(_tmpMat1, _tmpMat1);
  70156. }
  70157. this.bone.setRotationMatrix(_tmpMat1, BABYLON.Space.WORLD, this.mesh);
  70158. this._slerping = false;
  70159. }
  70160. };
  70161. BoneLookController.prototype._getAngleDiff = function (ang1, ang2) {
  70162. var angDiff = ang2 - ang1;
  70163. angDiff %= Math.PI * 2;
  70164. if (angDiff > Math.PI) {
  70165. angDiff -= Math.PI * 2;
  70166. }
  70167. else if (angDiff < -Math.PI) {
  70168. angDiff += Math.PI * 2;
  70169. }
  70170. return angDiff;
  70171. };
  70172. BoneLookController.prototype._getAngleBetween = function (ang1, ang2) {
  70173. ang1 %= (2 * Math.PI);
  70174. ang1 = (ang1 < 0) ? ang1 + (2 * Math.PI) : ang1;
  70175. ang2 %= (2 * Math.PI);
  70176. ang2 = (ang2 < 0) ? ang2 + (2 * Math.PI) : ang2;
  70177. var ab = 0;
  70178. if (ang1 < ang2) {
  70179. ab = ang2 - ang1;
  70180. }
  70181. else {
  70182. ab = ang1 - ang2;
  70183. }
  70184. if (ab > Math.PI) {
  70185. ab = Math.PI * 2 - ab;
  70186. }
  70187. return ab;
  70188. };
  70189. BoneLookController.prototype._isAngleBetween = function (ang, ang1, ang2) {
  70190. ang %= (2 * Math.PI);
  70191. ang = (ang < 0) ? ang + (2 * Math.PI) : ang;
  70192. ang1 %= (2 * Math.PI);
  70193. ang1 = (ang1 < 0) ? ang1 + (2 * Math.PI) : ang1;
  70194. ang2 %= (2 * Math.PI);
  70195. ang2 = (ang2 < 0) ? ang2 + (2 * Math.PI) : ang2;
  70196. if (ang1 < ang2) {
  70197. if (ang > ang1 && ang < ang2) {
  70198. return true;
  70199. }
  70200. }
  70201. else {
  70202. if (ang > ang2 && ang < ang1) {
  70203. return true;
  70204. }
  70205. }
  70206. return false;
  70207. };
  70208. 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()];
  70209. BoneLookController._tmpQuat = BABYLON.Quaternion.Identity();
  70210. BoneLookController._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  70211. return BoneLookController;
  70212. }());
  70213. BABYLON.BoneLookController = BoneLookController;
  70214. })(BABYLON || (BABYLON = {}));
  70215. //# sourceMappingURL=babylon.boneLookController.js.map
  70216. var BABYLON;
  70217. (function (BABYLON) {
  70218. var Skeleton = /** @class */ (function () {
  70219. function Skeleton(name, id, scene) {
  70220. this.name = name;
  70221. this.id = id;
  70222. this.bones = new Array();
  70223. this.needInitialSkinMatrix = false;
  70224. this._isDirty = true;
  70225. this._meshesWithPoseMatrix = new Array();
  70226. this._identity = BABYLON.Matrix.Identity();
  70227. this._ranges = {};
  70228. this._lastAbsoluteTransformsUpdateId = -1;
  70229. /**
  70230. * Specifies if the skeleton should be serialized.
  70231. */
  70232. this.doNotSerialize = false;
  70233. // Events
  70234. /**
  70235. * An event triggered before computing the skeleton's matrices
  70236. * @type {BABYLON.Observable}
  70237. */
  70238. this.onBeforeComputeObservable = new BABYLON.Observable();
  70239. this.bones = [];
  70240. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  70241. scene.skeletons.push(this);
  70242. //make sure it will recalculate the matrix next time prepare is called.
  70243. this._isDirty = true;
  70244. }
  70245. // Members
  70246. Skeleton.prototype.getTransformMatrices = function (mesh) {
  70247. if (this.needInitialSkinMatrix && mesh._bonesTransformMatrices) {
  70248. return mesh._bonesTransformMatrices;
  70249. }
  70250. if (!this._transformMatrices) {
  70251. this.prepare();
  70252. }
  70253. return this._transformMatrices;
  70254. };
  70255. Skeleton.prototype.getScene = function () {
  70256. return this._scene;
  70257. };
  70258. // Methods
  70259. /**
  70260. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  70261. */
  70262. Skeleton.prototype.toString = function (fullDetails) {
  70263. var ret = "Name: " + this.name + ", nBones: " + this.bones.length;
  70264. ret += ", nAnimationRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  70265. if (fullDetails) {
  70266. ret += ", Ranges: {";
  70267. var first = true;
  70268. for (var name_1 in this._ranges) {
  70269. if (first) {
  70270. ret += ", ";
  70271. first = false;
  70272. }
  70273. ret += name_1;
  70274. }
  70275. ret += "}";
  70276. }
  70277. return ret;
  70278. };
  70279. /**
  70280. * Get bone's index searching by name
  70281. * @param {string} name is bone's name to search for
  70282. * @return {number} Indice of the bone. Returns -1 if not found
  70283. */
  70284. Skeleton.prototype.getBoneIndexByName = function (name) {
  70285. for (var boneIndex = 0, cache = this.bones.length; boneIndex < cache; boneIndex++) {
  70286. if (this.bones[boneIndex].name === name) {
  70287. return boneIndex;
  70288. }
  70289. }
  70290. return -1;
  70291. };
  70292. Skeleton.prototype.createAnimationRange = function (name, from, to) {
  70293. // check name not already in use
  70294. if (!this._ranges[name]) {
  70295. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  70296. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  70297. if (this.bones[i].animations[0]) {
  70298. this.bones[i].animations[0].createRange(name, from, to);
  70299. }
  70300. }
  70301. }
  70302. };
  70303. Skeleton.prototype.deleteAnimationRange = function (name, deleteFrames) {
  70304. if (deleteFrames === void 0) { deleteFrames = true; }
  70305. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  70306. if (this.bones[i].animations[0]) {
  70307. this.bones[i].animations[0].deleteRange(name, deleteFrames);
  70308. }
  70309. }
  70310. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  70311. };
  70312. Skeleton.prototype.getAnimationRange = function (name) {
  70313. return this._ranges[name];
  70314. };
  70315. /**
  70316. * Returns as an Array, all AnimationRanges defined on this skeleton
  70317. */
  70318. Skeleton.prototype.getAnimationRanges = function () {
  70319. var animationRanges = [];
  70320. var name;
  70321. var i = 0;
  70322. for (name in this._ranges) {
  70323. animationRanges[i] = this._ranges[name];
  70324. i++;
  70325. }
  70326. return animationRanges;
  70327. };
  70328. /**
  70329. * note: This is not for a complete retargeting, only between very similar skeleton's with only possible bone length differences
  70330. */
  70331. Skeleton.prototype.copyAnimationRange = function (source, name, rescaleAsRequired) {
  70332. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  70333. if (this._ranges[name] || !source.getAnimationRange(name)) {
  70334. return false;
  70335. }
  70336. var ret = true;
  70337. var frameOffset = this._getHighestAnimationFrame() + 1;
  70338. // make a dictionary of source skeleton's bones, so exact same order or doublely nested loop is not required
  70339. var boneDict = {};
  70340. var sourceBones = source.bones;
  70341. var nBones;
  70342. var i;
  70343. for (i = 0, nBones = sourceBones.length; i < nBones; i++) {
  70344. boneDict[sourceBones[i].name] = sourceBones[i];
  70345. }
  70346. if (this.bones.length !== sourceBones.length) {
  70347. BABYLON.Tools.Warn("copyAnimationRange: this rig has " + this.bones.length + " bones, while source as " + sourceBones.length);
  70348. ret = false;
  70349. }
  70350. var skelDimensionsRatio = (rescaleAsRequired && this.dimensionsAtRest && source.dimensionsAtRest) ? this.dimensionsAtRest.divide(source.dimensionsAtRest) : null;
  70351. for (i = 0, nBones = this.bones.length; i < nBones; i++) {
  70352. var boneName = this.bones[i].name;
  70353. var sourceBone = boneDict[boneName];
  70354. if (sourceBone) {
  70355. ret = ret && this.bones[i].copyAnimationRange(sourceBone, name, frameOffset, rescaleAsRequired, skelDimensionsRatio);
  70356. }
  70357. else {
  70358. BABYLON.Tools.Warn("copyAnimationRange: not same rig, missing source bone " + boneName);
  70359. ret = false;
  70360. }
  70361. }
  70362. // do not call createAnimationRange(), since it also is done to bones, which was already done
  70363. var range = source.getAnimationRange(name);
  70364. if (range) {
  70365. this._ranges[name] = new BABYLON.AnimationRange(name, range.from + frameOffset, range.to + frameOffset);
  70366. }
  70367. return ret;
  70368. };
  70369. Skeleton.prototype.returnToRest = function () {
  70370. for (var index = 0; index < this.bones.length; index++) {
  70371. this.bones[index].returnToRest();
  70372. }
  70373. };
  70374. Skeleton.prototype._getHighestAnimationFrame = function () {
  70375. var ret = 0;
  70376. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  70377. if (this.bones[i].animations[0]) {
  70378. var highest = this.bones[i].animations[0].getHighestFrame();
  70379. if (ret < highest) {
  70380. ret = highest;
  70381. }
  70382. }
  70383. }
  70384. return ret;
  70385. };
  70386. Skeleton.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  70387. var range = this.getAnimationRange(name);
  70388. if (!range) {
  70389. return null;
  70390. }
  70391. return this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  70392. };
  70393. Skeleton.prototype._markAsDirty = function () {
  70394. this._isDirty = true;
  70395. };
  70396. Skeleton.prototype._registerMeshWithPoseMatrix = function (mesh) {
  70397. this._meshesWithPoseMatrix.push(mesh);
  70398. };
  70399. Skeleton.prototype._unregisterMeshWithPoseMatrix = function (mesh) {
  70400. var index = this._meshesWithPoseMatrix.indexOf(mesh);
  70401. if (index > -1) {
  70402. this._meshesWithPoseMatrix.splice(index, 1);
  70403. }
  70404. };
  70405. Skeleton.prototype._computeTransformMatrices = function (targetMatrix, initialSkinMatrix) {
  70406. this.onBeforeComputeObservable.notifyObservers(this);
  70407. for (var index = 0; index < this.bones.length; index++) {
  70408. var bone = this.bones[index];
  70409. var parentBone = bone.getParent();
  70410. if (parentBone) {
  70411. bone.getLocalMatrix().multiplyToRef(parentBone.getWorldMatrix(), bone.getWorldMatrix());
  70412. }
  70413. else {
  70414. if (initialSkinMatrix) {
  70415. bone.getLocalMatrix().multiplyToRef(initialSkinMatrix, bone.getWorldMatrix());
  70416. }
  70417. else {
  70418. bone.getWorldMatrix().copyFrom(bone.getLocalMatrix());
  70419. }
  70420. }
  70421. if (bone._index !== -1) {
  70422. var mappedIndex = bone._index === null ? index : bone._index;
  70423. bone.getInvertedAbsoluteTransform().multiplyToArray(bone.getWorldMatrix(), targetMatrix, mappedIndex * 16);
  70424. }
  70425. }
  70426. this._identity.copyToArray(targetMatrix, this.bones.length * 16);
  70427. };
  70428. Skeleton.prototype.prepare = function () {
  70429. if (!this._isDirty) {
  70430. return;
  70431. }
  70432. if (this.needInitialSkinMatrix) {
  70433. for (var index = 0; index < this._meshesWithPoseMatrix.length; index++) {
  70434. var mesh = this._meshesWithPoseMatrix[index];
  70435. var poseMatrix = mesh.getPoseMatrix();
  70436. if (!mesh._bonesTransformMatrices || mesh._bonesTransformMatrices.length !== 16 * (this.bones.length + 1)) {
  70437. mesh._bonesTransformMatrices = new Float32Array(16 * (this.bones.length + 1));
  70438. }
  70439. if (this._synchronizedWithMesh !== mesh) {
  70440. this._synchronizedWithMesh = mesh;
  70441. // Prepare bones
  70442. for (var boneIndex = 0; boneIndex < this.bones.length; boneIndex++) {
  70443. var bone = this.bones[boneIndex];
  70444. if (!bone.getParent()) {
  70445. var matrix = bone.getBaseMatrix();
  70446. matrix.multiplyToRef(poseMatrix, BABYLON.Tmp.Matrix[1]);
  70447. bone._updateDifferenceMatrix(BABYLON.Tmp.Matrix[1]);
  70448. }
  70449. }
  70450. }
  70451. this._computeTransformMatrices(mesh._bonesTransformMatrices, poseMatrix);
  70452. }
  70453. }
  70454. else {
  70455. if (!this._transformMatrices || this._transformMatrices.length !== 16 * (this.bones.length + 1)) {
  70456. this._transformMatrices = new Float32Array(16 * (this.bones.length + 1));
  70457. }
  70458. this._computeTransformMatrices(this._transformMatrices, null);
  70459. }
  70460. this._isDirty = false;
  70461. this._scene._activeBones.addCount(this.bones.length, false);
  70462. };
  70463. Skeleton.prototype.getAnimatables = function () {
  70464. if (!this._animatables || this._animatables.length !== this.bones.length) {
  70465. this._animatables = [];
  70466. for (var index = 0; index < this.bones.length; index++) {
  70467. this._animatables.push(this.bones[index]);
  70468. }
  70469. }
  70470. return this._animatables;
  70471. };
  70472. Skeleton.prototype.clone = function (name, id) {
  70473. var result = new Skeleton(name, id || name, this._scene);
  70474. result.needInitialSkinMatrix = this.needInitialSkinMatrix;
  70475. for (var index = 0; index < this.bones.length; index++) {
  70476. var source = this.bones[index];
  70477. var parentBone = null;
  70478. var parent_1 = source.getParent();
  70479. if (parent_1) {
  70480. var parentIndex = this.bones.indexOf(parent_1);
  70481. parentBone = result.bones[parentIndex];
  70482. }
  70483. var bone = new BABYLON.Bone(source.name, result, parentBone, source.getBaseMatrix().clone(), source.getRestPose().clone());
  70484. BABYLON.Tools.DeepCopy(source.animations, bone.animations);
  70485. }
  70486. if (this._ranges) {
  70487. result._ranges = {};
  70488. for (var rangeName in this._ranges) {
  70489. var range = this._ranges[rangeName];
  70490. if (range) {
  70491. result._ranges[rangeName] = range.clone();
  70492. }
  70493. }
  70494. }
  70495. this._isDirty = true;
  70496. return result;
  70497. };
  70498. Skeleton.prototype.enableBlending = function (blendingSpeed) {
  70499. if (blendingSpeed === void 0) { blendingSpeed = 0.01; }
  70500. this.bones.forEach(function (bone) {
  70501. bone.animations.forEach(function (animation) {
  70502. animation.enableBlending = true;
  70503. animation.blendingSpeed = blendingSpeed;
  70504. });
  70505. });
  70506. };
  70507. Skeleton.prototype.dispose = function () {
  70508. this._meshesWithPoseMatrix = [];
  70509. // Animations
  70510. this.getScene().stopAnimation(this);
  70511. // Remove from scene
  70512. this.getScene().removeSkeleton(this);
  70513. };
  70514. Skeleton.prototype.serialize = function () {
  70515. var serializationObject = {};
  70516. serializationObject.name = this.name;
  70517. serializationObject.id = this.id;
  70518. serializationObject.dimensionsAtRest = this.dimensionsAtRest;
  70519. serializationObject.bones = [];
  70520. serializationObject.needInitialSkinMatrix = this.needInitialSkinMatrix;
  70521. for (var index = 0; index < this.bones.length; index++) {
  70522. var bone = this.bones[index];
  70523. var parent_2 = bone.getParent();
  70524. var serializedBone = {
  70525. parentBoneIndex: parent_2 ? this.bones.indexOf(parent_2) : -1,
  70526. name: bone.name,
  70527. matrix: bone.getBaseMatrix().toArray(),
  70528. rest: bone.getRestPose().toArray()
  70529. };
  70530. serializationObject.bones.push(serializedBone);
  70531. if (bone.length) {
  70532. serializedBone.length = bone.length;
  70533. }
  70534. if (bone.animations && bone.animations.length > 0) {
  70535. serializedBone.animation = bone.animations[0].serialize();
  70536. }
  70537. serializationObject.ranges = [];
  70538. for (var name in this._ranges) {
  70539. var source = this._ranges[name];
  70540. if (!source) {
  70541. continue;
  70542. }
  70543. var range = {};
  70544. range.name = name;
  70545. range.from = source.from;
  70546. range.to = source.to;
  70547. serializationObject.ranges.push(range);
  70548. }
  70549. }
  70550. return serializationObject;
  70551. };
  70552. Skeleton.Parse = function (parsedSkeleton, scene) {
  70553. var skeleton = new Skeleton(parsedSkeleton.name, parsedSkeleton.id, scene);
  70554. if (parsedSkeleton.dimensionsAtRest) {
  70555. skeleton.dimensionsAtRest = BABYLON.Vector3.FromArray(parsedSkeleton.dimensionsAtRest);
  70556. }
  70557. skeleton.needInitialSkinMatrix = parsedSkeleton.needInitialSkinMatrix;
  70558. var index;
  70559. for (index = 0; index < parsedSkeleton.bones.length; index++) {
  70560. var parsedBone = parsedSkeleton.bones[index];
  70561. var parentBone = null;
  70562. if (parsedBone.parentBoneIndex > -1) {
  70563. parentBone = skeleton.bones[parsedBone.parentBoneIndex];
  70564. }
  70565. var rest = parsedBone.rest ? BABYLON.Matrix.FromArray(parsedBone.rest) : null;
  70566. var bone = new BABYLON.Bone(parsedBone.name, skeleton, parentBone, BABYLON.Matrix.FromArray(parsedBone.matrix), rest);
  70567. if (parsedBone.length) {
  70568. bone.length = parsedBone.length;
  70569. }
  70570. if (parsedBone.animation) {
  70571. bone.animations.push(BABYLON.Animation.Parse(parsedBone.animation));
  70572. }
  70573. }
  70574. // placed after bones, so createAnimationRange can cascade down
  70575. if (parsedSkeleton.ranges) {
  70576. for (index = 0; index < parsedSkeleton.ranges.length; index++) {
  70577. var data = parsedSkeleton.ranges[index];
  70578. skeleton.createAnimationRange(data.name, data.from, data.to);
  70579. }
  70580. }
  70581. return skeleton;
  70582. };
  70583. Skeleton.prototype.computeAbsoluteTransforms = function (forceUpdate) {
  70584. if (forceUpdate === void 0) { forceUpdate = false; }
  70585. var renderId = this._scene.getRenderId();
  70586. if (this._lastAbsoluteTransformsUpdateId != renderId || forceUpdate) {
  70587. this.bones[0].computeAbsoluteTransforms();
  70588. this._lastAbsoluteTransformsUpdateId = renderId;
  70589. }
  70590. };
  70591. Skeleton.prototype.getPoseMatrix = function () {
  70592. var poseMatrix = null;
  70593. if (this._meshesWithPoseMatrix.length > 0) {
  70594. poseMatrix = this._meshesWithPoseMatrix[0].getPoseMatrix();
  70595. }
  70596. return poseMatrix;
  70597. };
  70598. Skeleton.prototype.sortBones = function () {
  70599. var bones = new Array();
  70600. var visited = new Array(this.bones.length);
  70601. for (var index = 0; index < this.bones.length; index++) {
  70602. this._sortBones(index, bones, visited);
  70603. }
  70604. this.bones = bones;
  70605. };
  70606. Skeleton.prototype._sortBones = function (index, bones, visited) {
  70607. if (visited[index]) {
  70608. return;
  70609. }
  70610. visited[index] = true;
  70611. var bone = this.bones[index];
  70612. if (bone._index === undefined) {
  70613. bone._index = index;
  70614. }
  70615. var parentBone = bone.getParent();
  70616. if (parentBone) {
  70617. this._sortBones(this.bones.indexOf(parentBone), bones, visited);
  70618. }
  70619. bones.push(bone);
  70620. };
  70621. return Skeleton;
  70622. }());
  70623. BABYLON.Skeleton = Skeleton;
  70624. })(BABYLON || (BABYLON = {}));
  70625. //# sourceMappingURL=babylon.skeleton.js.map
  70626. var BABYLON;
  70627. (function (BABYLON) {
  70628. var SphericalPolynomial = /** @class */ (function () {
  70629. function SphericalPolynomial() {
  70630. this.x = BABYLON.Vector3.Zero();
  70631. this.y = BABYLON.Vector3.Zero();
  70632. this.z = BABYLON.Vector3.Zero();
  70633. this.xx = BABYLON.Vector3.Zero();
  70634. this.yy = BABYLON.Vector3.Zero();
  70635. this.zz = BABYLON.Vector3.Zero();
  70636. this.xy = BABYLON.Vector3.Zero();
  70637. this.yz = BABYLON.Vector3.Zero();
  70638. this.zx = BABYLON.Vector3.Zero();
  70639. }
  70640. SphericalPolynomial.prototype.addAmbient = function (color) {
  70641. var colorVector = new BABYLON.Vector3(color.r, color.g, color.b);
  70642. this.xx = this.xx.add(colorVector);
  70643. this.yy = this.yy.add(colorVector);
  70644. this.zz = this.zz.add(colorVector);
  70645. };
  70646. SphericalPolynomial.getSphericalPolynomialFromHarmonics = function (harmonics) {
  70647. var result = new SphericalPolynomial();
  70648. result.x = harmonics.L11.scale(1.02333);
  70649. result.y = harmonics.L1_1.scale(1.02333);
  70650. result.z = harmonics.L10.scale(1.02333);
  70651. result.xx = harmonics.L00.scale(0.886277).subtract(harmonics.L20.scale(0.247708)).add(harmonics.L22.scale(0.429043));
  70652. result.yy = harmonics.L00.scale(0.886277).subtract(harmonics.L20.scale(0.247708)).subtract(harmonics.L22.scale(0.429043));
  70653. result.zz = harmonics.L00.scale(0.886277).add(harmonics.L20.scale(0.495417));
  70654. result.yz = harmonics.L2_1.scale(0.858086);
  70655. result.zx = harmonics.L21.scale(0.858086);
  70656. result.xy = harmonics.L2_2.scale(0.858086);
  70657. result.scale(1.0 / Math.PI);
  70658. return result;
  70659. };
  70660. SphericalPolynomial.prototype.scale = function (scale) {
  70661. this.x = this.x.scale(scale);
  70662. this.y = this.y.scale(scale);
  70663. this.z = this.z.scale(scale);
  70664. this.xx = this.xx.scale(scale);
  70665. this.yy = this.yy.scale(scale);
  70666. this.zz = this.zz.scale(scale);
  70667. this.yz = this.yz.scale(scale);
  70668. this.zx = this.zx.scale(scale);
  70669. this.xy = this.xy.scale(scale);
  70670. };
  70671. return SphericalPolynomial;
  70672. }());
  70673. BABYLON.SphericalPolynomial = SphericalPolynomial;
  70674. var SphericalHarmonics = /** @class */ (function () {
  70675. function SphericalHarmonics() {
  70676. this.L00 = BABYLON.Vector3.Zero();
  70677. this.L1_1 = BABYLON.Vector3.Zero();
  70678. this.L10 = BABYLON.Vector3.Zero();
  70679. this.L11 = BABYLON.Vector3.Zero();
  70680. this.L2_2 = BABYLON.Vector3.Zero();
  70681. this.L2_1 = BABYLON.Vector3.Zero();
  70682. this.L20 = BABYLON.Vector3.Zero();
  70683. this.L21 = BABYLON.Vector3.Zero();
  70684. this.L22 = BABYLON.Vector3.Zero();
  70685. }
  70686. SphericalHarmonics.prototype.addLight = function (direction, color, deltaSolidAngle) {
  70687. var colorVector = new BABYLON.Vector3(color.r, color.g, color.b);
  70688. var c = colorVector.scale(deltaSolidAngle);
  70689. this.L00 = this.L00.add(c.scale(0.282095));
  70690. this.L1_1 = this.L1_1.add(c.scale(0.488603 * direction.y));
  70691. this.L10 = this.L10.add(c.scale(0.488603 * direction.z));
  70692. this.L11 = this.L11.add(c.scale(0.488603 * direction.x));
  70693. this.L2_2 = this.L2_2.add(c.scale(1.092548 * direction.x * direction.y));
  70694. this.L2_1 = this.L2_1.add(c.scale(1.092548 * direction.y * direction.z));
  70695. this.L21 = this.L21.add(c.scale(1.092548 * direction.x * direction.z));
  70696. this.L20 = this.L20.add(c.scale(0.315392 * (3.0 * direction.z * direction.z - 1.0)));
  70697. this.L22 = this.L22.add(c.scale(0.546274 * (direction.x * direction.x - direction.y * direction.y)));
  70698. };
  70699. SphericalHarmonics.prototype.scale = function (scale) {
  70700. this.L00 = this.L00.scale(scale);
  70701. this.L1_1 = this.L1_1.scale(scale);
  70702. this.L10 = this.L10.scale(scale);
  70703. this.L11 = this.L11.scale(scale);
  70704. this.L2_2 = this.L2_2.scale(scale);
  70705. this.L2_1 = this.L2_1.scale(scale);
  70706. this.L20 = this.L20.scale(scale);
  70707. this.L21 = this.L21.scale(scale);
  70708. this.L22 = this.L22.scale(scale);
  70709. };
  70710. SphericalHarmonics.prototype.convertIncidentRadianceToIrradiance = function () {
  70711. // Convert from incident radiance (Li) to irradiance (E) by applying convolution with the cosine-weighted hemisphere.
  70712. //
  70713. // E_lm = A_l * L_lm
  70714. //
  70715. // In spherical harmonics this convolution amounts to scaling factors for each frequency band.
  70716. // This corresponds to equation 5 in "An Efficient Representation for Irradiance Environment Maps", where
  70717. // the scaling factors are given in equation 9.
  70718. // Constant (Band 0)
  70719. this.L00 = this.L00.scale(3.141593);
  70720. // Linear (Band 1)
  70721. this.L1_1 = this.L1_1.scale(2.094395);
  70722. this.L10 = this.L10.scale(2.094395);
  70723. this.L11 = this.L11.scale(2.094395);
  70724. // Quadratic (Band 2)
  70725. this.L2_2 = this.L2_2.scale(0.785398);
  70726. this.L2_1 = this.L2_1.scale(0.785398);
  70727. this.L20 = this.L20.scale(0.785398);
  70728. this.L21 = this.L21.scale(0.785398);
  70729. this.L22 = this.L22.scale(0.785398);
  70730. };
  70731. SphericalHarmonics.prototype.convertIrradianceToLambertianRadiance = function () {
  70732. // Convert from irradiance to outgoing radiance for Lambertian BDRF, suitable for efficient shader evaluation.
  70733. // L = (1/pi) * E * rho
  70734. //
  70735. // This is done by an additional scale by 1/pi, so is a fairly trivial operation but important conceptually.
  70736. this.scale(1.0 / Math.PI);
  70737. // The resultant SH now represents outgoing radiance, so includes the Lambert 1/pi normalisation factor but without albedo (rho) applied
  70738. // (The pixel shader must apply albedo after texture fetches, etc).
  70739. };
  70740. SphericalHarmonics.getsphericalHarmonicsFromPolynomial = function (polynomial) {
  70741. var result = new SphericalHarmonics();
  70742. result.L00 = polynomial.xx.scale(0.376127).add(polynomial.yy.scale(0.376127)).add(polynomial.zz.scale(0.376126));
  70743. result.L1_1 = polynomial.y.scale(0.977204);
  70744. result.L10 = polynomial.z.scale(0.977204);
  70745. result.L11 = polynomial.x.scale(0.977204);
  70746. result.L2_2 = polynomial.xy.scale(1.16538);
  70747. result.L2_1 = polynomial.yz.scale(1.16538);
  70748. result.L20 = polynomial.zz.scale(1.34567).subtract(polynomial.xx.scale(0.672834)).subtract(polynomial.yy.scale(0.672834));
  70749. result.L21 = polynomial.zx.scale(1.16538);
  70750. result.L22 = polynomial.xx.scale(1.16538).subtract(polynomial.yy.scale(1.16538));
  70751. result.scale(Math.PI);
  70752. return result;
  70753. };
  70754. return SphericalHarmonics;
  70755. }());
  70756. BABYLON.SphericalHarmonics = SphericalHarmonics;
  70757. })(BABYLON || (BABYLON = {}));
  70758. //# sourceMappingURL=babylon.sphericalPolynomial.js.map
  70759. var BABYLON;
  70760. (function (BABYLON) {
  70761. var FileFaceOrientation = /** @class */ (function () {
  70762. function FileFaceOrientation(name, worldAxisForNormal, worldAxisForFileX, worldAxisForFileY) {
  70763. this.name = name;
  70764. this.worldAxisForNormal = worldAxisForNormal;
  70765. this.worldAxisForFileX = worldAxisForFileX;
  70766. this.worldAxisForFileY = worldAxisForFileY;
  70767. }
  70768. return FileFaceOrientation;
  70769. }());
  70770. ;
  70771. /**
  70772. * Helper class dealing with the extraction of spherical polynomial dataArray
  70773. * from a cube map.
  70774. */
  70775. var CubeMapToSphericalPolynomialTools = /** @class */ (function () {
  70776. function CubeMapToSphericalPolynomialTools() {
  70777. }
  70778. /**
  70779. * Converts a texture to the according Spherical Polynomial data.
  70780. * This extracts the first 3 orders only as they are the only one used in the lighting.
  70781. *
  70782. * @param texture The texture to extract the information from.
  70783. * @return The Spherical Polynomial data.
  70784. */
  70785. CubeMapToSphericalPolynomialTools.ConvertCubeMapTextureToSphericalPolynomial = function (texture) {
  70786. if (!texture.isCube) {
  70787. // Only supports cube Textures currently.
  70788. return null;
  70789. }
  70790. var size = texture.getSize().width;
  70791. var right = texture.readPixels(0);
  70792. var left = texture.readPixels(1);
  70793. var up;
  70794. var down;
  70795. if (texture.isRenderTarget) {
  70796. up = texture.readPixels(3);
  70797. down = texture.readPixels(2);
  70798. }
  70799. else {
  70800. up = texture.readPixels(2);
  70801. down = texture.readPixels(3);
  70802. }
  70803. var front = texture.readPixels(4);
  70804. var back = texture.readPixels(5);
  70805. var gammaSpace = texture.gammaSpace;
  70806. // Always read as RGBA.
  70807. var format = BABYLON.Engine.TEXTUREFORMAT_RGBA;
  70808. var type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  70809. if (texture.textureType && texture.textureType !== BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  70810. type = BABYLON.Engine.TEXTURETYPE_FLOAT;
  70811. }
  70812. var cubeInfo = {
  70813. size: size,
  70814. right: right,
  70815. left: left,
  70816. up: up,
  70817. down: down,
  70818. front: front,
  70819. back: back,
  70820. format: format,
  70821. type: type,
  70822. gammaSpace: gammaSpace,
  70823. };
  70824. return this.ConvertCubeMapToSphericalPolynomial(cubeInfo);
  70825. };
  70826. /**
  70827. * Converts a cubemap to the according Spherical Polynomial data.
  70828. * This extracts the first 3 orders only as they are the only one used in the lighting.
  70829. *
  70830. * @param cubeInfo The Cube map to extract the information from.
  70831. * @return The Spherical Polynomial data.
  70832. */
  70833. CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial = function (cubeInfo) {
  70834. var sphericalHarmonics = new BABYLON.SphericalHarmonics();
  70835. var totalSolidAngle = 0.0;
  70836. // The (u,v) range is [-1,+1], so the distance between each texel is 2/Size.
  70837. var du = 2.0 / cubeInfo.size;
  70838. var dv = du;
  70839. // The (u,v) of the first texel is half a texel from the corner (-1,-1).
  70840. var minUV = du * 0.5 - 1.0;
  70841. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  70842. var fileFace = this.FileFaces[faceIndex];
  70843. var dataArray = cubeInfo[fileFace.name];
  70844. var v = minUV;
  70845. // TODO: we could perform the summation directly into a SphericalPolynomial (SP), which is more efficient than SphericalHarmonic (SH).
  70846. // This is possible because during the summation we do not need the SH-specific properties, e.g. orthogonality.
  70847. // Because SP is still linear, so summation is fine in that basis.
  70848. var stride = cubeInfo.format === BABYLON.Engine.TEXTUREFORMAT_RGBA ? 4 : 3;
  70849. for (var y = 0; y < cubeInfo.size; y++) {
  70850. var u = minUV;
  70851. for (var x = 0; x < cubeInfo.size; x++) {
  70852. // World direction (not normalised)
  70853. var worldDirection = fileFace.worldAxisForFileX.scale(u).add(fileFace.worldAxisForFileY.scale(v)).add(fileFace.worldAxisForNormal);
  70854. worldDirection.normalize();
  70855. var deltaSolidAngle = Math.pow(1.0 + u * u + v * v, -3.0 / 2.0);
  70856. var r = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 0];
  70857. var g = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 1];
  70858. var b = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 2];
  70859. // Handle Integer types.
  70860. if (cubeInfo.type === BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  70861. r /= 255;
  70862. g /= 255;
  70863. b /= 255;
  70864. }
  70865. // Handle Gamma space textures.
  70866. if (cubeInfo.gammaSpace) {
  70867. r = Math.pow(BABYLON.Scalar.Clamp(r), BABYLON.ToLinearSpace);
  70868. g = Math.pow(BABYLON.Scalar.Clamp(g), BABYLON.ToLinearSpace);
  70869. b = Math.pow(BABYLON.Scalar.Clamp(b), BABYLON.ToLinearSpace);
  70870. }
  70871. var color = new BABYLON.Color3(r, g, b);
  70872. sphericalHarmonics.addLight(worldDirection, color, deltaSolidAngle);
  70873. totalSolidAngle += deltaSolidAngle;
  70874. u += du;
  70875. }
  70876. v += dv;
  70877. }
  70878. }
  70879. // Solid angle for entire sphere is 4*pi
  70880. var sphereSolidAngle = 4.0 * Math.PI;
  70881. // Adjust the solid angle to allow for how many faces we processed.
  70882. var facesProcessed = 6.0;
  70883. var expectedSolidAngle = sphereSolidAngle * facesProcessed / 6.0;
  70884. // Adjust the harmonics so that the accumulated solid angle matches the expected solid angle.
  70885. // This is needed because the numerical integration over the cube uses a
  70886. // small angle approximation of solid angle for each texel (see deltaSolidAngle),
  70887. // and also to compensate for accumulative error due to float precision in the summation.
  70888. var correctionFactor = expectedSolidAngle / totalSolidAngle;
  70889. sphericalHarmonics.scale(correctionFactor);
  70890. sphericalHarmonics.convertIncidentRadianceToIrradiance();
  70891. sphericalHarmonics.convertIrradianceToLambertianRadiance();
  70892. return BABYLON.SphericalPolynomial.getSphericalPolynomialFromHarmonics(sphericalHarmonics);
  70893. };
  70894. CubeMapToSphericalPolynomialTools.FileFaces = [
  70895. new FileFaceOrientation("right", new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(0, -1, 0)),
  70896. new FileFaceOrientation("left", new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(0, -1, 0)),
  70897. new FileFaceOrientation("up", new BABYLON.Vector3(0, 1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, 1)),
  70898. new FileFaceOrientation("down", new BABYLON.Vector3(0, -1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1)),
  70899. new FileFaceOrientation("front", new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, -1, 0)),
  70900. new FileFaceOrientation("back", new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, -1, 0)) // -Z bottom
  70901. ];
  70902. return CubeMapToSphericalPolynomialTools;
  70903. }());
  70904. BABYLON.CubeMapToSphericalPolynomialTools = CubeMapToSphericalPolynomialTools;
  70905. })(BABYLON || (BABYLON = {}));
  70906. //# sourceMappingURL=babylon.cubemapToSphericalPolynomial.js.map
  70907. var BABYLON;
  70908. (function (BABYLON) {
  70909. /**
  70910. * Helper class usefull to convert panorama picture to their cubemap representation in 6 faces.
  70911. */
  70912. var PanoramaToCubeMapTools = /** @class */ (function () {
  70913. function PanoramaToCubeMapTools() {
  70914. }
  70915. /**
  70916. * Converts a panorma stored in RGB right to left up to down format into a cubemap (6 faces).
  70917. *
  70918. * @param float32Array The source data.
  70919. * @param inputWidth The width of the input panorama.
  70920. * @param inputhHeight The height of the input panorama.
  70921. * @param size The willing size of the generated cubemap (each faces will be size * size pixels)
  70922. * @return The cubemap data
  70923. */
  70924. PanoramaToCubeMapTools.ConvertPanoramaToCubemap = function (float32Array, inputWidth, inputHeight, size) {
  70925. if (!float32Array) {
  70926. throw "ConvertPanoramaToCubemap: input cannot be null";
  70927. }
  70928. if (float32Array.length != inputWidth * inputHeight * 3) {
  70929. throw "ConvertPanoramaToCubemap: input size is wrong";
  70930. }
  70931. var textureFront = this.CreateCubemapTexture(size, this.FACE_FRONT, float32Array, inputWidth, inputHeight);
  70932. var textureBack = this.CreateCubemapTexture(size, this.FACE_BACK, float32Array, inputWidth, inputHeight);
  70933. var textureLeft = this.CreateCubemapTexture(size, this.FACE_LEFT, float32Array, inputWidth, inputHeight);
  70934. var textureRight = this.CreateCubemapTexture(size, this.FACE_RIGHT, float32Array, inputWidth, inputHeight);
  70935. var textureUp = this.CreateCubemapTexture(size, this.FACE_UP, float32Array, inputWidth, inputHeight);
  70936. var textureDown = this.CreateCubemapTexture(size, this.FACE_DOWN, float32Array, inputWidth, inputHeight);
  70937. return {
  70938. front: textureFront,
  70939. back: textureBack,
  70940. left: textureLeft,
  70941. right: textureRight,
  70942. up: textureUp,
  70943. down: textureDown,
  70944. size: size,
  70945. type: BABYLON.Engine.TEXTURETYPE_FLOAT,
  70946. format: BABYLON.Engine.TEXTUREFORMAT_RGB,
  70947. gammaSpace: false,
  70948. };
  70949. };
  70950. PanoramaToCubeMapTools.CreateCubemapTexture = function (texSize, faceData, float32Array, inputWidth, inputHeight) {
  70951. var buffer = new ArrayBuffer(texSize * texSize * 4 * 3);
  70952. var textureArray = new Float32Array(buffer);
  70953. var rotDX1 = faceData[1].subtract(faceData[0]).scale(1 / texSize);
  70954. var rotDX2 = faceData[3].subtract(faceData[2]).scale(1 / texSize);
  70955. var dy = 1 / texSize;
  70956. var fy = 0;
  70957. for (var y = 0; y < texSize; y++) {
  70958. var xv1 = faceData[0];
  70959. var xv2 = faceData[2];
  70960. for (var x = 0; x < texSize; x++) {
  70961. var v = xv2.subtract(xv1).scale(fy).add(xv1);
  70962. v.normalize();
  70963. var color = this.CalcProjectionSpherical(v, float32Array, inputWidth, inputHeight);
  70964. // 3 channels per pixels
  70965. textureArray[y * texSize * 3 + (x * 3) + 0] = color.r;
  70966. textureArray[y * texSize * 3 + (x * 3) + 1] = color.g;
  70967. textureArray[y * texSize * 3 + (x * 3) + 2] = color.b;
  70968. xv1 = xv1.add(rotDX1);
  70969. xv2 = xv2.add(rotDX2);
  70970. }
  70971. fy += dy;
  70972. }
  70973. return textureArray;
  70974. };
  70975. PanoramaToCubeMapTools.CalcProjectionSpherical = function (vDir, float32Array, inputWidth, inputHeight) {
  70976. var theta = Math.atan2(vDir.z, vDir.x);
  70977. var phi = Math.acos(vDir.y);
  70978. while (theta < -Math.PI)
  70979. theta += 2 * Math.PI;
  70980. while (theta > Math.PI)
  70981. theta -= 2 * Math.PI;
  70982. var dx = theta / Math.PI;
  70983. var dy = phi / Math.PI;
  70984. // recenter.
  70985. dx = dx * 0.5 + 0.5;
  70986. var px = Math.round(dx * inputWidth);
  70987. if (px < 0)
  70988. px = 0;
  70989. else if (px >= inputWidth)
  70990. px = inputWidth - 1;
  70991. var py = Math.round(dy * inputHeight);
  70992. if (py < 0)
  70993. py = 0;
  70994. else if (py >= inputHeight)
  70995. py = inputHeight - 1;
  70996. var inputY = (inputHeight - py - 1);
  70997. var r = float32Array[inputY * inputWidth * 3 + (px * 3) + 0];
  70998. var g = float32Array[inputY * inputWidth * 3 + (px * 3) + 1];
  70999. var b = float32Array[inputY * inputWidth * 3 + (px * 3) + 2];
  71000. return {
  71001. r: r,
  71002. g: g,
  71003. b: b
  71004. };
  71005. };
  71006. PanoramaToCubeMapTools.FACE_FRONT = [
  71007. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  71008. new BABYLON.Vector3(1.0, -1.0, -1.0),
  71009. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  71010. new BABYLON.Vector3(1.0, 1.0, -1.0)
  71011. ];
  71012. PanoramaToCubeMapTools.FACE_BACK = [
  71013. new BABYLON.Vector3(1.0, -1.0, 1.0),
  71014. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  71015. new BABYLON.Vector3(1.0, 1.0, 1.0),
  71016. new BABYLON.Vector3(-1.0, 1.0, 1.0)
  71017. ];
  71018. PanoramaToCubeMapTools.FACE_RIGHT = [
  71019. new BABYLON.Vector3(1.0, -1.0, -1.0),
  71020. new BABYLON.Vector3(1.0, -1.0, 1.0),
  71021. new BABYLON.Vector3(1.0, 1.0, -1.0),
  71022. new BABYLON.Vector3(1.0, 1.0, 1.0)
  71023. ];
  71024. PanoramaToCubeMapTools.FACE_LEFT = [
  71025. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  71026. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  71027. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  71028. new BABYLON.Vector3(-1.0, 1.0, -1.0)
  71029. ];
  71030. PanoramaToCubeMapTools.FACE_DOWN = [
  71031. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  71032. new BABYLON.Vector3(1.0, 1.0, -1.0),
  71033. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  71034. new BABYLON.Vector3(1.0, 1.0, 1.0)
  71035. ];
  71036. PanoramaToCubeMapTools.FACE_UP = [
  71037. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  71038. new BABYLON.Vector3(1.0, -1.0, 1.0),
  71039. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  71040. new BABYLON.Vector3(1.0, -1.0, -1.0)
  71041. ];
  71042. return PanoramaToCubeMapTools;
  71043. }());
  71044. BABYLON.PanoramaToCubeMapTools = PanoramaToCubeMapTools;
  71045. })(BABYLON || (BABYLON = {}));
  71046. //# sourceMappingURL=babylon.panoramaToCubemap.js.map
  71047. var BABYLON;
  71048. (function (BABYLON) {
  71049. ;
  71050. /**
  71051. * This groups tools to convert HDR texture to native colors array.
  71052. */
  71053. var HDRTools = /** @class */ (function () {
  71054. function HDRTools() {
  71055. }
  71056. HDRTools.Ldexp = function (mantissa, exponent) {
  71057. if (exponent > 1023) {
  71058. return mantissa * Math.pow(2, 1023) * Math.pow(2, exponent - 1023);
  71059. }
  71060. if (exponent < -1074) {
  71061. return mantissa * Math.pow(2, -1074) * Math.pow(2, exponent + 1074);
  71062. }
  71063. return mantissa * Math.pow(2, exponent);
  71064. };
  71065. HDRTools.Rgbe2float = function (float32array, red, green, blue, exponent, index) {
  71066. if (exponent > 0) {
  71067. exponent = this.Ldexp(1.0, exponent - (128 + 8));
  71068. float32array[index + 0] = red * exponent;
  71069. float32array[index + 1] = green * exponent;
  71070. float32array[index + 2] = blue * exponent;
  71071. }
  71072. else {
  71073. float32array[index + 0] = 0;
  71074. float32array[index + 1] = 0;
  71075. float32array[index + 2] = 0;
  71076. }
  71077. };
  71078. HDRTools.readStringLine = function (uint8array, startIndex) {
  71079. var line = "";
  71080. var character = "";
  71081. for (var i = startIndex; i < uint8array.length - startIndex; i++) {
  71082. character = String.fromCharCode(uint8array[i]);
  71083. if (character == "\n") {
  71084. break;
  71085. }
  71086. line += character;
  71087. }
  71088. return line;
  71089. };
  71090. /**
  71091. * Reads header information from an RGBE texture stored in a native array.
  71092. * More information on this format are available here:
  71093. * https://en.wikipedia.org/wiki/RGBE_image_format
  71094. *
  71095. * @param uint8array The binary file stored in native array.
  71096. * @return The header information.
  71097. */
  71098. HDRTools.RGBE_ReadHeader = function (uint8array) {
  71099. var height = 0;
  71100. var width = 0;
  71101. var line = this.readStringLine(uint8array, 0);
  71102. if (line[0] != '#' || line[1] != '?') {
  71103. throw "Bad HDR Format.";
  71104. }
  71105. var endOfHeader = false;
  71106. var findFormat = false;
  71107. var lineIndex = 0;
  71108. do {
  71109. lineIndex += (line.length + 1);
  71110. line = this.readStringLine(uint8array, lineIndex);
  71111. if (line == "FORMAT=32-bit_rle_rgbe") {
  71112. findFormat = true;
  71113. }
  71114. else if (line.length == 0) {
  71115. endOfHeader = true;
  71116. }
  71117. } while (!endOfHeader);
  71118. if (!findFormat) {
  71119. throw "HDR Bad header format, unsupported FORMAT";
  71120. }
  71121. lineIndex += (line.length + 1);
  71122. line = this.readStringLine(uint8array, lineIndex);
  71123. var sizeRegexp = /^\-Y (.*) \+X (.*)$/g;
  71124. var match = sizeRegexp.exec(line);
  71125. // TODO. Support +Y and -X if needed.
  71126. if (!match || match.length < 3) {
  71127. throw "HDR Bad header format, no size";
  71128. }
  71129. width = parseInt(match[2]);
  71130. height = parseInt(match[1]);
  71131. if (width < 8 || width > 0x7fff) {
  71132. throw "HDR Bad header format, unsupported size";
  71133. }
  71134. lineIndex += (line.length + 1);
  71135. return {
  71136. height: height,
  71137. width: width,
  71138. dataPosition: lineIndex
  71139. };
  71140. };
  71141. /**
  71142. * Returns the cubemap information (each faces texture data) extracted from an RGBE texture.
  71143. * This RGBE texture needs to store the information as a panorama.
  71144. *
  71145. * More information on this format are available here:
  71146. * https://en.wikipedia.org/wiki/RGBE_image_format
  71147. *
  71148. * @param buffer The binary file stored in an array buffer.
  71149. * @param size The expected size of the extracted cubemap.
  71150. * @return The Cube Map information.
  71151. */
  71152. HDRTools.GetCubeMapTextureData = function (buffer, size) {
  71153. var uint8array = new Uint8Array(buffer);
  71154. var hdrInfo = this.RGBE_ReadHeader(uint8array);
  71155. var data = this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  71156. var cubeMapData = BABYLON.PanoramaToCubeMapTools.ConvertPanoramaToCubemap(data, hdrInfo.width, hdrInfo.height, size);
  71157. return cubeMapData;
  71158. };
  71159. /**
  71160. * Returns the pixels data extracted from an RGBE texture.
  71161. * This pixels will be stored left to right up to down in the R G B order in one array.
  71162. *
  71163. * More information on this format are available here:
  71164. * https://en.wikipedia.org/wiki/RGBE_image_format
  71165. *
  71166. * @param uint8array The binary file stored in an array buffer.
  71167. * @param hdrInfo The header information of the file.
  71168. * @return The pixels data in RGB right to left up to down order.
  71169. */
  71170. HDRTools.RGBE_ReadPixels = function (uint8array, hdrInfo) {
  71171. // Keep for multi format supports.
  71172. return this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  71173. };
  71174. HDRTools.RGBE_ReadPixels_RLE = function (uint8array, hdrInfo) {
  71175. var num_scanlines = hdrInfo.height;
  71176. var scanline_width = hdrInfo.width;
  71177. var a, b, c, d, count;
  71178. var dataIndex = hdrInfo.dataPosition;
  71179. var index = 0, endIndex = 0, i = 0;
  71180. var scanLineArrayBuffer = new ArrayBuffer(scanline_width * 4); // four channel R G B E
  71181. var scanLineArray = new Uint8Array(scanLineArrayBuffer);
  71182. // 3 channels of 4 bytes per pixel in float.
  71183. var resultBuffer = new ArrayBuffer(hdrInfo.width * hdrInfo.height * 4 * 3);
  71184. var resultArray = new Float32Array(resultBuffer);
  71185. // read in each successive scanline
  71186. while (num_scanlines > 0) {
  71187. a = uint8array[dataIndex++];
  71188. b = uint8array[dataIndex++];
  71189. c = uint8array[dataIndex++];
  71190. d = uint8array[dataIndex++];
  71191. if (a != 2 || b != 2 || (c & 0x80)) {
  71192. // this file is not run length encoded
  71193. throw "HDR Bad header format, not RLE";
  71194. }
  71195. if (((c << 8) | d) != scanline_width) {
  71196. throw "HDR Bad header format, wrong scan line width";
  71197. }
  71198. index = 0;
  71199. // read each of the four channels for the scanline into the buffer
  71200. for (i = 0; i < 4; i++) {
  71201. endIndex = (i + 1) * scanline_width;
  71202. while (index < endIndex) {
  71203. a = uint8array[dataIndex++];
  71204. b = uint8array[dataIndex++];
  71205. if (a > 128) {
  71206. // a run of the same value
  71207. count = a - 128;
  71208. if ((count == 0) || (count > endIndex - index)) {
  71209. throw "HDR Bad Format, bad scanline data (run)";
  71210. }
  71211. while (count-- > 0) {
  71212. scanLineArray[index++] = b;
  71213. }
  71214. }
  71215. else {
  71216. // a non-run
  71217. count = a;
  71218. if ((count == 0) || (count > endIndex - index)) {
  71219. throw "HDR Bad Format, bad scanline data (non-run)";
  71220. }
  71221. scanLineArray[index++] = b;
  71222. if (--count > 0) {
  71223. for (var j = 0; j < count; j++) {
  71224. scanLineArray[index++] = uint8array[dataIndex++];
  71225. }
  71226. }
  71227. }
  71228. }
  71229. }
  71230. // now convert data from buffer into floats
  71231. for (i = 0; i < scanline_width; i++) {
  71232. a = scanLineArray[i];
  71233. b = scanLineArray[i + scanline_width];
  71234. c = scanLineArray[i + 2 * scanline_width];
  71235. d = scanLineArray[i + 3 * scanline_width];
  71236. this.Rgbe2float(resultArray, a, b, c, d, (hdrInfo.height - num_scanlines) * scanline_width * 3 + i * 3);
  71237. }
  71238. num_scanlines--;
  71239. }
  71240. return resultArray;
  71241. };
  71242. return HDRTools;
  71243. }());
  71244. BABYLON.HDRTools = HDRTools;
  71245. })(BABYLON || (BABYLON = {}));
  71246. //# sourceMappingURL=babylon.hdr.js.map
  71247. var BABYLON;
  71248. (function (BABYLON) {
  71249. /**
  71250. * This represents a texture coming from an HDR input.
  71251. *
  71252. * The only supported format is currently panorama picture stored in RGBE format.
  71253. * Example of such files can be found on HDRLib: http://hdrlib.com/
  71254. */
  71255. var HDRCubeTexture = /** @class */ (function (_super) {
  71256. __extends(HDRCubeTexture, _super);
  71257. /**
  71258. * Instantiates an HDRTexture from the following parameters.
  71259. *
  71260. * @param url The location of the HDR raw data (Panorama stored in RGBE format)
  71261. * @param scene The scene the texture will be used in
  71262. * @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.
  71263. * @param noMipmap Forces to not generate the mipmap if true
  71264. * @param generateHarmonics Specifies whether you want to extract the polynomial harmonics during the generation process
  71265. * @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)
  71266. * @param usePMREMGenerator Specifies whether or not to generate the CubeMap through CubeMapGen to avoid seams issue at run time.
  71267. */
  71268. function HDRCubeTexture(url, scene, size, noMipmap, generateHarmonics, useInGammaSpace, usePMREMGenerator, onLoad, onError) {
  71269. if (noMipmap === void 0) { noMipmap = false; }
  71270. if (generateHarmonics === void 0) { generateHarmonics = true; }
  71271. if (useInGammaSpace === void 0) { useInGammaSpace = false; }
  71272. if (usePMREMGenerator === void 0) { usePMREMGenerator = false; }
  71273. if (onLoad === void 0) { onLoad = null; }
  71274. if (onError === void 0) { onError = null; }
  71275. var _this = _super.call(this, scene) || this;
  71276. _this._useInGammaSpace = false;
  71277. _this._generateHarmonics = true;
  71278. _this._isBABYLONPreprocessed = false;
  71279. _this._onLoad = null;
  71280. _this._onError = null;
  71281. /**
  71282. * The texture coordinates mode. As this texture is stored in a cube format, please modify carefully.
  71283. */
  71284. _this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  71285. /**
  71286. * Specifies wether the texture has been generated through the PMREMGenerator tool.
  71287. * This is usefull at run time to apply the good shader.
  71288. */
  71289. _this.isPMREM = false;
  71290. _this._isBlocking = true;
  71291. if (!url) {
  71292. return _this;
  71293. }
  71294. _this.name = url;
  71295. _this.url = url;
  71296. _this.hasAlpha = false;
  71297. _this.isCube = true;
  71298. _this._textureMatrix = BABYLON.Matrix.Identity();
  71299. _this._onLoad = onLoad;
  71300. _this._onError = onError;
  71301. _this.gammaSpace = false;
  71302. var caps = scene.getEngine().getCaps();
  71303. if (size) {
  71304. _this._isBABYLONPreprocessed = false;
  71305. _this._noMipmap = noMipmap;
  71306. _this._size = size;
  71307. _this._useInGammaSpace = useInGammaSpace;
  71308. _this._usePMREMGenerator = usePMREMGenerator &&
  71309. caps.textureLOD &&
  71310. caps.textureFloat &&
  71311. !_this._useInGammaSpace;
  71312. }
  71313. else {
  71314. _this._isBABYLONPreprocessed = true;
  71315. _this._noMipmap = false;
  71316. _this._useInGammaSpace = false;
  71317. _this._usePMREMGenerator = caps.textureLOD && caps.textureFloat &&
  71318. !_this._useInGammaSpace;
  71319. }
  71320. _this.isPMREM = _this._usePMREMGenerator;
  71321. _this._texture = _this._getFromCache(url, _this._noMipmap);
  71322. if (!_this._texture) {
  71323. if (!scene.useDelayedTextureLoading) {
  71324. _this.loadTexture();
  71325. }
  71326. else {
  71327. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  71328. }
  71329. }
  71330. return _this;
  71331. }
  71332. Object.defineProperty(HDRCubeTexture.prototype, "isBlocking", {
  71333. /**
  71334. * Gets wether or not the texture is blocking during loading.
  71335. */
  71336. get: function () {
  71337. return this._isBlocking;
  71338. },
  71339. /**
  71340. * Sets wether or not the texture is blocking during loading.
  71341. */
  71342. set: function (value) {
  71343. this._isBlocking = value;
  71344. },
  71345. enumerable: true,
  71346. configurable: true
  71347. });
  71348. /**
  71349. * Occurs when the file is a preprocessed .babylon.hdr file.
  71350. */
  71351. HDRCubeTexture.prototype.loadBabylonTexture = function () {
  71352. var _this = this;
  71353. var mipLevels = 0;
  71354. var floatArrayView = null;
  71355. var scene = this.getScene();
  71356. var mipmapGenerator = (!this._useInGammaSpace && scene && scene.getEngine().getCaps().textureFloat) ? function (data) {
  71357. var mips = new Array();
  71358. if (!floatArrayView) {
  71359. return mips;
  71360. }
  71361. var startIndex = 30;
  71362. for (var level = 0; level < mipLevels; level++) {
  71363. mips.push([]);
  71364. // Fill each pixel of the mip level.
  71365. var faceSize = Math.pow(_this._size >> level, 2) * 3;
  71366. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  71367. var faceData = floatArrayView.subarray(startIndex, startIndex + faceSize);
  71368. mips[level].push(faceData);
  71369. startIndex += faceSize;
  71370. }
  71371. }
  71372. return mips;
  71373. } : null;
  71374. var callback = function (buffer) {
  71375. var scene = _this.getScene();
  71376. if (!scene) {
  71377. return null;
  71378. }
  71379. // Create Native Array Views
  71380. var intArrayView = new Int32Array(buffer);
  71381. floatArrayView = new Float32Array(buffer);
  71382. // Fill header.
  71383. var version = intArrayView[0]; // Version 1. (MAy be use in case of format changes for backward compaibility)
  71384. _this._size = intArrayView[1]; // CubeMap max mip face size.
  71385. // Update Texture Information.
  71386. if (!_this._texture) {
  71387. return null;
  71388. }
  71389. _this._texture.updateSize(_this._size, _this._size);
  71390. // Fill polynomial information.
  71391. var sphericalPolynomial = new BABYLON.SphericalPolynomial();
  71392. sphericalPolynomial.x.copyFromFloats(floatArrayView[2], floatArrayView[3], floatArrayView[4]);
  71393. sphericalPolynomial.y.copyFromFloats(floatArrayView[5], floatArrayView[6], floatArrayView[7]);
  71394. sphericalPolynomial.z.copyFromFloats(floatArrayView[8], floatArrayView[9], floatArrayView[10]);
  71395. sphericalPolynomial.xx.copyFromFloats(floatArrayView[11], floatArrayView[12], floatArrayView[13]);
  71396. sphericalPolynomial.yy.copyFromFloats(floatArrayView[14], floatArrayView[15], floatArrayView[16]);
  71397. sphericalPolynomial.zz.copyFromFloats(floatArrayView[17], floatArrayView[18], floatArrayView[19]);
  71398. sphericalPolynomial.xy.copyFromFloats(floatArrayView[20], floatArrayView[21], floatArrayView[22]);
  71399. sphericalPolynomial.yz.copyFromFloats(floatArrayView[23], floatArrayView[24], floatArrayView[25]);
  71400. sphericalPolynomial.zx.copyFromFloats(floatArrayView[26], floatArrayView[27], floatArrayView[28]);
  71401. _this.sphericalPolynomial = sphericalPolynomial;
  71402. // Fill pixel data.
  71403. mipLevels = intArrayView[29]; // Number of mip levels.
  71404. var startIndex = 30;
  71405. var data = [];
  71406. var faceSize = Math.pow(_this._size, 2) * 3;
  71407. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  71408. data.push(floatArrayView.subarray(startIndex, startIndex + faceSize));
  71409. startIndex += faceSize;
  71410. }
  71411. var results = [];
  71412. var byteArray = null;
  71413. // Push each faces.
  71414. for (var k = 0; k < 6; k++) {
  71415. var dataFace = null;
  71416. // To be deprecated.
  71417. if (version === 1) {
  71418. var j = ([0, 2, 4, 1, 3, 5])[k]; // Transforms +X+Y+Z... to +X-X+Y-Y...
  71419. dataFace = data[j];
  71420. }
  71421. // If special cases.
  71422. if (!mipmapGenerator && dataFace) {
  71423. if (!scene.getEngine().getCaps().textureFloat) {
  71424. // 3 channels of 1 bytes per pixel in bytes.
  71425. var byteBuffer = new ArrayBuffer(faceSize);
  71426. byteArray = new Uint8Array(byteBuffer);
  71427. }
  71428. for (var i = 0; i < _this._size * _this._size; i++) {
  71429. // Put in gamma space if requested.
  71430. if (_this._useInGammaSpace) {
  71431. dataFace[(i * 3) + 0] = Math.pow(dataFace[(i * 3) + 0], BABYLON.ToGammaSpace);
  71432. dataFace[(i * 3) + 1] = Math.pow(dataFace[(i * 3) + 1], BABYLON.ToGammaSpace);
  71433. dataFace[(i * 3) + 2] = Math.pow(dataFace[(i * 3) + 2], BABYLON.ToGammaSpace);
  71434. }
  71435. // Convert to int texture for fallback.
  71436. if (byteArray) {
  71437. var r = Math.max(dataFace[(i * 3) + 0] * 255, 0);
  71438. var g = Math.max(dataFace[(i * 3) + 1] * 255, 0);
  71439. var b = Math.max(dataFace[(i * 3) + 2] * 255, 0);
  71440. // May use luminance instead if the result is not accurate.
  71441. var max = Math.max(Math.max(r, g), b);
  71442. if (max > 255) {
  71443. var scale = 255 / max;
  71444. r *= scale;
  71445. g *= scale;
  71446. b *= scale;
  71447. }
  71448. byteArray[(i * 3) + 0] = r;
  71449. byteArray[(i * 3) + 1] = g;
  71450. byteArray[(i * 3) + 2] = b;
  71451. }
  71452. }
  71453. }
  71454. // Fill the array accordingly.
  71455. if (byteArray) {
  71456. results.push(byteArray);
  71457. }
  71458. else {
  71459. results.push(dataFace);
  71460. }
  71461. }
  71462. return results;
  71463. };
  71464. if (scene) {
  71465. 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);
  71466. }
  71467. };
  71468. /**
  71469. * Occurs when the file is raw .hdr file.
  71470. */
  71471. HDRCubeTexture.prototype.loadHDRTexture = function () {
  71472. var _this = this;
  71473. var callback = function (buffer) {
  71474. var scene = _this.getScene();
  71475. if (!scene) {
  71476. return null;
  71477. }
  71478. // Extract the raw linear data.
  71479. var data = BABYLON.HDRTools.GetCubeMapTextureData(buffer, _this._size);
  71480. // Generate harmonics if needed.
  71481. if (_this._generateHarmonics) {
  71482. var sphericalPolynomial = BABYLON.CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial(data);
  71483. _this.sphericalPolynomial = sphericalPolynomial;
  71484. }
  71485. var results = [];
  71486. var byteArray = null;
  71487. // Push each faces.
  71488. for (var j = 0; j < 6; j++) {
  71489. // Create uintarray fallback.
  71490. if (!scene.getEngine().getCaps().textureFloat) {
  71491. // 3 channels of 1 bytes per pixel in bytes.
  71492. var byteBuffer = new ArrayBuffer(_this._size * _this._size * 3);
  71493. byteArray = new Uint8Array(byteBuffer);
  71494. }
  71495. var dataFace = (data[HDRCubeTexture._facesMapping[j]]);
  71496. // If special cases.
  71497. if (_this._useInGammaSpace || byteArray) {
  71498. for (var i = 0; i < _this._size * _this._size; i++) {
  71499. // Put in gamma space if requested.
  71500. if (_this._useInGammaSpace) {
  71501. dataFace[(i * 3) + 0] = Math.pow(dataFace[(i * 3) + 0], BABYLON.ToGammaSpace);
  71502. dataFace[(i * 3) + 1] = Math.pow(dataFace[(i * 3) + 1], BABYLON.ToGammaSpace);
  71503. dataFace[(i * 3) + 2] = Math.pow(dataFace[(i * 3) + 2], BABYLON.ToGammaSpace);
  71504. }
  71505. // Convert to int texture for fallback.
  71506. if (byteArray) {
  71507. var r = Math.max(dataFace[(i * 3) + 0] * 255, 0);
  71508. var g = Math.max(dataFace[(i * 3) + 1] * 255, 0);
  71509. var b = Math.max(dataFace[(i * 3) + 2] * 255, 0);
  71510. // May use luminance instead if the result is not accurate.
  71511. var max = Math.max(Math.max(r, g), b);
  71512. if (max > 255) {
  71513. var scale = 255 / max;
  71514. r *= scale;
  71515. g *= scale;
  71516. b *= scale;
  71517. }
  71518. byteArray[(i * 3) + 0] = r;
  71519. byteArray[(i * 3) + 1] = g;
  71520. byteArray[(i * 3) + 2] = b;
  71521. }
  71522. }
  71523. }
  71524. if (byteArray) {
  71525. results.push(byteArray);
  71526. }
  71527. else {
  71528. results.push(dataFace);
  71529. }
  71530. }
  71531. return results;
  71532. };
  71533. var mipmapGenerator = null;
  71534. // TODO. Implement In code PMREM Generator following the LYS toolset generation.
  71535. // if (!this._noMipmap &&
  71536. // this._usePMREMGenerator) {
  71537. // mipmapGenerator = (data: ArrayBufferView[]) => {
  71538. // // Custom setup of the generator matching with the PBR shader values.
  71539. // var generator = new BABYLON.PMREMGenerator(data,
  71540. // this._size,
  71541. // this._size,
  71542. // 0,
  71543. // 3,
  71544. // this.getScene().getEngine().getCaps().textureFloat,
  71545. // 2048,
  71546. // 0.25,
  71547. // false,
  71548. // true);
  71549. // return generator.filterCubeMap();
  71550. // };
  71551. // }
  71552. var scene = this.getScene();
  71553. if (scene) {
  71554. 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);
  71555. }
  71556. };
  71557. /**
  71558. * Starts the loading process of the texture.
  71559. */
  71560. HDRCubeTexture.prototype.loadTexture = function () {
  71561. if (this._isBABYLONPreprocessed) {
  71562. this.loadBabylonTexture();
  71563. }
  71564. else {
  71565. this.loadHDRTexture();
  71566. }
  71567. };
  71568. HDRCubeTexture.prototype.clone = function () {
  71569. var scene = this.getScene();
  71570. if (!scene) {
  71571. return this;
  71572. }
  71573. var size = (this._isBABYLONPreprocessed ? null : this._size);
  71574. var newTexture = new HDRCubeTexture(this.url, scene, size, this._noMipmap, this._generateHarmonics, this._useInGammaSpace, this._usePMREMGenerator);
  71575. // Base texture
  71576. newTexture.level = this.level;
  71577. newTexture.wrapU = this.wrapU;
  71578. newTexture.wrapV = this.wrapV;
  71579. newTexture.coordinatesIndex = this.coordinatesIndex;
  71580. newTexture.coordinatesMode = this.coordinatesMode;
  71581. return newTexture;
  71582. };
  71583. // Methods
  71584. HDRCubeTexture.prototype.delayLoad = function () {
  71585. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  71586. return;
  71587. }
  71588. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  71589. this._texture = this._getFromCache(this.url, this._noMipmap);
  71590. if (!this._texture) {
  71591. this.loadTexture();
  71592. }
  71593. };
  71594. HDRCubeTexture.prototype.getReflectionTextureMatrix = function () {
  71595. return this._textureMatrix;
  71596. };
  71597. HDRCubeTexture.prototype.setReflectionTextureMatrix = function (value) {
  71598. this._textureMatrix = value;
  71599. };
  71600. HDRCubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  71601. var texture = null;
  71602. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  71603. var size = parsedTexture.isBABYLONPreprocessed ? null : parsedTexture.size;
  71604. texture = new HDRCubeTexture(rootUrl + parsedTexture.name, scene, size, parsedTexture.noMipmap, parsedTexture.generateHarmonics, parsedTexture.useInGammaSpace, parsedTexture.usePMREMGenerator);
  71605. texture.name = parsedTexture.name;
  71606. texture.hasAlpha = parsedTexture.hasAlpha;
  71607. texture.level = parsedTexture.level;
  71608. texture.coordinatesMode = parsedTexture.coordinatesMode;
  71609. texture.isBlocking = parsedTexture.isBlocking;
  71610. }
  71611. return texture;
  71612. };
  71613. HDRCubeTexture.prototype.serialize = function () {
  71614. if (!this.name) {
  71615. return null;
  71616. }
  71617. var serializationObject = {};
  71618. serializationObject.name = this.name;
  71619. serializationObject.hasAlpha = this.hasAlpha;
  71620. serializationObject.isCube = true;
  71621. serializationObject.level = this.level;
  71622. serializationObject.size = this._size;
  71623. serializationObject.coordinatesMode = this.coordinatesMode;
  71624. serializationObject.useInGammaSpace = this._useInGammaSpace;
  71625. serializationObject.generateHarmonics = this._generateHarmonics;
  71626. serializationObject.usePMREMGenerator = this._usePMREMGenerator;
  71627. serializationObject.isBABYLONPreprocessed = this._isBABYLONPreprocessed;
  71628. serializationObject.customType = "BABYLON.HDRCubeTexture";
  71629. serializationObject.noMipmap = this._noMipmap;
  71630. serializationObject.isBlocking = this._isBlocking;
  71631. return serializationObject;
  71632. };
  71633. /**
  71634. * Saves as a file the data contained in the texture in a binary format.
  71635. * This can be used to prevent the long loading tie associated with creating the seamless texture as well
  71636. * as the spherical used in the lighting.
  71637. * @param url The HDR file url.
  71638. * @param size The size of the texture data to generate (one of the cubemap face desired width).
  71639. * @param onError Method called if any error happens during download.
  71640. * @return The packed binary data.
  71641. */
  71642. HDRCubeTexture.generateBabylonHDROnDisk = function (url, size, onError) {
  71643. if (onError === void 0) { onError = null; }
  71644. var callback = function (buffer) {
  71645. var data = new Blob([buffer], { type: 'application/octet-stream' });
  71646. // Returns a URL you can use as a href.
  71647. var objUrl = window.URL.createObjectURL(data);
  71648. // Simulates a link to it and click to dowload.
  71649. var a = document.createElement("a");
  71650. document.body.appendChild(a);
  71651. a.style.display = "none";
  71652. a.href = objUrl;
  71653. a.download = "envmap.babylon.hdr";
  71654. a.click();
  71655. };
  71656. HDRCubeTexture.generateBabylonHDR(url, size, callback, onError);
  71657. };
  71658. /**
  71659. * Serializes the data contained in the texture in a binary format.
  71660. * This can be used to prevent the long loading tie associated with creating the seamless texture as well
  71661. * as the spherical used in the lighting.
  71662. * @param url The HDR file url.
  71663. * @param size The size of the texture data to generate (one of the cubemap face desired width).
  71664. * @param onError Method called if any error happens during download.
  71665. * @return The packed binary data.
  71666. */
  71667. HDRCubeTexture.generateBabylonHDR = function (url, size, callback, onError) {
  71668. if (onError === void 0) { onError = null; }
  71669. // Needs the url tho create the texture.
  71670. if (!url) {
  71671. return;
  71672. }
  71673. // Check Power of two size.
  71674. if (!BABYLON.Tools.IsExponentOfTwo(size)) {
  71675. return;
  71676. }
  71677. // Coming Back in 3.x.
  71678. BABYLON.Tools.Error("Generation of Babylon HDR is coming back in 3.2.");
  71679. };
  71680. HDRCubeTexture._facesMapping = [
  71681. "right",
  71682. "left",
  71683. "up",
  71684. "down",
  71685. "front",
  71686. "back"
  71687. ];
  71688. return HDRCubeTexture;
  71689. }(BABYLON.BaseTexture));
  71690. BABYLON.HDRCubeTexture = HDRCubeTexture;
  71691. })(BABYLON || (BABYLON = {}));
  71692. //# sourceMappingURL=babylon.hdrCubeTexture.js.map
  71693. // All the credit goes to this project and the guy who's behind it https://github.com/mapbox/earcut
  71694. // Huge respect for a such great lib.
  71695. // Earcut license:
  71696. // Copyright (c) 2016, Mapbox
  71697. //
  71698. // Permission to use, copy, modify, and/or distribute this software for any purpose
  71699. // with or without fee is hereby granted, provided that the above copyright notice
  71700. // and this permission notice appear in all copies.
  71701. //
  71702. // THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
  71703. // REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND
  71704. // FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
  71705. // INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS
  71706. // OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER
  71707. // TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF
  71708. // THIS SOFTWARE.
  71709. var Earcut;
  71710. (function (Earcut) {
  71711. /**
  71712. * The fastest and smallest JavaScript polygon triangulation library for your WebGL apps
  71713. * @param data is a flat array of vertice coordinates like [x0, y0, x1, y1, x2, y2, ...].
  71714. * @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).
  71715. * @param dim is the number of coordinates per vertice in the input array (2 by default).
  71716. */
  71717. function earcut(data, holeIndices, dim) {
  71718. dim = dim || 2;
  71719. var hasHoles = holeIndices && holeIndices.length, outerLen = hasHoles ? holeIndices[0] * dim : data.length, outerNode = linkedList(data, 0, outerLen, dim, true), triangles = new Array();
  71720. if (!outerNode)
  71721. return triangles;
  71722. var minX = 0, minY = 0, maxX, maxY, x, y, size = 0;
  71723. if (hasHoles)
  71724. outerNode = eliminateHoles(data, holeIndices, outerNode, dim);
  71725. // if the shape is not too simple, we'll use z-order curve hash later; calculate polygon bbox
  71726. if (data.length > 80 * dim) {
  71727. minX = maxX = data[0];
  71728. minY = maxY = data[1];
  71729. for (var i = dim; i < outerLen; i += dim) {
  71730. x = data[i];
  71731. y = data[i + 1];
  71732. if (x < minX)
  71733. minX = x;
  71734. if (y < minY)
  71735. minY = y;
  71736. if (x > maxX)
  71737. maxX = x;
  71738. if (y > maxY)
  71739. maxY = y;
  71740. }
  71741. // minX, minY and size are later used to transform coords into integers for z-order calculation
  71742. size = Math.max(maxX - minX, maxY - minY);
  71743. }
  71744. earcutLinked(outerNode, triangles, dim, minX, minY, size, 0);
  71745. return triangles;
  71746. }
  71747. Earcut.earcut = earcut;
  71748. var Node = /** @class */ (function () {
  71749. function Node(i, x, y) {
  71750. this.i = i;
  71751. this.x = x;
  71752. this.y = y;
  71753. this.prev = null;
  71754. this.next = null;
  71755. this.z = null;
  71756. this.prevZ = null;
  71757. this.nextZ = null;
  71758. this.steiner = false;
  71759. }
  71760. return Node;
  71761. }());
  71762. // create a circular doubly linked list from polygon points in the specified winding order
  71763. function linkedList(data, start, end, dim, clockwise) {
  71764. var i, last = null;
  71765. if (clockwise === (signedArea(data, start, end, dim) > 0)) {
  71766. for (i = start; i < end; i += dim)
  71767. last = insertNode(i, data[i], data[i + 1], last);
  71768. }
  71769. else {
  71770. for (i = end - dim; i >= start; i -= dim)
  71771. last = insertNode(i, data[i], data[i + 1], last);
  71772. }
  71773. if (last && equals(last, last.next)) {
  71774. removeNode(last);
  71775. last = last.next;
  71776. }
  71777. return last;
  71778. }
  71779. // eliminate colinear or duplicate points
  71780. function filterPoints(start, end) {
  71781. if (!start)
  71782. return start;
  71783. if (!end)
  71784. end = start;
  71785. var p = start, again;
  71786. do {
  71787. again = false;
  71788. if (!p.steiner && (equals(p, p.next) || area(p.prev, p, p.next) === 0)) {
  71789. removeNode(p);
  71790. p = end = p.prev;
  71791. if (p === p.next)
  71792. return undefined;
  71793. again = true;
  71794. }
  71795. else {
  71796. p = p.next;
  71797. }
  71798. } while (again || p !== end);
  71799. return end;
  71800. }
  71801. // main ear slicing loop which triangulates a polygon (given as a linked list)
  71802. function earcutLinked(ear, triangles, dim, minX, minY, size, pass) {
  71803. if (!ear)
  71804. return;
  71805. // interlink polygon nodes in z-order
  71806. if (!pass && size)
  71807. indexCurve(ear, minX, minY, size);
  71808. var stop = ear, prev, next;
  71809. // iterate through ears, slicing them one by one
  71810. while (ear.prev !== ear.next) {
  71811. prev = ear.prev;
  71812. next = ear.next;
  71813. if (size ? isEarHashed(ear, minX, minY, size) : isEar(ear)) {
  71814. // cut off the triangle
  71815. triangles.push(prev.i / dim);
  71816. triangles.push(ear.i / dim);
  71817. triangles.push(next.i / dim);
  71818. removeNode(ear);
  71819. // skipping the next vertice leads to less sliver triangles
  71820. ear = next.next;
  71821. stop = next.next;
  71822. continue;
  71823. }
  71824. ear = next;
  71825. // if we looped through the whole remaining polygon and can't find any more ears
  71826. if (ear === stop) {
  71827. // try filtering points and slicing again
  71828. if (!pass) {
  71829. earcutLinked(filterPoints(ear, undefined), triangles, dim, minX, minY, size, 1);
  71830. // if this didn't work, try curing all small self-intersections locally
  71831. }
  71832. else if (pass === 1) {
  71833. ear = cureLocalIntersections(ear, triangles, dim);
  71834. earcutLinked(ear, triangles, dim, minX, minY, size, 2);
  71835. // as a last resort, try splitting the remaining polygon into two
  71836. }
  71837. else if (pass === 2) {
  71838. splitEarcut(ear, triangles, dim, minX, minY, size);
  71839. }
  71840. break;
  71841. }
  71842. }
  71843. }
  71844. // check whether a polygon node forms a valid ear with adjacent nodes
  71845. function isEar(ear) {
  71846. var a = ear.prev, b = ear, c = ear.next;
  71847. if (area(a, b, c) >= 0)
  71848. return false; // reflex, can't be an ear
  71849. // now make sure we don't have other points inside the potential ear
  71850. var p = ear.next.next;
  71851. while (p !== ear.prev) {
  71852. if (pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) &&
  71853. area(p.prev, p, p.next) >= 0)
  71854. return false;
  71855. p = p.next;
  71856. }
  71857. return true;
  71858. }
  71859. function isEarHashed(ear, minX, minY, size) {
  71860. var a = ear.prev, b = ear, c = ear.next;
  71861. if (area(a, b, c) >= 0)
  71862. return false; // reflex, can't be an ear
  71863. // triangle bbox; min & max are calculated like this for speed
  71864. 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);
  71865. // z-order range for the current triangle bbox;
  71866. var minZ = zOrder(minTX, minTY, minX, minY, size), maxZ = zOrder(maxTX, maxTY, minX, minY, size);
  71867. // first look for points inside the triangle in increasing z-order
  71868. var p = ear.nextZ;
  71869. while (p && p.z <= maxZ) {
  71870. if (p !== ear.prev &&
  71871. p !== ear.next &&
  71872. pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) &&
  71873. area(p.prev, p, p.next) >= 0)
  71874. return false;
  71875. p = p.nextZ;
  71876. }
  71877. // then look for points in decreasing z-order
  71878. p = ear.prevZ;
  71879. while (p && p.z >= minZ) {
  71880. if (p !== ear.prev &&
  71881. p !== ear.next &&
  71882. pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) &&
  71883. area(p.prev, p, p.next) >= 0)
  71884. return false;
  71885. p = p.prevZ;
  71886. }
  71887. return true;
  71888. }
  71889. // go through all polygon nodes and cure small local self-intersections
  71890. function cureLocalIntersections(start, triangles, dim) {
  71891. var p = start;
  71892. do {
  71893. var a = p.prev, b = p.next.next;
  71894. if (!equals(a, b) && intersects(a, p, p.next, b) && locallyInside(a, b) && locallyInside(b, a)) {
  71895. triangles.push(a.i / dim);
  71896. triangles.push(p.i / dim);
  71897. triangles.push(b.i / dim);
  71898. // remove two nodes involved
  71899. removeNode(p);
  71900. removeNode(p.next);
  71901. p = start = b;
  71902. }
  71903. p = p.next;
  71904. } while (p !== start);
  71905. return p;
  71906. }
  71907. // try splitting polygon into two and triangulate them independently
  71908. function splitEarcut(start, triangles, dim, minX, minY, size) {
  71909. // look for a valid diagonal that divides the polygon into two
  71910. var a = start;
  71911. do {
  71912. var b = a.next.next;
  71913. while (b !== a.prev) {
  71914. if (a.i !== b.i && isValidDiagonal(a, b)) {
  71915. // split the polygon in two by the diagonal
  71916. var c = splitPolygon(a, b);
  71917. // filter colinear points around the cuts
  71918. a = filterPoints(a, a.next);
  71919. c = filterPoints(c, c.next);
  71920. // run earcut on each half
  71921. earcutLinked(a, triangles, dim, minX, minY, size, undefined);
  71922. earcutLinked(c, triangles, dim, minX, minY, size, undefined);
  71923. return;
  71924. }
  71925. b = b.next;
  71926. }
  71927. a = a.next;
  71928. } while (a !== start);
  71929. }
  71930. // link every hole into the outer loop, producing a single-ring polygon without holes
  71931. function eliminateHoles(data, holeIndices, outerNode, dim) {
  71932. var queue = [], i, len, start, end, list;
  71933. for (i = 0, len = holeIndices.length; i < len; i++) {
  71934. start = holeIndices[i] * dim;
  71935. end = i < len - 1 ? holeIndices[i + 1] * dim : data.length;
  71936. list = linkedList(data, start, end, dim, false);
  71937. if (list === list.next)
  71938. list.steiner = true;
  71939. queue.push(getLeftmost(list));
  71940. }
  71941. queue.sort(compareX);
  71942. // process holes from left to right
  71943. for (i = 0; i < queue.length; i++) {
  71944. eliminateHole(queue[i], outerNode);
  71945. outerNode = filterPoints(outerNode, outerNode.next);
  71946. }
  71947. return outerNode;
  71948. }
  71949. function compareX(a, b) {
  71950. return a.x - b.x;
  71951. }
  71952. // find a bridge between vertices that connects hole with an outer ring and and link it
  71953. function eliminateHole(hole, outerNode) {
  71954. outerNode = findHoleBridge(hole, outerNode);
  71955. if (outerNode) {
  71956. var b = splitPolygon(outerNode, hole);
  71957. filterPoints(b, b.next);
  71958. }
  71959. }
  71960. // David Eberly's algorithm for finding a bridge between hole and outer polygon
  71961. function findHoleBridge(hole, outerNode) {
  71962. var p = outerNode, hx = hole.x, hy = hole.y, qx = -Infinity, m;
  71963. // find a segment intersected by a ray from the hole's leftmost point to the left;
  71964. // segment's endpoint with lesser x will be potential connection point
  71965. do {
  71966. if (hy <= p.y && hy >= p.next.y) {
  71967. var x = p.x + (hy - p.y) * (p.next.x - p.x) / (p.next.y - p.y);
  71968. if (x <= hx && x > qx) {
  71969. qx = x;
  71970. if (x === hx) {
  71971. if (hy === p.y)
  71972. return p;
  71973. if (hy === p.next.y)
  71974. return p.next;
  71975. }
  71976. m = p.x < p.next.x ? p : p.next;
  71977. }
  71978. }
  71979. p = p.next;
  71980. } while (p !== outerNode);
  71981. if (!m)
  71982. return null;
  71983. if (hx === qx)
  71984. return m.prev; // hole touches outer segment; pick lower endpoint
  71985. // look for points inside the triangle of hole point, segment intersection and endpoint;
  71986. // if there are no points found, we have a valid connection;
  71987. // otherwise choose the point of the minimum angle with the ray as connection point
  71988. var stop = m, mx = m.x, my = m.y, tanMin = Infinity, tan;
  71989. p = m.next;
  71990. while (p !== stop) {
  71991. if (hx >= p.x &&
  71992. p.x >= mx &&
  71993. pointInTriangle(hy < my ? hx : qx, hy, mx, my, hy < my ? qx : hx, hy, p.x, p.y)) {
  71994. tan = Math.abs(hy - p.y) / (hx - p.x); // tangential
  71995. if ((tan < tanMin || (tan === tanMin && p.x > m.x)) && locallyInside(p, hole)) {
  71996. m = p;
  71997. tanMin = tan;
  71998. }
  71999. }
  72000. p = p.next;
  72001. }
  72002. return m;
  72003. }
  72004. // interlink polygon nodes in z-order
  72005. function indexCurve(start, minX, minY, size) {
  72006. var p = start;
  72007. do {
  72008. if (p.z === null)
  72009. p.z = zOrder(p.x, p.y, minX, minY, size);
  72010. p.prevZ = p.prev;
  72011. p.nextZ = p.next;
  72012. p = p.next;
  72013. } while (p !== start);
  72014. p.prevZ.nextZ = null;
  72015. p.prevZ = null;
  72016. sortLinked(p);
  72017. }
  72018. // Simon Tatham's linked list merge sort algorithm
  72019. // http://www.chiark.greenend.org.uk/~sgtatham/algorithms/listsort.html
  72020. function sortLinked(list) {
  72021. var i, p, q, e, tail, numMerges, pSize, qSize, inSize = 1;
  72022. do {
  72023. p = list;
  72024. list = null;
  72025. tail = null;
  72026. numMerges = 0;
  72027. while (p) {
  72028. numMerges++;
  72029. q = p;
  72030. pSize = 0;
  72031. for (i = 0; i < inSize; i++) {
  72032. pSize++;
  72033. q = q.nextZ;
  72034. if (!q)
  72035. break;
  72036. }
  72037. qSize = inSize;
  72038. while (pSize > 0 || (qSize > 0 && q)) {
  72039. if (pSize === 0) {
  72040. e = q;
  72041. q = q.nextZ;
  72042. qSize--;
  72043. }
  72044. else if (qSize === 0 || !q) {
  72045. e = p;
  72046. p = p.nextZ;
  72047. pSize--;
  72048. }
  72049. else if (p.z <= q.z) {
  72050. e = p;
  72051. p = p.nextZ;
  72052. pSize--;
  72053. }
  72054. else {
  72055. e = q;
  72056. q = q.nextZ;
  72057. qSize--;
  72058. }
  72059. if (tail)
  72060. tail.nextZ = e;
  72061. else
  72062. list = e;
  72063. e.prevZ = tail;
  72064. tail = e;
  72065. }
  72066. p = q;
  72067. }
  72068. tail.nextZ = null;
  72069. inSize *= 2;
  72070. } while (numMerges > 1);
  72071. return list;
  72072. }
  72073. // z-order of a point given coords and size of the data bounding box
  72074. function zOrder(x, y, minX, minY, size) {
  72075. // coords are transformed into non-negative 15-bit integer range
  72076. x = 32767 * (x - minX) / size;
  72077. y = 32767 * (y - minY) / size;
  72078. x = (x | (x << 8)) & 0x00FF00FF;
  72079. x = (x | (x << 4)) & 0x0F0F0F0F;
  72080. x = (x | (x << 2)) & 0x33333333;
  72081. x = (x | (x << 1)) & 0x55555555;
  72082. y = (y | (y << 8)) & 0x00FF00FF;
  72083. y = (y | (y << 4)) & 0x0F0F0F0F;
  72084. y = (y | (y << 2)) & 0x33333333;
  72085. y = (y | (y << 1)) & 0x55555555;
  72086. return x | (y << 1);
  72087. }
  72088. // find the leftmost node of a polygon ring
  72089. function getLeftmost(start) {
  72090. var p = start, leftmost = start;
  72091. do {
  72092. if (p.x < leftmost.x)
  72093. leftmost = p;
  72094. p = p.next;
  72095. } while (p !== start);
  72096. return leftmost;
  72097. }
  72098. // check if a point lies within a convex triangle
  72099. function pointInTriangle(ax, ay, bx, by, cx, cy, px, py) {
  72100. return (cx - px) * (ay - py) - (ax - px) * (cy - py) >= 0 &&
  72101. (ax - px) * (by - py) - (bx - px) * (ay - py) >= 0 &&
  72102. (bx - px) * (cy - py) - (cx - px) * (by - py) >= 0;
  72103. }
  72104. // check if a diagonal between two polygon nodes is valid (lies in polygon interior)
  72105. function isValidDiagonal(a, b) {
  72106. return a.next.i !== b.i &&
  72107. a.prev.i !== b.i &&
  72108. !intersectsPolygon(a, b) &&
  72109. locallyInside(a, b) &&
  72110. locallyInside(b, a) &&
  72111. middleInside(a, b);
  72112. }
  72113. // signed area of a triangle
  72114. function area(p, q, r) {
  72115. return (q.y - p.y) * (r.x - q.x) - (q.x - p.x) * (r.y - q.y);
  72116. }
  72117. // check if two points are equal
  72118. function equals(p1, p2) {
  72119. return p1.x === p2.x && p1.y === p2.y;
  72120. }
  72121. // check if two segments intersect
  72122. function intersects(p1, q1, p2, q2) {
  72123. if ((equals(p1, q1) && equals(p2, q2)) ||
  72124. (equals(p1, q2) && equals(p2, q1)))
  72125. return true;
  72126. return area(p1, q1, p2) > 0 !== area(p1, q1, q2) > 0 &&
  72127. area(p2, q2, p1) > 0 !== area(p2, q2, q1) > 0;
  72128. }
  72129. // check if a polygon diagonal intersects any polygon segments
  72130. function intersectsPolygon(a, b) {
  72131. var p = a;
  72132. do {
  72133. if (p.i !== a.i &&
  72134. p.next.i !== a.i &&
  72135. p.i !== b.i &&
  72136. p.next.i !== b.i &&
  72137. intersects(p, p.next, a, b))
  72138. return true;
  72139. p = p.next;
  72140. } while (p !== a);
  72141. return false;
  72142. }
  72143. // check if a polygon diagonal is locally inside the polygon
  72144. function locallyInside(a, b) {
  72145. return area(a.prev, a, a.next) < 0
  72146. ? area(a, b, a.next) >= 0 && area(a, a.prev, b) >= 0
  72147. : area(a, b, a.prev) < 0 || area(a, a.next, b) < 0;
  72148. }
  72149. // check if the middle point of a polygon diagonal is inside the polygon
  72150. function middleInside(a, b) {
  72151. var p = a, inside = false, px = (a.x + b.x) / 2, py = (a.y + b.y) / 2;
  72152. do {
  72153. if (((p.y > py) !== (p.next.y > py)) && (px < (p.next.x - p.x) * (py - p.y) / (p.next.y - p.y) + p.x))
  72154. inside = !inside;
  72155. p = p.next;
  72156. } while (p !== a);
  72157. return inside;
  72158. }
  72159. // link two polygon vertices with a bridge; if the vertices belong to the same ring, it splits polygon into two;
  72160. // if one belongs to the outer ring and another to a hole, it merges it into a single ring
  72161. function splitPolygon(a, b) {
  72162. 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;
  72163. a.next = b;
  72164. b.prev = a;
  72165. a2.next = an;
  72166. an.prev = a2;
  72167. b2.next = a2;
  72168. a2.prev = b2;
  72169. bp.next = b2;
  72170. b2.prev = bp;
  72171. return b2;
  72172. }
  72173. // create a node and optionally link it with previous one (in a circular doubly linked list)
  72174. function insertNode(i, x, y, last) {
  72175. var p = new Node(i, x, y);
  72176. if (!last) {
  72177. p.prev = p;
  72178. p.next = p;
  72179. }
  72180. else {
  72181. p.next = last.next;
  72182. p.prev = last;
  72183. last.next.prev = p;
  72184. last.next = p;
  72185. }
  72186. return p;
  72187. }
  72188. function removeNode(p) {
  72189. p.next.prev = p.prev;
  72190. p.prev.next = p.next;
  72191. if (p.prevZ)
  72192. p.prevZ.nextZ = p.nextZ;
  72193. if (p.nextZ)
  72194. p.nextZ.prevZ = p.prevZ;
  72195. }
  72196. /**
  72197. * return a percentage difference between the polygon area and its triangulation area;
  72198. * used to verify correctness of triangulation
  72199. */
  72200. function deviation(data, holeIndices, dim, triangles) {
  72201. var hasHoles = holeIndices && holeIndices.length;
  72202. var outerLen = hasHoles ? holeIndices[0] * dim : data.length;
  72203. var polygonArea = Math.abs(signedArea(data, 0, outerLen, dim));
  72204. if (hasHoles) {
  72205. for (var i = 0, len = holeIndices.length; i < len; i++) {
  72206. var start = holeIndices[i] * dim;
  72207. var end = i < len - 1 ? holeIndices[i + 1] * dim : data.length;
  72208. polygonArea -= Math.abs(signedArea(data, start, end, dim));
  72209. }
  72210. }
  72211. var trianglesArea = 0;
  72212. for (i = 0; i < triangles.length; i += 3) {
  72213. var a = triangles[i] * dim;
  72214. var b = triangles[i + 1] * dim;
  72215. var c = triangles[i + 2] * dim;
  72216. trianglesArea += Math.abs((data[a] - data[c]) * (data[b + 1] - data[a + 1]) -
  72217. (data[a] - data[b]) * (data[c + 1] - data[a + 1]));
  72218. }
  72219. return polygonArea === 0 && trianglesArea === 0 ? 0 : Math.abs((trianglesArea - polygonArea) / polygonArea);
  72220. }
  72221. Earcut.deviation = deviation;
  72222. ;
  72223. function signedArea(data, start, end, dim) {
  72224. var sum = 0;
  72225. for (var i = start, j = end - dim; i < end; i += dim) {
  72226. sum += (data[j] - data[i]) * (data[i + 1] + data[j + 1]);
  72227. j = i;
  72228. }
  72229. return sum;
  72230. }
  72231. /**
  72232. * turn a polygon in a multi-dimensional array form (e.g. as in GeoJSON) into a form Earcut accepts
  72233. */
  72234. function flatten(data) {
  72235. var dim = data[0][0].length, result = { vertices: new Array(), holes: new Array(), dimensions: dim }, holeIndex = 0;
  72236. for (var i = 0; i < data.length; i++) {
  72237. for (var j = 0; j < data[i].length; j++) {
  72238. for (var d = 0; d < dim; d++)
  72239. result.vertices.push(data[i][j][d]);
  72240. }
  72241. if (i > 0) {
  72242. holeIndex += data[i - 1].length;
  72243. result.holes.push(holeIndex);
  72244. }
  72245. }
  72246. return result;
  72247. }
  72248. Earcut.flatten = flatten;
  72249. ;
  72250. })(Earcut || (Earcut = {}));
  72251. //# sourceMappingURL=babylon.earcut.js.map
  72252. var BABYLON;
  72253. (function (BABYLON) {
  72254. var IndexedVector2 = /** @class */ (function (_super) {
  72255. __extends(IndexedVector2, _super);
  72256. function IndexedVector2(original, index) {
  72257. var _this = _super.call(this, original.x, original.y) || this;
  72258. _this.index = index;
  72259. return _this;
  72260. }
  72261. return IndexedVector2;
  72262. }(BABYLON.Vector2));
  72263. var PolygonPoints = /** @class */ (function () {
  72264. function PolygonPoints() {
  72265. this.elements = new Array();
  72266. }
  72267. PolygonPoints.prototype.add = function (originalPoints) {
  72268. var _this = this;
  72269. var result = new Array();
  72270. originalPoints.forEach(function (point) {
  72271. if (result.length === 0 || !point.equalsWithEpsilon(result[0])) {
  72272. var newPoint = new IndexedVector2(point, _this.elements.length);
  72273. result.push(newPoint);
  72274. _this.elements.push(newPoint);
  72275. }
  72276. });
  72277. return result;
  72278. };
  72279. PolygonPoints.prototype.computeBounds = function () {
  72280. var lmin = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  72281. var lmax = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  72282. this.elements.forEach(function (point) {
  72283. // x
  72284. if (point.x < lmin.x) {
  72285. lmin.x = point.x;
  72286. }
  72287. else if (point.x > lmax.x) {
  72288. lmax.x = point.x;
  72289. }
  72290. // y
  72291. if (point.y < lmin.y) {
  72292. lmin.y = point.y;
  72293. }
  72294. else if (point.y > lmax.y) {
  72295. lmax.y = point.y;
  72296. }
  72297. });
  72298. return {
  72299. min: lmin,
  72300. max: lmax,
  72301. width: lmax.x - lmin.x,
  72302. height: lmax.y - lmin.y
  72303. };
  72304. };
  72305. return PolygonPoints;
  72306. }());
  72307. var Polygon = /** @class */ (function () {
  72308. function Polygon() {
  72309. }
  72310. Polygon.Rectangle = function (xmin, ymin, xmax, ymax) {
  72311. return [
  72312. new BABYLON.Vector2(xmin, ymin),
  72313. new BABYLON.Vector2(xmax, ymin),
  72314. new BABYLON.Vector2(xmax, ymax),
  72315. new BABYLON.Vector2(xmin, ymax)
  72316. ];
  72317. };
  72318. Polygon.Circle = function (radius, cx, cy, numberOfSides) {
  72319. if (cx === void 0) { cx = 0; }
  72320. if (cy === void 0) { cy = 0; }
  72321. if (numberOfSides === void 0) { numberOfSides = 32; }
  72322. var result = new Array();
  72323. var angle = 0;
  72324. var increment = (Math.PI * 2) / numberOfSides;
  72325. for (var i = 0; i < numberOfSides; i++) {
  72326. result.push(new BABYLON.Vector2(cx + Math.cos(angle) * radius, cy + Math.sin(angle) * radius));
  72327. angle -= increment;
  72328. }
  72329. return result;
  72330. };
  72331. Polygon.Parse = function (input) {
  72332. var floats = input.split(/[^-+eE\.\d]+/).map(parseFloat).filter(function (val) { return (!isNaN(val)); });
  72333. var i, result = [];
  72334. for (i = 0; i < (floats.length & 0x7FFFFFFE); i += 2) {
  72335. result.push(new BABYLON.Vector2(floats[i], floats[i + 1]));
  72336. }
  72337. return result;
  72338. };
  72339. Polygon.StartingAt = function (x, y) {
  72340. return BABYLON.Path2.StartingAt(x, y);
  72341. };
  72342. return Polygon;
  72343. }());
  72344. BABYLON.Polygon = Polygon;
  72345. var PolygonMeshBuilder = /** @class */ (function () {
  72346. function PolygonMeshBuilder(name, contours, scene) {
  72347. this._points = new PolygonPoints();
  72348. this._outlinepoints = new PolygonPoints();
  72349. this._holes = new Array();
  72350. this._epoints = new Array();
  72351. this._eholes = new Array();
  72352. this._name = name;
  72353. this._scene = scene;
  72354. var points;
  72355. if (contours instanceof BABYLON.Path2) {
  72356. points = contours.getPoints();
  72357. }
  72358. else {
  72359. points = contours;
  72360. }
  72361. this._addToepoint(points);
  72362. this._points.add(points);
  72363. this._outlinepoints.add(points);
  72364. }
  72365. PolygonMeshBuilder.prototype._addToepoint = function (points) {
  72366. for (var _i = 0, points_1 = points; _i < points_1.length; _i++) {
  72367. var p = points_1[_i];
  72368. this._epoints.push(p.x, p.y);
  72369. }
  72370. };
  72371. PolygonMeshBuilder.prototype.addHole = function (hole) {
  72372. this._points.add(hole);
  72373. var holepoints = new PolygonPoints();
  72374. holepoints.add(hole);
  72375. this._holes.push(holepoints);
  72376. this._eholes.push(this._epoints.length / 2);
  72377. this._addToepoint(hole);
  72378. return this;
  72379. };
  72380. PolygonMeshBuilder.prototype.build = function (updatable, depth) {
  72381. var _this = this;
  72382. if (updatable === void 0) { updatable = false; }
  72383. if (depth === void 0) { depth = 0; }
  72384. var result = new BABYLON.Mesh(this._name, this._scene);
  72385. var normals = new Array();
  72386. var positions = new Array();
  72387. var uvs = new Array();
  72388. var bounds = this._points.computeBounds();
  72389. this._points.elements.forEach(function (p) {
  72390. normals.push(0, 1.0, 0);
  72391. positions.push(p.x, 0, p.y);
  72392. uvs.push((p.x - bounds.min.x) / bounds.width, (p.y - bounds.min.y) / bounds.height);
  72393. });
  72394. var indices = new Array();
  72395. var res = Earcut.earcut(this._epoints, this._eholes, 2);
  72396. for (var i = 0; i < res.length; i++) {
  72397. indices.push(res[i]);
  72398. }
  72399. if (depth > 0) {
  72400. var positionscount = (positions.length / 3); //get the current pointcount
  72401. this._points.elements.forEach(function (p) {
  72402. normals.push(0, -1.0, 0);
  72403. positions.push(p.x, -depth, p.y);
  72404. uvs.push(1 - (p.x - bounds.min.x) / bounds.width, 1 - (p.y - bounds.min.y) / bounds.height);
  72405. });
  72406. var totalCount = indices.length;
  72407. for (var i = 0; i < totalCount; i += 3) {
  72408. var i0 = indices[i + 0];
  72409. var i1 = indices[i + 1];
  72410. var i2 = indices[i + 2];
  72411. indices.push(i2 + positionscount);
  72412. indices.push(i1 + positionscount);
  72413. indices.push(i0 + positionscount);
  72414. }
  72415. //Add the sides
  72416. this.addSide(positions, normals, uvs, indices, bounds, this._outlinepoints, depth, false);
  72417. this._holes.forEach(function (hole) {
  72418. _this.addSide(positions, normals, uvs, indices, bounds, hole, depth, true);
  72419. });
  72420. }
  72421. result.setVerticesData(BABYLON.VertexBuffer.PositionKind, positions, updatable);
  72422. result.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  72423. result.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs, updatable);
  72424. result.setIndices(indices);
  72425. return result;
  72426. };
  72427. PolygonMeshBuilder.prototype.addSide = function (positions, normals, uvs, indices, bounds, points, depth, flip) {
  72428. var StartIndex = positions.length / 3;
  72429. var ulength = 0;
  72430. for (var i = 0; i < points.elements.length; i++) {
  72431. var p = points.elements[i];
  72432. var p1;
  72433. if ((i + 1) > points.elements.length - 1) {
  72434. p1 = points.elements[0];
  72435. }
  72436. else {
  72437. p1 = points.elements[i + 1];
  72438. }
  72439. positions.push(p.x, 0, p.y);
  72440. positions.push(p.x, -depth, p.y);
  72441. positions.push(p1.x, 0, p1.y);
  72442. positions.push(p1.x, -depth, p1.y);
  72443. var v1 = new BABYLON.Vector3(p.x, 0, p.y);
  72444. var v2 = new BABYLON.Vector3(p1.x, 0, p1.y);
  72445. var v3 = v2.subtract(v1);
  72446. var v4 = new BABYLON.Vector3(0, 1, 0);
  72447. var vn = BABYLON.Vector3.Cross(v3, v4);
  72448. vn = vn.normalize();
  72449. uvs.push(ulength / bounds.width, 0);
  72450. uvs.push(ulength / bounds.width, 1);
  72451. ulength += v3.length();
  72452. uvs.push((ulength / bounds.width), 0);
  72453. uvs.push((ulength / bounds.width), 1);
  72454. if (!flip) {
  72455. normals.push(-vn.x, -vn.y, -vn.z);
  72456. normals.push(-vn.x, -vn.y, -vn.z);
  72457. normals.push(-vn.x, -vn.y, -vn.z);
  72458. normals.push(-vn.x, -vn.y, -vn.z);
  72459. indices.push(StartIndex);
  72460. indices.push(StartIndex + 1);
  72461. indices.push(StartIndex + 2);
  72462. indices.push(StartIndex + 1);
  72463. indices.push(StartIndex + 3);
  72464. indices.push(StartIndex + 2);
  72465. }
  72466. else {
  72467. normals.push(vn.x, vn.y, vn.z);
  72468. normals.push(vn.x, vn.y, vn.z);
  72469. normals.push(vn.x, vn.y, vn.z);
  72470. normals.push(vn.x, vn.y, vn.z);
  72471. indices.push(StartIndex);
  72472. indices.push(StartIndex + 2);
  72473. indices.push(StartIndex + 1);
  72474. indices.push(StartIndex + 1);
  72475. indices.push(StartIndex + 2);
  72476. indices.push(StartIndex + 3);
  72477. }
  72478. StartIndex += 4;
  72479. }
  72480. ;
  72481. };
  72482. return PolygonMeshBuilder;
  72483. }());
  72484. BABYLON.PolygonMeshBuilder = PolygonMeshBuilder;
  72485. })(BABYLON || (BABYLON = {}));
  72486. //# sourceMappingURL=babylon.polygonMesh.js.map
  72487. var BABYLON;
  72488. (function (BABYLON) {
  72489. // Unique ID when we import meshes from Babylon to CSG
  72490. var currentCSGMeshId = 0;
  72491. // # class Vertex
  72492. // Represents a vertex of a polygon. Use your own vertex class instead of this
  72493. // one to provide additional features like texture coordinates and vertex
  72494. // colors. Custom vertex classes need to provide a `pos` property and `clone()`,
  72495. // `flip()`, and `interpolate()` methods that behave analogous to the ones
  72496. // defined by `BABYLON.CSG.Vertex`. This class provides `normal` so convenience
  72497. // functions like `BABYLON.CSG.sphere()` can return a smooth vertex normal, but `normal`
  72498. // is not used anywhere else.
  72499. // Same goes for uv, it allows to keep the original vertex uv coordinates of the 2 meshes
  72500. var Vertex = /** @class */ (function () {
  72501. function Vertex(pos, normal, uv) {
  72502. this.pos = pos;
  72503. this.normal = normal;
  72504. this.uv = uv;
  72505. }
  72506. Vertex.prototype.clone = function () {
  72507. return new Vertex(this.pos.clone(), this.normal.clone(), this.uv.clone());
  72508. };
  72509. // Invert all orientation-specific data (e.g. vertex normal). Called when the
  72510. // orientation of a polygon is flipped.
  72511. Vertex.prototype.flip = function () {
  72512. this.normal = this.normal.scale(-1);
  72513. };
  72514. // Create a new vertex between this vertex and `other` by linearly
  72515. // interpolating all properties using a parameter of `t`. Subclasses should
  72516. // override this to interpolate additional properties.
  72517. Vertex.prototype.interpolate = function (other, t) {
  72518. 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));
  72519. };
  72520. return Vertex;
  72521. }());
  72522. // # class Plane
  72523. // Represents a plane in 3D space.
  72524. var Plane = /** @class */ (function () {
  72525. function Plane(normal, w) {
  72526. this.normal = normal;
  72527. this.w = w;
  72528. }
  72529. Plane.FromPoints = function (a, b, c) {
  72530. var v0 = c.subtract(a);
  72531. var v1 = b.subtract(a);
  72532. if (v0.lengthSquared() === 0 || v1.lengthSquared() === 0) {
  72533. return null;
  72534. }
  72535. var n = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(v0, v1));
  72536. return new Plane(n, BABYLON.Vector3.Dot(n, a));
  72537. };
  72538. Plane.prototype.clone = function () {
  72539. return new Plane(this.normal.clone(), this.w);
  72540. };
  72541. Plane.prototype.flip = function () {
  72542. this.normal.scaleInPlace(-1);
  72543. this.w = -this.w;
  72544. };
  72545. // Split `polygon` by this plane if needed, then put the polygon or polygon
  72546. // fragments in the appropriate lists. Coplanar polygons go into either
  72547. // `coplanarFront` or `coplanarBack` depending on their orientation with
  72548. // respect to this plane. Polygons in front or in back of this plane go into
  72549. // either `front` or `back`.
  72550. Plane.prototype.splitPolygon = function (polygon, coplanarFront, coplanarBack, front, back) {
  72551. var COPLANAR = 0;
  72552. var FRONT = 1;
  72553. var BACK = 2;
  72554. var SPANNING = 3;
  72555. // Classify each point as well as the entire polygon into one of the above
  72556. // four classes.
  72557. var polygonType = 0;
  72558. var types = [];
  72559. var i;
  72560. var t;
  72561. for (i = 0; i < polygon.vertices.length; i++) {
  72562. t = BABYLON.Vector3.Dot(this.normal, polygon.vertices[i].pos) - this.w;
  72563. var type = (t < -Plane.EPSILON) ? BACK : (t > Plane.EPSILON) ? FRONT : COPLANAR;
  72564. polygonType |= type;
  72565. types.push(type);
  72566. }
  72567. // Put the polygon in the correct list, splitting it when necessary.
  72568. switch (polygonType) {
  72569. case COPLANAR:
  72570. (BABYLON.Vector3.Dot(this.normal, polygon.plane.normal) > 0 ? coplanarFront : coplanarBack).push(polygon);
  72571. break;
  72572. case FRONT:
  72573. front.push(polygon);
  72574. break;
  72575. case BACK:
  72576. back.push(polygon);
  72577. break;
  72578. case SPANNING:
  72579. var f = [], b = [];
  72580. for (i = 0; i < polygon.vertices.length; i++) {
  72581. var j = (i + 1) % polygon.vertices.length;
  72582. var ti = types[i], tj = types[j];
  72583. var vi = polygon.vertices[i], vj = polygon.vertices[j];
  72584. if (ti !== BACK)
  72585. f.push(vi);
  72586. if (ti !== FRONT)
  72587. b.push(ti !== BACK ? vi.clone() : vi);
  72588. if ((ti | tj) === SPANNING) {
  72589. t = (this.w - BABYLON.Vector3.Dot(this.normal, vi.pos)) / BABYLON.Vector3.Dot(this.normal, vj.pos.subtract(vi.pos));
  72590. var v = vi.interpolate(vj, t);
  72591. f.push(v);
  72592. b.push(v.clone());
  72593. }
  72594. }
  72595. var poly;
  72596. if (f.length >= 3) {
  72597. poly = new Polygon(f, polygon.shared);
  72598. if (poly.plane)
  72599. front.push(poly);
  72600. }
  72601. if (b.length >= 3) {
  72602. poly = new Polygon(b, polygon.shared);
  72603. if (poly.plane)
  72604. back.push(poly);
  72605. }
  72606. break;
  72607. }
  72608. };
  72609. // `BABYLON.CSG.Plane.EPSILON` is the tolerance used by `splitPolygon()` to decide if a
  72610. // point is on the plane.
  72611. Plane.EPSILON = 1e-5;
  72612. return Plane;
  72613. }());
  72614. // # class Polygon
  72615. // Represents a convex polygon. The vertices used to initialize a polygon must
  72616. // be coplanar and form a convex loop.
  72617. //
  72618. // Each convex polygon has a `shared` property, which is shared between all
  72619. // polygons that are clones of each other or were split from the same polygon.
  72620. // This can be used to define per-polygon properties (such as surface color).
  72621. var Polygon = /** @class */ (function () {
  72622. function Polygon(vertices, shared) {
  72623. this.vertices = vertices;
  72624. this.shared = shared;
  72625. this.plane = Plane.FromPoints(vertices[0].pos, vertices[1].pos, vertices[2].pos);
  72626. }
  72627. Polygon.prototype.clone = function () {
  72628. var vertices = this.vertices.map(function (v) { return v.clone(); });
  72629. return new Polygon(vertices, this.shared);
  72630. };
  72631. Polygon.prototype.flip = function () {
  72632. this.vertices.reverse().map(function (v) { v.flip(); });
  72633. this.plane.flip();
  72634. };
  72635. return Polygon;
  72636. }());
  72637. // # class Node
  72638. // Holds a node in a BSP tree. A BSP tree is built from a collection of polygons
  72639. // by picking a polygon to split along. That polygon (and all other coplanar
  72640. // polygons) are added directly to that node and the other polygons are added to
  72641. // the front and/or back subtrees. This is not a leafy BSP tree since there is
  72642. // no distinction between internal and leaf nodes.
  72643. var Node = /** @class */ (function () {
  72644. function Node(polygons) {
  72645. this.plane = null;
  72646. this.front = null;
  72647. this.back = null;
  72648. this.polygons = new Array();
  72649. if (polygons) {
  72650. this.build(polygons);
  72651. }
  72652. }
  72653. Node.prototype.clone = function () {
  72654. var node = new Node();
  72655. node.plane = this.plane && this.plane.clone();
  72656. node.front = this.front && this.front.clone();
  72657. node.back = this.back && this.back.clone();
  72658. node.polygons = this.polygons.map(function (p) { return p.clone(); });
  72659. return node;
  72660. };
  72661. // Convert solid space to empty space and empty space to solid space.
  72662. Node.prototype.invert = function () {
  72663. for (var i = 0; i < this.polygons.length; i++) {
  72664. this.polygons[i].flip();
  72665. }
  72666. if (this.plane) {
  72667. this.plane.flip();
  72668. }
  72669. if (this.front) {
  72670. this.front.invert();
  72671. }
  72672. if (this.back) {
  72673. this.back.invert();
  72674. }
  72675. var temp = this.front;
  72676. this.front = this.back;
  72677. this.back = temp;
  72678. };
  72679. // Recursively remove all polygons in `polygons` that are inside this BSP
  72680. // tree.
  72681. Node.prototype.clipPolygons = function (polygons) {
  72682. if (!this.plane)
  72683. return polygons.slice();
  72684. var front = new Array(), back = new Array();
  72685. for (var i = 0; i < polygons.length; i++) {
  72686. this.plane.splitPolygon(polygons[i], front, back, front, back);
  72687. }
  72688. if (this.front) {
  72689. front = this.front.clipPolygons(front);
  72690. }
  72691. if (this.back) {
  72692. back = this.back.clipPolygons(back);
  72693. }
  72694. else {
  72695. back = [];
  72696. }
  72697. return front.concat(back);
  72698. };
  72699. // Remove all polygons in this BSP tree that are inside the other BSP tree
  72700. // `bsp`.
  72701. Node.prototype.clipTo = function (bsp) {
  72702. this.polygons = bsp.clipPolygons(this.polygons);
  72703. if (this.front)
  72704. this.front.clipTo(bsp);
  72705. if (this.back)
  72706. this.back.clipTo(bsp);
  72707. };
  72708. // Return a list of all polygons in this BSP tree.
  72709. Node.prototype.allPolygons = function () {
  72710. var polygons = this.polygons.slice();
  72711. if (this.front)
  72712. polygons = polygons.concat(this.front.allPolygons());
  72713. if (this.back)
  72714. polygons = polygons.concat(this.back.allPolygons());
  72715. return polygons;
  72716. };
  72717. // Build a BSP tree out of `polygons`. When called on an existing tree, the
  72718. // new polygons are filtered down to the bottom of the tree and become new
  72719. // nodes there. Each set of polygons is partitioned using the first polygon
  72720. // (no heuristic is used to pick a good split).
  72721. Node.prototype.build = function (polygons) {
  72722. if (!polygons.length)
  72723. return;
  72724. if (!this.plane)
  72725. this.plane = polygons[0].plane.clone();
  72726. var front = new Array(), back = new Array();
  72727. for (var i = 0; i < polygons.length; i++) {
  72728. this.plane.splitPolygon(polygons[i], this.polygons, this.polygons, front, back);
  72729. }
  72730. if (front.length) {
  72731. if (!this.front)
  72732. this.front = new Node();
  72733. this.front.build(front);
  72734. }
  72735. if (back.length) {
  72736. if (!this.back)
  72737. this.back = new Node();
  72738. this.back.build(back);
  72739. }
  72740. };
  72741. return Node;
  72742. }());
  72743. var CSG = /** @class */ (function () {
  72744. function CSG() {
  72745. this.polygons = new Array();
  72746. }
  72747. // Convert BABYLON.Mesh to BABYLON.CSG
  72748. CSG.FromMesh = function (mesh) {
  72749. var vertex, normal, uv, position, polygon, polygons = new Array(), vertices;
  72750. var matrix, meshPosition, meshRotation, meshRotationQuaternion = null, meshScaling;
  72751. if (mesh instanceof BABYLON.Mesh) {
  72752. mesh.computeWorldMatrix(true);
  72753. matrix = mesh.getWorldMatrix();
  72754. meshPosition = mesh.position.clone();
  72755. meshRotation = mesh.rotation.clone();
  72756. if (mesh.rotationQuaternion) {
  72757. meshRotationQuaternion = mesh.rotationQuaternion.clone();
  72758. }
  72759. meshScaling = mesh.scaling.clone();
  72760. }
  72761. else {
  72762. throw 'BABYLON.CSG: Wrong Mesh type, must be BABYLON.Mesh';
  72763. }
  72764. var indices = mesh.getIndices(), positions = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind), normals = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind), uvs = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  72765. var subMeshes = mesh.subMeshes;
  72766. for (var sm = 0, sml = subMeshes.length; sm < sml; sm++) {
  72767. for (var i = subMeshes[sm].indexStart, il = subMeshes[sm].indexCount + subMeshes[sm].indexStart; i < il; i += 3) {
  72768. vertices = [];
  72769. for (var j = 0; j < 3; j++) {
  72770. var sourceNormal = new BABYLON.Vector3(normals[indices[i + j] * 3], normals[indices[i + j] * 3 + 1], normals[indices[i + j] * 3 + 2]);
  72771. uv = new BABYLON.Vector2(uvs[indices[i + j] * 2], uvs[indices[i + j] * 2 + 1]);
  72772. var sourcePosition = new BABYLON.Vector3(positions[indices[i + j] * 3], positions[indices[i + j] * 3 + 1], positions[indices[i + j] * 3 + 2]);
  72773. position = BABYLON.Vector3.TransformCoordinates(sourcePosition, matrix);
  72774. normal = BABYLON.Vector3.TransformNormal(sourceNormal, matrix);
  72775. vertex = new Vertex(position, normal, uv);
  72776. vertices.push(vertex);
  72777. }
  72778. polygon = new Polygon(vertices, { subMeshId: sm, meshId: currentCSGMeshId, materialIndex: subMeshes[sm].materialIndex });
  72779. // To handle the case of degenerated triangle
  72780. // polygon.plane == null <=> the polygon does not represent 1 single plane <=> the triangle is degenerated
  72781. if (polygon.plane)
  72782. polygons.push(polygon);
  72783. }
  72784. }
  72785. var csg = CSG.FromPolygons(polygons);
  72786. csg.matrix = matrix;
  72787. csg.position = meshPosition;
  72788. csg.rotation = meshRotation;
  72789. csg.scaling = meshScaling;
  72790. csg.rotationQuaternion = meshRotationQuaternion;
  72791. currentCSGMeshId++;
  72792. return csg;
  72793. };
  72794. // Construct a BABYLON.CSG solid from a list of `BABYLON.CSG.Polygon` instances.
  72795. CSG.FromPolygons = function (polygons) {
  72796. var csg = new CSG();
  72797. csg.polygons = polygons;
  72798. return csg;
  72799. };
  72800. CSG.prototype.clone = function () {
  72801. var csg = new CSG();
  72802. csg.polygons = this.polygons.map(function (p) { return p.clone(); });
  72803. csg.copyTransformAttributes(this);
  72804. return csg;
  72805. };
  72806. CSG.prototype.union = function (csg) {
  72807. var a = new Node(this.clone().polygons);
  72808. var b = new Node(csg.clone().polygons);
  72809. a.clipTo(b);
  72810. b.clipTo(a);
  72811. b.invert();
  72812. b.clipTo(a);
  72813. b.invert();
  72814. a.build(b.allPolygons());
  72815. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  72816. };
  72817. CSG.prototype.unionInPlace = function (csg) {
  72818. var a = new Node(this.polygons);
  72819. var b = new Node(csg.polygons);
  72820. a.clipTo(b);
  72821. b.clipTo(a);
  72822. b.invert();
  72823. b.clipTo(a);
  72824. b.invert();
  72825. a.build(b.allPolygons());
  72826. this.polygons = a.allPolygons();
  72827. };
  72828. CSG.prototype.subtract = function (csg) {
  72829. var a = new Node(this.clone().polygons);
  72830. var b = new Node(csg.clone().polygons);
  72831. a.invert();
  72832. a.clipTo(b);
  72833. b.clipTo(a);
  72834. b.invert();
  72835. b.clipTo(a);
  72836. b.invert();
  72837. a.build(b.allPolygons());
  72838. a.invert();
  72839. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  72840. };
  72841. CSG.prototype.subtractInPlace = function (csg) {
  72842. var a = new Node(this.polygons);
  72843. var b = new Node(csg.polygons);
  72844. a.invert();
  72845. a.clipTo(b);
  72846. b.clipTo(a);
  72847. b.invert();
  72848. b.clipTo(a);
  72849. b.invert();
  72850. a.build(b.allPolygons());
  72851. a.invert();
  72852. this.polygons = a.allPolygons();
  72853. };
  72854. CSG.prototype.intersect = function (csg) {
  72855. var a = new Node(this.clone().polygons);
  72856. var b = new Node(csg.clone().polygons);
  72857. a.invert();
  72858. b.clipTo(a);
  72859. b.invert();
  72860. a.clipTo(b);
  72861. b.clipTo(a);
  72862. a.build(b.allPolygons());
  72863. a.invert();
  72864. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  72865. };
  72866. CSG.prototype.intersectInPlace = function (csg) {
  72867. var a = new Node(this.polygons);
  72868. var b = new Node(csg.polygons);
  72869. a.invert();
  72870. b.clipTo(a);
  72871. b.invert();
  72872. a.clipTo(b);
  72873. b.clipTo(a);
  72874. a.build(b.allPolygons());
  72875. a.invert();
  72876. this.polygons = a.allPolygons();
  72877. };
  72878. // Return a new BABYLON.CSG solid with solid and empty space switched. This solid is
  72879. // not modified.
  72880. CSG.prototype.inverse = function () {
  72881. var csg = this.clone();
  72882. csg.inverseInPlace();
  72883. return csg;
  72884. };
  72885. CSG.prototype.inverseInPlace = function () {
  72886. this.polygons.map(function (p) { p.flip(); });
  72887. };
  72888. // This is used to keep meshes transformations so they can be restored
  72889. // when we build back a Babylon Mesh
  72890. // NB : All CSG operations are performed in world coordinates
  72891. CSG.prototype.copyTransformAttributes = function (csg) {
  72892. this.matrix = csg.matrix;
  72893. this.position = csg.position;
  72894. this.rotation = csg.rotation;
  72895. this.scaling = csg.scaling;
  72896. this.rotationQuaternion = csg.rotationQuaternion;
  72897. return this;
  72898. };
  72899. // Build Raw mesh from CSG
  72900. // Coordinates here are in world space
  72901. CSG.prototype.buildMeshGeometry = function (name, scene, keepSubMeshes) {
  72902. var matrix = this.matrix.clone();
  72903. matrix.invert();
  72904. 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;
  72905. if (keepSubMeshes) {
  72906. // Sort Polygons, since subMeshes are indices range
  72907. polygons.sort(function (a, b) {
  72908. if (a.shared.meshId === b.shared.meshId) {
  72909. return a.shared.subMeshId - b.shared.subMeshId;
  72910. }
  72911. else {
  72912. return a.shared.meshId - b.shared.meshId;
  72913. }
  72914. });
  72915. }
  72916. for (var i = 0, il = polygons.length; i < il; i++) {
  72917. polygon = polygons[i];
  72918. // Building SubMeshes
  72919. if (!subMesh_dict[polygon.shared.meshId]) {
  72920. subMesh_dict[polygon.shared.meshId] = {};
  72921. }
  72922. if (!subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId]) {
  72923. subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId] = {
  72924. indexStart: +Infinity,
  72925. indexEnd: -Infinity,
  72926. materialIndex: polygon.shared.materialIndex
  72927. };
  72928. }
  72929. subMesh_obj = subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId];
  72930. for (var j = 2, jl = polygon.vertices.length; j < jl; j++) {
  72931. polygonIndices[0] = 0;
  72932. polygonIndices[1] = j - 1;
  72933. polygonIndices[2] = j;
  72934. for (var k = 0; k < 3; k++) {
  72935. vertex.copyFrom(polygon.vertices[polygonIndices[k]].pos);
  72936. normal.copyFrom(polygon.vertices[polygonIndices[k]].normal);
  72937. uv.copyFrom(polygon.vertices[polygonIndices[k]].uv);
  72938. var localVertex = BABYLON.Vector3.TransformCoordinates(vertex, matrix);
  72939. var localNormal = BABYLON.Vector3.TransformNormal(normal, matrix);
  72940. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z];
  72941. // Check if 2 points can be merged
  72942. if (!(typeof vertex_idx !== 'undefined' &&
  72943. normals[vertex_idx * 3] === localNormal.x &&
  72944. normals[vertex_idx * 3 + 1] === localNormal.y &&
  72945. normals[vertex_idx * 3 + 2] === localNormal.z &&
  72946. uvs[vertex_idx * 2] === uv.x &&
  72947. uvs[vertex_idx * 2 + 1] === uv.y)) {
  72948. vertices.push(localVertex.x, localVertex.y, localVertex.z);
  72949. uvs.push(uv.x, uv.y);
  72950. normals.push(normal.x, normal.y, normal.z);
  72951. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z] = (vertices.length / 3) - 1;
  72952. }
  72953. indices.push(vertex_idx);
  72954. subMesh_obj.indexStart = Math.min(currentIndex, subMesh_obj.indexStart);
  72955. subMesh_obj.indexEnd = Math.max(currentIndex, subMesh_obj.indexEnd);
  72956. currentIndex++;
  72957. }
  72958. }
  72959. }
  72960. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, vertices);
  72961. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  72962. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs);
  72963. mesh.setIndices(indices, null);
  72964. if (keepSubMeshes) {
  72965. // We offset the materialIndex by the previous number of materials in the CSG mixed meshes
  72966. var materialIndexOffset = 0, materialMaxIndex;
  72967. mesh.subMeshes = new Array();
  72968. for (var m in subMesh_dict) {
  72969. materialMaxIndex = -1;
  72970. for (var sm in subMesh_dict[m]) {
  72971. subMesh_obj = subMesh_dict[m][sm];
  72972. BABYLON.SubMesh.CreateFromIndices(subMesh_obj.materialIndex + materialIndexOffset, subMesh_obj.indexStart, subMesh_obj.indexEnd - subMesh_obj.indexStart + 1, mesh);
  72973. materialMaxIndex = Math.max(subMesh_obj.materialIndex, materialMaxIndex);
  72974. }
  72975. materialIndexOffset += ++materialMaxIndex;
  72976. }
  72977. }
  72978. return mesh;
  72979. };
  72980. // Build Mesh from CSG taking material and transforms into account
  72981. CSG.prototype.toMesh = function (name, material, scene, keepSubMeshes) {
  72982. var mesh = this.buildMeshGeometry(name, scene, keepSubMeshes);
  72983. mesh.material = material;
  72984. mesh.position.copyFrom(this.position);
  72985. mesh.rotation.copyFrom(this.rotation);
  72986. if (this.rotationQuaternion) {
  72987. mesh.rotationQuaternion = this.rotationQuaternion.clone();
  72988. }
  72989. mesh.scaling.copyFrom(this.scaling);
  72990. mesh.computeWorldMatrix(true);
  72991. return mesh;
  72992. };
  72993. return CSG;
  72994. }());
  72995. BABYLON.CSG = CSG;
  72996. })(BABYLON || (BABYLON = {}));
  72997. //# sourceMappingURL=babylon.csg.js.map
  72998. var BABYLON;
  72999. (function (BABYLON) {
  73000. var LensFlare = /** @class */ (function () {
  73001. function LensFlare(size, position, color, imgUrl, system) {
  73002. this.size = size;
  73003. this.position = position;
  73004. this.alphaMode = BABYLON.Engine.ALPHA_ONEONE;
  73005. this.color = color || new BABYLON.Color3(1, 1, 1);
  73006. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, system.getScene(), true) : null;
  73007. this._system = system;
  73008. system.lensFlares.push(this);
  73009. }
  73010. LensFlare.AddFlare = function (size, position, color, imgUrl, system) {
  73011. return new LensFlare(size, position, color, imgUrl, system);
  73012. };
  73013. LensFlare.prototype.dispose = function () {
  73014. if (this.texture) {
  73015. this.texture.dispose();
  73016. }
  73017. // Remove from scene
  73018. var index = this._system.lensFlares.indexOf(this);
  73019. this._system.lensFlares.splice(index, 1);
  73020. };
  73021. ;
  73022. return LensFlare;
  73023. }());
  73024. BABYLON.LensFlare = LensFlare;
  73025. })(BABYLON || (BABYLON = {}));
  73026. //# sourceMappingURL=babylon.lensFlare.js.map
  73027. var BABYLON;
  73028. (function (BABYLON) {
  73029. var LensFlareSystem = /** @class */ (function () {
  73030. function LensFlareSystem(name, emitter, scene) {
  73031. this.name = name;
  73032. this.lensFlares = new Array();
  73033. this.borderLimit = 300;
  73034. this.viewportBorder = 0;
  73035. this.layerMask = 0x0FFFFFFF;
  73036. this._vertexBuffers = {};
  73037. this._isEnabled = true;
  73038. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  73039. this._emitter = emitter;
  73040. this.id = name;
  73041. scene.lensFlareSystems.push(this);
  73042. this.meshesSelectionPredicate = function (m) { return (scene.activeCamera && m.material && m.isVisible && m.isEnabled() && m.isBlocker && ((m.layerMask & scene.activeCamera.layerMask) != 0)); };
  73043. var engine = scene.getEngine();
  73044. // VBO
  73045. var vertices = [];
  73046. vertices.push(1, 1);
  73047. vertices.push(-1, 1);
  73048. vertices.push(-1, -1);
  73049. vertices.push(1, -1);
  73050. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  73051. // Indices
  73052. var indices = [];
  73053. indices.push(0);
  73054. indices.push(1);
  73055. indices.push(2);
  73056. indices.push(0);
  73057. indices.push(2);
  73058. indices.push(3);
  73059. this._indexBuffer = engine.createIndexBuffer(indices);
  73060. // Effects
  73061. this._effect = engine.createEffect("lensFlare", [BABYLON.VertexBuffer.PositionKind], ["color", "viewportMatrix"], ["textureSampler"], "");
  73062. }
  73063. Object.defineProperty(LensFlareSystem.prototype, "isEnabled", {
  73064. get: function () {
  73065. return this._isEnabled;
  73066. },
  73067. set: function (value) {
  73068. this._isEnabled = value;
  73069. },
  73070. enumerable: true,
  73071. configurable: true
  73072. });
  73073. LensFlareSystem.prototype.getScene = function () {
  73074. return this._scene;
  73075. };
  73076. LensFlareSystem.prototype.getEmitter = function () {
  73077. return this._emitter;
  73078. };
  73079. LensFlareSystem.prototype.setEmitter = function (newEmitter) {
  73080. this._emitter = newEmitter;
  73081. };
  73082. LensFlareSystem.prototype.getEmitterPosition = function () {
  73083. return this._emitter.getAbsolutePosition ? this._emitter.getAbsolutePosition() : this._emitter.position;
  73084. };
  73085. LensFlareSystem.prototype.computeEffectivePosition = function (globalViewport) {
  73086. var position = this.getEmitterPosition();
  73087. position = BABYLON.Vector3.Project(position, BABYLON.Matrix.Identity(), this._scene.getTransformMatrix(), globalViewport);
  73088. this._positionX = position.x;
  73089. this._positionY = position.y;
  73090. position = BABYLON.Vector3.TransformCoordinates(this.getEmitterPosition(), this._scene.getViewMatrix());
  73091. if (this.viewportBorder > 0) {
  73092. globalViewport.x -= this.viewportBorder;
  73093. globalViewport.y -= this.viewportBorder;
  73094. globalViewport.width += this.viewportBorder * 2;
  73095. globalViewport.height += this.viewportBorder * 2;
  73096. position.x += this.viewportBorder;
  73097. position.y += this.viewportBorder;
  73098. this._positionX += this.viewportBorder;
  73099. this._positionY += this.viewportBorder;
  73100. }
  73101. if (position.z > 0) {
  73102. if ((this._positionX > globalViewport.x) && (this._positionX < globalViewport.x + globalViewport.width)) {
  73103. if ((this._positionY > globalViewport.y) && (this._positionY < globalViewport.y + globalViewport.height))
  73104. return true;
  73105. }
  73106. return true;
  73107. }
  73108. return false;
  73109. };
  73110. LensFlareSystem.prototype._isVisible = function () {
  73111. if (!this._isEnabled || !this._scene.activeCamera) {
  73112. return false;
  73113. }
  73114. var emitterPosition = this.getEmitterPosition();
  73115. var direction = emitterPosition.subtract(this._scene.activeCamera.globalPosition);
  73116. var distance = direction.length();
  73117. direction.normalize();
  73118. var ray = new BABYLON.Ray(this._scene.activeCamera.globalPosition, direction);
  73119. var pickInfo = this._scene.pickWithRay(ray, this.meshesSelectionPredicate, true);
  73120. return !pickInfo || !pickInfo.hit || pickInfo.distance > distance;
  73121. };
  73122. LensFlareSystem.prototype.render = function () {
  73123. if (!this._effect.isReady() || !this._scene.activeCamera)
  73124. return false;
  73125. var engine = this._scene.getEngine();
  73126. var viewport = this._scene.activeCamera.viewport;
  73127. var globalViewport = viewport.toGlobal(engine.getRenderWidth(true), engine.getRenderHeight(true));
  73128. // Position
  73129. if (!this.computeEffectivePosition(globalViewport)) {
  73130. return false;
  73131. }
  73132. // Visibility
  73133. if (!this._isVisible()) {
  73134. return false;
  73135. }
  73136. // Intensity
  73137. var awayX;
  73138. var awayY;
  73139. if (this._positionX < this.borderLimit + globalViewport.x) {
  73140. awayX = this.borderLimit + globalViewport.x - this._positionX;
  73141. }
  73142. else if (this._positionX > globalViewport.x + globalViewport.width - this.borderLimit) {
  73143. awayX = this._positionX - globalViewport.x - globalViewport.width + this.borderLimit;
  73144. }
  73145. else {
  73146. awayX = 0;
  73147. }
  73148. if (this._positionY < this.borderLimit + globalViewport.y) {
  73149. awayY = this.borderLimit + globalViewport.y - this._positionY;
  73150. }
  73151. else if (this._positionY > globalViewport.y + globalViewport.height - this.borderLimit) {
  73152. awayY = this._positionY - globalViewport.y - globalViewport.height + this.borderLimit;
  73153. }
  73154. else {
  73155. awayY = 0;
  73156. }
  73157. var away = (awayX > awayY) ? awayX : awayY;
  73158. away -= this.viewportBorder;
  73159. if (away > this.borderLimit) {
  73160. away = this.borderLimit;
  73161. }
  73162. var intensity = 1.0 - (away / this.borderLimit);
  73163. if (intensity < 0) {
  73164. return false;
  73165. }
  73166. if (intensity > 1.0) {
  73167. intensity = 1.0;
  73168. }
  73169. if (this.viewportBorder > 0) {
  73170. globalViewport.x += this.viewportBorder;
  73171. globalViewport.y += this.viewportBorder;
  73172. globalViewport.width -= this.viewportBorder * 2;
  73173. globalViewport.height -= this.viewportBorder * 2;
  73174. this._positionX -= this.viewportBorder;
  73175. this._positionY -= this.viewportBorder;
  73176. }
  73177. // Position
  73178. var centerX = globalViewport.x + globalViewport.width / 2;
  73179. var centerY = globalViewport.y + globalViewport.height / 2;
  73180. var distX = centerX - this._positionX;
  73181. var distY = centerY - this._positionY;
  73182. // Effects
  73183. engine.enableEffect(this._effect);
  73184. engine.setState(false);
  73185. engine.setDepthBuffer(false);
  73186. // VBOs
  73187. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  73188. // Flares
  73189. for (var index = 0; index < this.lensFlares.length; index++) {
  73190. var flare = this.lensFlares[index];
  73191. engine.setAlphaMode(flare.alphaMode);
  73192. var x = centerX - (distX * flare.position);
  73193. var y = centerY - (distY * flare.position);
  73194. var cw = flare.size;
  73195. var ch = flare.size * engine.getAspectRatio(this._scene.activeCamera, true);
  73196. var cx = 2 * (x / (globalViewport.width + globalViewport.x * 2)) - 1.0;
  73197. var cy = 1.0 - 2 * (y / (globalViewport.height + globalViewport.y * 2));
  73198. var viewportMatrix = BABYLON.Matrix.FromValues(cw / 2, 0, 0, 0, 0, ch / 2, 0, 0, 0, 0, 1, 0, cx, cy, 0, 1);
  73199. this._effect.setMatrix("viewportMatrix", viewportMatrix);
  73200. // Texture
  73201. this._effect.setTexture("textureSampler", flare.texture);
  73202. // Color
  73203. this._effect.setFloat4("color", flare.color.r * intensity, flare.color.g * intensity, flare.color.b * intensity, 1.0);
  73204. // Draw order
  73205. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  73206. }
  73207. engine.setDepthBuffer(true);
  73208. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  73209. return true;
  73210. };
  73211. LensFlareSystem.prototype.dispose = function () {
  73212. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  73213. if (vertexBuffer) {
  73214. vertexBuffer.dispose();
  73215. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  73216. }
  73217. if (this._indexBuffer) {
  73218. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  73219. this._indexBuffer = null;
  73220. }
  73221. while (this.lensFlares.length) {
  73222. this.lensFlares[0].dispose();
  73223. }
  73224. // Remove from scene
  73225. var index = this._scene.lensFlareSystems.indexOf(this);
  73226. this._scene.lensFlareSystems.splice(index, 1);
  73227. };
  73228. LensFlareSystem.Parse = function (parsedLensFlareSystem, scene, rootUrl) {
  73229. var emitter = scene.getLastEntryByID(parsedLensFlareSystem.emitterId);
  73230. var name = parsedLensFlareSystem.name || "lensFlareSystem#" + parsedLensFlareSystem.emitterId;
  73231. var lensFlareSystem = new LensFlareSystem(name, emitter, scene);
  73232. lensFlareSystem.id = parsedLensFlareSystem.id || name;
  73233. lensFlareSystem.borderLimit = parsedLensFlareSystem.borderLimit;
  73234. for (var index = 0; index < parsedLensFlareSystem.flares.length; index++) {
  73235. var parsedFlare = parsedLensFlareSystem.flares[index];
  73236. BABYLON.LensFlare.AddFlare(parsedFlare.size, parsedFlare.position, BABYLON.Color3.FromArray(parsedFlare.color), parsedFlare.textureName ? rootUrl + parsedFlare.textureName : "", lensFlareSystem);
  73237. }
  73238. return lensFlareSystem;
  73239. };
  73240. LensFlareSystem.prototype.serialize = function () {
  73241. var serializationObject = {};
  73242. serializationObject.id = this.id;
  73243. serializationObject.name = this.name;
  73244. serializationObject.emitterId = this.getEmitter().id;
  73245. serializationObject.borderLimit = this.borderLimit;
  73246. serializationObject.flares = [];
  73247. for (var index = 0; index < this.lensFlares.length; index++) {
  73248. var flare = this.lensFlares[index];
  73249. serializationObject.flares.push({
  73250. size: flare.size,
  73251. position: flare.position,
  73252. color: flare.color.asArray(),
  73253. textureName: BABYLON.Tools.GetFilename(flare.texture ? flare.texture.name : "")
  73254. });
  73255. }
  73256. return serializationObject;
  73257. };
  73258. return LensFlareSystem;
  73259. }());
  73260. BABYLON.LensFlareSystem = LensFlareSystem;
  73261. })(BABYLON || (BABYLON = {}));
  73262. //# sourceMappingURL=babylon.lensFlareSystem.js.map
  73263. var BABYLON;
  73264. (function (BABYLON) {
  73265. /**
  73266. * This is a holder class for the physics joint created by the physics plugin.
  73267. * It holds a set of functions to control the underlying joint.
  73268. */
  73269. var PhysicsJoint = /** @class */ (function () {
  73270. function PhysicsJoint(type, jointData) {
  73271. this.type = type;
  73272. this.jointData = jointData;
  73273. jointData.nativeParams = jointData.nativeParams || {};
  73274. }
  73275. Object.defineProperty(PhysicsJoint.prototype, "physicsJoint", {
  73276. get: function () {
  73277. return this._physicsJoint;
  73278. },
  73279. set: function (newJoint) {
  73280. if (this._physicsJoint) {
  73281. //remove from the wolrd
  73282. }
  73283. this._physicsJoint = newJoint;
  73284. },
  73285. enumerable: true,
  73286. configurable: true
  73287. });
  73288. Object.defineProperty(PhysicsJoint.prototype, "physicsPlugin", {
  73289. set: function (physicsPlugin) {
  73290. this._physicsPlugin = physicsPlugin;
  73291. },
  73292. enumerable: true,
  73293. configurable: true
  73294. });
  73295. /**
  73296. * Execute a function that is physics-plugin specific.
  73297. * @param {Function} func the function that will be executed.
  73298. * It accepts two parameters: the physics world and the physics joint.
  73299. */
  73300. PhysicsJoint.prototype.executeNativeFunction = function (func) {
  73301. func(this._physicsPlugin.world, this._physicsJoint);
  73302. };
  73303. //TODO check if the native joints are the same
  73304. //Joint Types
  73305. PhysicsJoint.DistanceJoint = 0;
  73306. PhysicsJoint.HingeJoint = 1;
  73307. PhysicsJoint.BallAndSocketJoint = 2;
  73308. PhysicsJoint.WheelJoint = 3;
  73309. PhysicsJoint.SliderJoint = 4;
  73310. //OIMO
  73311. PhysicsJoint.PrismaticJoint = 5;
  73312. //ENERGY FTW! (compare with this - http://ode-wiki.org/wiki/index.php?title=Manual:_Joint_Types_and_Functions)
  73313. PhysicsJoint.UniversalJoint = 6;
  73314. PhysicsJoint.Hinge2Joint = PhysicsJoint.WheelJoint;
  73315. //Cannon
  73316. //Similar to a Ball-Joint. Different in params
  73317. PhysicsJoint.PointToPointJoint = 8;
  73318. //Cannon only at the moment
  73319. PhysicsJoint.SpringJoint = 9;
  73320. PhysicsJoint.LockJoint = 10;
  73321. return PhysicsJoint;
  73322. }());
  73323. BABYLON.PhysicsJoint = PhysicsJoint;
  73324. /**
  73325. * A class representing a physics distance joint.
  73326. */
  73327. var DistanceJoint = /** @class */ (function (_super) {
  73328. __extends(DistanceJoint, _super);
  73329. function DistanceJoint(jointData) {
  73330. return _super.call(this, PhysicsJoint.DistanceJoint, jointData) || this;
  73331. }
  73332. /**
  73333. * Update the predefined distance.
  73334. */
  73335. DistanceJoint.prototype.updateDistance = function (maxDistance, minDistance) {
  73336. this._physicsPlugin.updateDistanceJoint(this, maxDistance, minDistance);
  73337. };
  73338. return DistanceJoint;
  73339. }(PhysicsJoint));
  73340. BABYLON.DistanceJoint = DistanceJoint;
  73341. var MotorEnabledJoint = /** @class */ (function (_super) {
  73342. __extends(MotorEnabledJoint, _super);
  73343. function MotorEnabledJoint(type, jointData) {
  73344. return _super.call(this, type, jointData) || this;
  73345. }
  73346. /**
  73347. * Set the motor values.
  73348. * Attention, this function is plugin specific. Engines won't react 100% the same.
  73349. * @param {number} force the force to apply
  73350. * @param {number} maxForce max force for this motor.
  73351. */
  73352. MotorEnabledJoint.prototype.setMotor = function (force, maxForce) {
  73353. this._physicsPlugin.setMotor(this, force || 0, maxForce);
  73354. };
  73355. /**
  73356. * Set the motor's limits.
  73357. * Attention, this function is plugin specific. Engines won't react 100% the same.
  73358. */
  73359. MotorEnabledJoint.prototype.setLimit = function (upperLimit, lowerLimit) {
  73360. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);
  73361. };
  73362. return MotorEnabledJoint;
  73363. }(PhysicsJoint));
  73364. BABYLON.MotorEnabledJoint = MotorEnabledJoint;
  73365. /**
  73366. * This class represents a single hinge physics joint
  73367. */
  73368. var HingeJoint = /** @class */ (function (_super) {
  73369. __extends(HingeJoint, _super);
  73370. function HingeJoint(jointData) {
  73371. return _super.call(this, PhysicsJoint.HingeJoint, jointData) || this;
  73372. }
  73373. /**
  73374. * Set the motor values.
  73375. * Attention, this function is plugin specific. Engines won't react 100% the same.
  73376. * @param {number} force the force to apply
  73377. * @param {number} maxForce max force for this motor.
  73378. */
  73379. HingeJoint.prototype.setMotor = function (force, maxForce) {
  73380. this._physicsPlugin.setMotor(this, force || 0, maxForce);
  73381. };
  73382. /**
  73383. * Set the motor's limits.
  73384. * Attention, this function is plugin specific. Engines won't react 100% the same.
  73385. */
  73386. HingeJoint.prototype.setLimit = function (upperLimit, lowerLimit) {
  73387. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);
  73388. };
  73389. return HingeJoint;
  73390. }(MotorEnabledJoint));
  73391. BABYLON.HingeJoint = HingeJoint;
  73392. /**
  73393. * This class represents a dual hinge physics joint (same as wheel joint)
  73394. */
  73395. var Hinge2Joint = /** @class */ (function (_super) {
  73396. __extends(Hinge2Joint, _super);
  73397. function Hinge2Joint(jointData) {
  73398. return _super.call(this, PhysicsJoint.Hinge2Joint, jointData) || this;
  73399. }
  73400. /**
  73401. * Set the motor values.
  73402. * Attention, this function is plugin specific. Engines won't react 100% the same.
  73403. * @param {number} force the force to apply
  73404. * @param {number} maxForce max force for this motor.
  73405. * @param {motorIndex} the motor's index, 0 or 1.
  73406. */
  73407. Hinge2Joint.prototype.setMotor = function (force, maxForce, motorIndex) {
  73408. if (motorIndex === void 0) { motorIndex = 0; }
  73409. this._physicsPlugin.setMotor(this, force || 0, maxForce, motorIndex);
  73410. };
  73411. /**
  73412. * Set the motor limits.
  73413. * Attention, this function is plugin specific. Engines won't react 100% the same.
  73414. * @param {number} upperLimit the upper limit
  73415. * @param {number} lowerLimit lower limit
  73416. * @param {motorIndex} the motor's index, 0 or 1.
  73417. */
  73418. Hinge2Joint.prototype.setLimit = function (upperLimit, lowerLimit, motorIndex) {
  73419. if (motorIndex === void 0) { motorIndex = 0; }
  73420. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit, motorIndex);
  73421. };
  73422. return Hinge2Joint;
  73423. }(MotorEnabledJoint));
  73424. BABYLON.Hinge2Joint = Hinge2Joint;
  73425. })(BABYLON || (BABYLON = {}));
  73426. //# sourceMappingURL=babylon.physicsJoint.js.map
  73427. var BABYLON;
  73428. (function (BABYLON) {
  73429. var PhysicsImpostor = /** @class */ (function () {
  73430. function PhysicsImpostor(object, type, _options, _scene) {
  73431. if (_options === void 0) { _options = { mass: 0 }; }
  73432. var _this = this;
  73433. this.object = object;
  73434. this.type = type;
  73435. this._options = _options;
  73436. this._scene = _scene;
  73437. this._bodyUpdateRequired = false;
  73438. this._onBeforePhysicsStepCallbacks = new Array();
  73439. this._onAfterPhysicsStepCallbacks = new Array();
  73440. this._onPhysicsCollideCallbacks = [];
  73441. this._deltaPosition = BABYLON.Vector3.Zero();
  73442. this._isDisposed = false;
  73443. //temp variables for parent rotation calculations
  73444. //private _mats: Array<Matrix> = [new Matrix(), new Matrix()];
  73445. this._tmpQuat = new BABYLON.Quaternion();
  73446. this._tmpQuat2 = new BABYLON.Quaternion();
  73447. /**
  73448. * this function is executed by the physics engine.
  73449. */
  73450. this.beforeStep = function () {
  73451. if (!_this._physicsEngine) {
  73452. return;
  73453. }
  73454. _this.object.translate(_this._deltaPosition, -1);
  73455. _this._deltaRotationConjugated && _this.object.rotationQuaternion && _this.object.rotationQuaternion.multiplyToRef(_this._deltaRotationConjugated, _this.object.rotationQuaternion);
  73456. _this.object.computeWorldMatrix(false);
  73457. if (_this.object.parent && _this.object.rotationQuaternion) {
  73458. _this.getParentsRotation();
  73459. _this._tmpQuat.multiplyToRef(_this.object.rotationQuaternion, _this._tmpQuat);
  73460. }
  73461. else {
  73462. _this._tmpQuat.copyFrom(_this.object.rotationQuaternion || new BABYLON.Quaternion());
  73463. }
  73464. if (!_this._options.disableBidirectionalTransformation) {
  73465. _this.object.rotationQuaternion && _this._physicsEngine.getPhysicsPlugin().setPhysicsBodyTransformation(_this, /*bInfo.boundingBox.centerWorld*/ _this.object.getAbsolutePivotPoint(), _this._tmpQuat);
  73466. }
  73467. _this._onBeforePhysicsStepCallbacks.forEach(function (func) {
  73468. func(_this);
  73469. });
  73470. };
  73471. /**
  73472. * this function is executed by the physics engine.
  73473. */
  73474. this.afterStep = function () {
  73475. if (!_this._physicsEngine) {
  73476. return;
  73477. }
  73478. _this._onAfterPhysicsStepCallbacks.forEach(function (func) {
  73479. func(_this);
  73480. });
  73481. _this._physicsEngine.getPhysicsPlugin().setTransformationFromPhysicsBody(_this);
  73482. // object has now its world rotation. needs to be converted to local.
  73483. if (_this.object.parent && _this.object.rotationQuaternion) {
  73484. _this.getParentsRotation();
  73485. _this._tmpQuat.conjugateInPlace();
  73486. _this._tmpQuat.multiplyToRef(_this.object.rotationQuaternion, _this.object.rotationQuaternion);
  73487. }
  73488. // take the position set and make it the absolute position of this object.
  73489. _this.object.setAbsolutePosition(_this.object.position);
  73490. _this._deltaRotation && _this.object.rotationQuaternion && _this.object.rotationQuaternion.multiplyToRef(_this._deltaRotation, _this.object.rotationQuaternion);
  73491. _this.object.translate(_this._deltaPosition, 1);
  73492. };
  73493. /**
  73494. * Legacy collision detection event support
  73495. */
  73496. this.onCollideEvent = null;
  73497. //event and body object due to cannon's event-based architecture.
  73498. this.onCollide = function (e) {
  73499. if (!_this._onPhysicsCollideCallbacks.length && !_this.onCollideEvent) {
  73500. return;
  73501. }
  73502. if (!_this._physicsEngine) {
  73503. return;
  73504. }
  73505. var otherImpostor = _this._physicsEngine.getImpostorWithPhysicsBody(e.body);
  73506. if (otherImpostor) {
  73507. // Legacy collision detection event support
  73508. if (_this.onCollideEvent) {
  73509. _this.onCollideEvent(_this, otherImpostor);
  73510. }
  73511. _this._onPhysicsCollideCallbacks.filter(function (obj) {
  73512. return obj.otherImpostors.indexOf(otherImpostor) !== -1;
  73513. }).forEach(function (obj) {
  73514. obj.callback(_this, otherImpostor);
  73515. });
  73516. }
  73517. };
  73518. //sanity check!
  73519. if (!this.object) {
  73520. BABYLON.Tools.Error("No object was provided. A physics object is obligatory");
  73521. return;
  73522. }
  73523. //legacy support for old syntax.
  73524. if (!this._scene && object.getScene) {
  73525. this._scene = object.getScene();
  73526. }
  73527. if (!this._scene) {
  73528. return;
  73529. }
  73530. this._physicsEngine = this._scene.getPhysicsEngine();
  73531. if (!this._physicsEngine) {
  73532. BABYLON.Tools.Error("Physics not enabled. Please use scene.enablePhysics(...) before creating impostors.");
  73533. }
  73534. else {
  73535. //set the object's quaternion, if not set
  73536. if (!this.object.rotationQuaternion) {
  73537. if (this.object.rotation) {
  73538. this.object.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.object.rotation.y, this.object.rotation.x, this.object.rotation.z);
  73539. }
  73540. else {
  73541. this.object.rotationQuaternion = new BABYLON.Quaternion();
  73542. }
  73543. }
  73544. //default options params
  73545. this._options.mass = (_options.mass === void 0) ? 0 : _options.mass;
  73546. this._options.friction = (_options.friction === void 0) ? 0.2 : _options.friction;
  73547. this._options.restitution = (_options.restitution === void 0) ? 0.2 : _options.restitution;
  73548. this._joints = [];
  73549. //If the mesh has a parent, don't initialize the physicsBody. Instead wait for the parent to do that.
  73550. if (!this.object.parent || this._options.ignoreParent) {
  73551. this._init();
  73552. }
  73553. else if (this.object.parent.physicsImpostor) {
  73554. BABYLON.Tools.Warn("You must affect impostors to children before affecting impostor to parent.");
  73555. }
  73556. }
  73557. }
  73558. Object.defineProperty(PhysicsImpostor.prototype, "isDisposed", {
  73559. get: function () {
  73560. return this._isDisposed;
  73561. },
  73562. enumerable: true,
  73563. configurable: true
  73564. });
  73565. Object.defineProperty(PhysicsImpostor.prototype, "mass", {
  73566. get: function () {
  73567. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyMass(this) : 0;
  73568. },
  73569. set: function (value) {
  73570. this.setMass(value);
  73571. },
  73572. enumerable: true,
  73573. configurable: true
  73574. });
  73575. Object.defineProperty(PhysicsImpostor.prototype, "friction", {
  73576. get: function () {
  73577. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyFriction(this) : 0;
  73578. },
  73579. set: function (value) {
  73580. if (!this._physicsEngine) {
  73581. return;
  73582. }
  73583. this._physicsEngine.getPhysicsPlugin().setBodyFriction(this, value);
  73584. },
  73585. enumerable: true,
  73586. configurable: true
  73587. });
  73588. Object.defineProperty(PhysicsImpostor.prototype, "restitution", {
  73589. get: function () {
  73590. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyRestitution(this) : 0;
  73591. },
  73592. set: function (value) {
  73593. if (!this._physicsEngine) {
  73594. return;
  73595. }
  73596. this._physicsEngine.getPhysicsPlugin().setBodyRestitution(this, value);
  73597. },
  73598. enumerable: true,
  73599. configurable: true
  73600. });
  73601. /**
  73602. * This function will completly initialize this impostor.
  73603. * It will create a new body - but only if this mesh has no parent.
  73604. * If it has, this impostor will not be used other than to define the impostor
  73605. * of the child mesh.
  73606. */
  73607. PhysicsImpostor.prototype._init = function () {
  73608. if (!this._physicsEngine) {
  73609. return;
  73610. }
  73611. this._physicsEngine.removeImpostor(this);
  73612. this.physicsBody = null;
  73613. this._parent = this._parent || this._getPhysicsParent();
  73614. if (!this._isDisposed && (!this.parent || this._options.ignoreParent)) {
  73615. this._physicsEngine.addImpostor(this);
  73616. }
  73617. };
  73618. PhysicsImpostor.prototype._getPhysicsParent = function () {
  73619. if (this.object.parent instanceof BABYLON.AbstractMesh) {
  73620. var parentMesh = this.object.parent;
  73621. return parentMesh.physicsImpostor;
  73622. }
  73623. return null;
  73624. };
  73625. /**
  73626. * Should a new body be generated.
  73627. */
  73628. PhysicsImpostor.prototype.isBodyInitRequired = function () {
  73629. return this._bodyUpdateRequired || (!this._physicsBody && !this._parent);
  73630. };
  73631. PhysicsImpostor.prototype.setScalingUpdated = function (updated) {
  73632. this.forceUpdate();
  73633. };
  73634. /**
  73635. * Force a regeneration of this or the parent's impostor's body.
  73636. * Use under cautious - This will remove all joints already implemented.
  73637. */
  73638. PhysicsImpostor.prototype.forceUpdate = function () {
  73639. this._init();
  73640. if (this.parent && !this._options.ignoreParent) {
  73641. this.parent.forceUpdate();
  73642. }
  73643. };
  73644. Object.defineProperty(PhysicsImpostor.prototype, "physicsBody", {
  73645. /*public get mesh(): AbstractMesh {
  73646. return this._mesh;
  73647. }*/
  73648. /**
  73649. * Gets the body that holds this impostor. Either its own, or its parent.
  73650. */
  73651. get: function () {
  73652. return (this._parent && !this._options.ignoreParent) ? this._parent.physicsBody : this._physicsBody;
  73653. },
  73654. /**
  73655. * Set the physics body. Used mainly by the physics engine/plugin
  73656. */
  73657. set: function (physicsBody) {
  73658. if (this._physicsBody && this._physicsEngine) {
  73659. this._physicsEngine.getPhysicsPlugin().removePhysicsBody(this);
  73660. }
  73661. this._physicsBody = physicsBody;
  73662. this.resetUpdateFlags();
  73663. },
  73664. enumerable: true,
  73665. configurable: true
  73666. });
  73667. Object.defineProperty(PhysicsImpostor.prototype, "parent", {
  73668. get: function () {
  73669. return !this._options.ignoreParent && this._parent ? this._parent : null;
  73670. },
  73671. set: function (value) {
  73672. this._parent = value;
  73673. },
  73674. enumerable: true,
  73675. configurable: true
  73676. });
  73677. PhysicsImpostor.prototype.resetUpdateFlags = function () {
  73678. this._bodyUpdateRequired = false;
  73679. };
  73680. PhysicsImpostor.prototype.getObjectExtendSize = function () {
  73681. if (this.object.getBoundingInfo) {
  73682. var q = this.object.rotationQuaternion;
  73683. //reset rotation
  73684. this.object.rotationQuaternion = PhysicsImpostor.IDENTITY_QUATERNION;
  73685. //calculate the world matrix with no rotation
  73686. this.object.computeWorldMatrix && this.object.computeWorldMatrix(true);
  73687. var boundingInfo = this.object.getBoundingInfo();
  73688. var size = boundingInfo.boundingBox.extendSizeWorld.scale(2);
  73689. //bring back the rotation
  73690. this.object.rotationQuaternion = q;
  73691. //calculate the world matrix with the new rotation
  73692. this.object.computeWorldMatrix && this.object.computeWorldMatrix(true);
  73693. return size;
  73694. }
  73695. else {
  73696. return PhysicsImpostor.DEFAULT_OBJECT_SIZE;
  73697. }
  73698. };
  73699. PhysicsImpostor.prototype.getObjectCenter = function () {
  73700. if (this.object.getBoundingInfo) {
  73701. var boundingInfo = this.object.getBoundingInfo();
  73702. return boundingInfo.boundingBox.centerWorld;
  73703. }
  73704. else {
  73705. return this.object.position;
  73706. }
  73707. };
  73708. /**
  73709. * Get a specific parametes from the options parameter.
  73710. */
  73711. PhysicsImpostor.prototype.getParam = function (paramName) {
  73712. return this._options[paramName];
  73713. };
  73714. /**
  73715. * Sets a specific parameter in the options given to the physics plugin
  73716. */
  73717. PhysicsImpostor.prototype.setParam = function (paramName, value) {
  73718. this._options[paramName] = value;
  73719. this._bodyUpdateRequired = true;
  73720. };
  73721. /**
  73722. * Specifically change the body's mass option. Won't recreate the physics body object
  73723. */
  73724. PhysicsImpostor.prototype.setMass = function (mass) {
  73725. if (this.getParam("mass") !== mass) {
  73726. this.setParam("mass", mass);
  73727. }
  73728. if (this._physicsEngine) {
  73729. this._physicsEngine.getPhysicsPlugin().setBodyMass(this, mass);
  73730. }
  73731. };
  73732. PhysicsImpostor.prototype.getLinearVelocity = function () {
  73733. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getLinearVelocity(this) : BABYLON.Vector3.Zero();
  73734. };
  73735. PhysicsImpostor.prototype.setLinearVelocity = function (velocity) {
  73736. if (this._physicsEngine) {
  73737. this._physicsEngine.getPhysicsPlugin().setLinearVelocity(this, velocity);
  73738. }
  73739. };
  73740. PhysicsImpostor.prototype.getAngularVelocity = function () {
  73741. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getAngularVelocity(this) : BABYLON.Vector3.Zero();
  73742. };
  73743. PhysicsImpostor.prototype.setAngularVelocity = function (velocity) {
  73744. if (this._physicsEngine) {
  73745. this._physicsEngine.getPhysicsPlugin().setAngularVelocity(this, velocity);
  73746. }
  73747. };
  73748. /**
  73749. * Execute a function with the physics plugin native code.
  73750. * Provide a function the will have two variables - the world object and the physics body object.
  73751. */
  73752. PhysicsImpostor.prototype.executeNativeFunction = function (func) {
  73753. if (this._physicsEngine) {
  73754. func(this._physicsEngine.getPhysicsPlugin().world, this.physicsBody);
  73755. }
  73756. };
  73757. /**
  73758. * Register a function that will be executed before the physics world is stepping forward.
  73759. */
  73760. PhysicsImpostor.prototype.registerBeforePhysicsStep = function (func) {
  73761. this._onBeforePhysicsStepCallbacks.push(func);
  73762. };
  73763. PhysicsImpostor.prototype.unregisterBeforePhysicsStep = function (func) {
  73764. var index = this._onBeforePhysicsStepCallbacks.indexOf(func);
  73765. if (index > -1) {
  73766. this._onBeforePhysicsStepCallbacks.splice(index, 1);
  73767. }
  73768. else {
  73769. BABYLON.Tools.Warn("Function to remove was not found");
  73770. }
  73771. };
  73772. /**
  73773. * Register a function that will be executed after the physics step
  73774. */
  73775. PhysicsImpostor.prototype.registerAfterPhysicsStep = function (func) {
  73776. this._onAfterPhysicsStepCallbacks.push(func);
  73777. };
  73778. PhysicsImpostor.prototype.unregisterAfterPhysicsStep = function (func) {
  73779. var index = this._onAfterPhysicsStepCallbacks.indexOf(func);
  73780. if (index > -1) {
  73781. this._onAfterPhysicsStepCallbacks.splice(index, 1);
  73782. }
  73783. else {
  73784. BABYLON.Tools.Warn("Function to remove was not found");
  73785. }
  73786. };
  73787. /**
  73788. * register a function that will be executed when this impostor collides against a different body.
  73789. */
  73790. PhysicsImpostor.prototype.registerOnPhysicsCollide = function (collideAgainst, func) {
  73791. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  73792. this._onPhysicsCollideCallbacks.push({ callback: func, otherImpostors: collidedAgainstList });
  73793. };
  73794. PhysicsImpostor.prototype.unregisterOnPhysicsCollide = function (collideAgainst, func) {
  73795. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  73796. var index = this._onPhysicsCollideCallbacks.indexOf({ callback: func, otherImpostors: collidedAgainstList });
  73797. if (index > -1) {
  73798. this._onPhysicsCollideCallbacks.splice(index, 1);
  73799. }
  73800. else {
  73801. BABYLON.Tools.Warn("Function to remove was not found");
  73802. }
  73803. };
  73804. PhysicsImpostor.prototype.getParentsRotation = function () {
  73805. var parent = this.object.parent;
  73806. this._tmpQuat.copyFromFloats(0, 0, 0, 1);
  73807. while (parent) {
  73808. if (parent.rotationQuaternion) {
  73809. this._tmpQuat2.copyFrom(parent.rotationQuaternion);
  73810. }
  73811. else {
  73812. BABYLON.Quaternion.RotationYawPitchRollToRef(parent.rotation.y, parent.rotation.x, parent.rotation.z, this._tmpQuat2);
  73813. }
  73814. this._tmpQuat.multiplyToRef(this._tmpQuat2, this._tmpQuat);
  73815. parent = parent.parent;
  73816. }
  73817. return this._tmpQuat;
  73818. };
  73819. /**
  73820. * Apply a force
  73821. */
  73822. PhysicsImpostor.prototype.applyForce = function (force, contactPoint) {
  73823. if (this._physicsEngine) {
  73824. this._physicsEngine.getPhysicsPlugin().applyForce(this, force, contactPoint);
  73825. }
  73826. return this;
  73827. };
  73828. /**
  73829. * Apply an impulse
  73830. */
  73831. PhysicsImpostor.prototype.applyImpulse = function (force, contactPoint) {
  73832. if (this._physicsEngine) {
  73833. this._physicsEngine.getPhysicsPlugin().applyImpulse(this, force, contactPoint);
  73834. }
  73835. return this;
  73836. };
  73837. /**
  73838. * A help function to create a joint.
  73839. */
  73840. PhysicsImpostor.prototype.createJoint = function (otherImpostor, jointType, jointData) {
  73841. var joint = new BABYLON.PhysicsJoint(jointType, jointData);
  73842. this.addJoint(otherImpostor, joint);
  73843. return this;
  73844. };
  73845. /**
  73846. * Add a joint to this impostor with a different impostor.
  73847. */
  73848. PhysicsImpostor.prototype.addJoint = function (otherImpostor, joint) {
  73849. this._joints.push({
  73850. otherImpostor: otherImpostor,
  73851. joint: joint
  73852. });
  73853. if (this._physicsEngine) {
  73854. this._physicsEngine.addJoint(this, otherImpostor, joint);
  73855. }
  73856. return this;
  73857. };
  73858. /**
  73859. * Will keep this body still, in a sleep mode.
  73860. */
  73861. PhysicsImpostor.prototype.sleep = function () {
  73862. if (this._physicsEngine) {
  73863. this._physicsEngine.getPhysicsPlugin().sleepBody(this);
  73864. }
  73865. return this;
  73866. };
  73867. /**
  73868. * Wake the body up.
  73869. */
  73870. PhysicsImpostor.prototype.wakeUp = function () {
  73871. if (this._physicsEngine) {
  73872. this._physicsEngine.getPhysicsPlugin().wakeUpBody(this);
  73873. }
  73874. return this;
  73875. };
  73876. PhysicsImpostor.prototype.clone = function (newObject) {
  73877. if (!newObject)
  73878. return null;
  73879. return new PhysicsImpostor(newObject, this.type, this._options, this._scene);
  73880. };
  73881. PhysicsImpostor.prototype.dispose = function () {
  73882. var _this = this;
  73883. //no dispose if no physics engine is available.
  73884. if (!this._physicsEngine) {
  73885. return;
  73886. }
  73887. this._joints.forEach(function (j) {
  73888. if (_this._physicsEngine) {
  73889. _this._physicsEngine.removeJoint(_this, j.otherImpostor, j.joint);
  73890. }
  73891. });
  73892. //dispose the physics body
  73893. this._physicsEngine.removeImpostor(this);
  73894. if (this.parent) {
  73895. this.parent.forceUpdate();
  73896. }
  73897. else {
  73898. /*this._object.getChildMeshes().forEach(function(mesh) {
  73899. if (mesh.physicsImpostor) {
  73900. if (disposeChildren) {
  73901. mesh.physicsImpostor.dispose();
  73902. mesh.physicsImpostor = null;
  73903. }
  73904. }
  73905. })*/
  73906. }
  73907. this._isDisposed = true;
  73908. };
  73909. PhysicsImpostor.prototype.setDeltaPosition = function (position) {
  73910. this._deltaPosition.copyFrom(position);
  73911. };
  73912. PhysicsImpostor.prototype.setDeltaRotation = function (rotation) {
  73913. if (!this._deltaRotation) {
  73914. this._deltaRotation = new BABYLON.Quaternion();
  73915. }
  73916. this._deltaRotation.copyFrom(rotation);
  73917. this._deltaRotationConjugated = this._deltaRotation.conjugate();
  73918. };
  73919. PhysicsImpostor.prototype.getBoxSizeToRef = function (result) {
  73920. if (this._physicsEngine) {
  73921. this._physicsEngine.getPhysicsPlugin().getBoxSizeToRef(this, result);
  73922. }
  73923. return this;
  73924. };
  73925. PhysicsImpostor.prototype.getRadius = function () {
  73926. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getRadius(this) : 0;
  73927. };
  73928. /**
  73929. * Sync a bone with this impostor
  73930. * @param bone The bone to sync to the impostor.
  73931. * @param boneMesh The mesh that the bone is influencing.
  73932. * @param jointPivot The pivot of the joint / bone in local space.
  73933. * @param distToJoint Optional distance from the impostor to the joint.
  73934. * @param adjustRotation Optional quaternion for adjusting the local rotation of the bone.
  73935. */
  73936. PhysicsImpostor.prototype.syncBoneWithImpostor = function (bone, boneMesh, jointPivot, distToJoint, adjustRotation) {
  73937. var tempVec = PhysicsImpostor._tmpVecs[0];
  73938. var mesh = this.object;
  73939. if (mesh.rotationQuaternion) {
  73940. if (adjustRotation) {
  73941. var tempQuat = PhysicsImpostor._tmpQuat;
  73942. mesh.rotationQuaternion.multiplyToRef(adjustRotation, tempQuat);
  73943. bone.setRotationQuaternion(tempQuat, BABYLON.Space.WORLD, boneMesh);
  73944. }
  73945. else {
  73946. bone.setRotationQuaternion(mesh.rotationQuaternion, BABYLON.Space.WORLD, boneMesh);
  73947. }
  73948. }
  73949. tempVec.x = 0;
  73950. tempVec.y = 0;
  73951. tempVec.z = 0;
  73952. if (jointPivot) {
  73953. tempVec.x = jointPivot.x;
  73954. tempVec.y = jointPivot.y;
  73955. tempVec.z = jointPivot.z;
  73956. bone.getDirectionToRef(tempVec, boneMesh, tempVec);
  73957. if (distToJoint === undefined || distToJoint === null) {
  73958. distToJoint = jointPivot.length();
  73959. }
  73960. tempVec.x *= distToJoint;
  73961. tempVec.y *= distToJoint;
  73962. tempVec.z *= distToJoint;
  73963. }
  73964. if (bone.getParent()) {
  73965. tempVec.addInPlace(mesh.getAbsolutePosition());
  73966. bone.setAbsolutePosition(tempVec, boneMesh);
  73967. }
  73968. else {
  73969. boneMesh.setAbsolutePosition(mesh.getAbsolutePosition());
  73970. boneMesh.position.x -= tempVec.x;
  73971. boneMesh.position.y -= tempVec.y;
  73972. boneMesh.position.z -= tempVec.z;
  73973. }
  73974. };
  73975. /**
  73976. * Sync impostor to a bone
  73977. * @param bone The bone that the impostor will be synced to.
  73978. * @param boneMesh The mesh that the bone is influencing.
  73979. * @param jointPivot The pivot of the joint / bone in local space.
  73980. * @param distToJoint Optional distance from the impostor to the joint.
  73981. * @param adjustRotation Optional quaternion for adjusting the local rotation of the bone.
  73982. * @param boneAxis Optional vector3 axis the bone is aligned with
  73983. */
  73984. PhysicsImpostor.prototype.syncImpostorWithBone = function (bone, boneMesh, jointPivot, distToJoint, adjustRotation, boneAxis) {
  73985. var mesh = this.object;
  73986. if (mesh.rotationQuaternion) {
  73987. if (adjustRotation) {
  73988. var tempQuat = PhysicsImpostor._tmpQuat;
  73989. bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, boneMesh, tempQuat);
  73990. tempQuat.multiplyToRef(adjustRotation, mesh.rotationQuaternion);
  73991. }
  73992. else {
  73993. bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, boneMesh, mesh.rotationQuaternion);
  73994. }
  73995. }
  73996. var pos = PhysicsImpostor._tmpVecs[0];
  73997. var boneDir = PhysicsImpostor._tmpVecs[1];
  73998. if (!boneAxis) {
  73999. boneAxis = PhysicsImpostor._tmpVecs[2];
  74000. boneAxis.x = 0;
  74001. boneAxis.y = 1;
  74002. boneAxis.z = 0;
  74003. }
  74004. bone.getDirectionToRef(boneAxis, boneMesh, boneDir);
  74005. bone.getAbsolutePositionToRef(boneMesh, pos);
  74006. if ((distToJoint === undefined || distToJoint === null) && jointPivot) {
  74007. distToJoint = jointPivot.length();
  74008. }
  74009. if (distToJoint !== undefined && distToJoint !== null) {
  74010. pos.x += boneDir.x * distToJoint;
  74011. pos.y += boneDir.y * distToJoint;
  74012. pos.z += boneDir.z * distToJoint;
  74013. }
  74014. mesh.setAbsolutePosition(pos);
  74015. };
  74016. PhysicsImpostor.DEFAULT_OBJECT_SIZE = new BABYLON.Vector3(1, 1, 1);
  74017. PhysicsImpostor.IDENTITY_QUATERNION = BABYLON.Quaternion.Identity();
  74018. PhysicsImpostor._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  74019. PhysicsImpostor._tmpQuat = BABYLON.Quaternion.Identity();
  74020. //Impostor types
  74021. PhysicsImpostor.NoImpostor = 0;
  74022. PhysicsImpostor.SphereImpostor = 1;
  74023. PhysicsImpostor.BoxImpostor = 2;
  74024. PhysicsImpostor.PlaneImpostor = 3;
  74025. PhysicsImpostor.MeshImpostor = 4;
  74026. PhysicsImpostor.CylinderImpostor = 7;
  74027. PhysicsImpostor.ParticleImpostor = 8;
  74028. PhysicsImpostor.HeightmapImpostor = 9;
  74029. return PhysicsImpostor;
  74030. }());
  74031. BABYLON.PhysicsImpostor = PhysicsImpostor;
  74032. })(BABYLON || (BABYLON = {}));
  74033. //# sourceMappingURL=babylon.physicsImpostor.js.map
  74034. var BABYLON;
  74035. (function (BABYLON) {
  74036. var PhysicsEngine = /** @class */ (function () {
  74037. function PhysicsEngine(gravity, _physicsPlugin) {
  74038. if (_physicsPlugin === void 0) { _physicsPlugin = new BABYLON.CannonJSPlugin(); }
  74039. this._physicsPlugin = _physicsPlugin;
  74040. //new methods and parameters
  74041. this._impostors = [];
  74042. this._joints = [];
  74043. if (!this._physicsPlugin.isSupported()) {
  74044. throw new Error("Physics Engine " + this._physicsPlugin.name + " cannot be found. "
  74045. + "Please make sure it is included.");
  74046. }
  74047. gravity = gravity || new BABYLON.Vector3(0, -9.807, 0);
  74048. this.setGravity(gravity);
  74049. this.setTimeStep();
  74050. }
  74051. PhysicsEngine.prototype.setGravity = function (gravity) {
  74052. this.gravity = gravity;
  74053. this._physicsPlugin.setGravity(this.gravity);
  74054. };
  74055. /**
  74056. * Set the time step of the physics engine.
  74057. * default is 1/60.
  74058. * To slow it down, enter 1/600 for example.
  74059. * To speed it up, 1/30
  74060. * @param {number} newTimeStep the new timestep to apply to this world.
  74061. */
  74062. PhysicsEngine.prototype.setTimeStep = function (newTimeStep) {
  74063. if (newTimeStep === void 0) { newTimeStep = 1 / 60; }
  74064. this._physicsPlugin.setTimeStep(newTimeStep);
  74065. };
  74066. /**
  74067. * Get the time step of the physics engine.
  74068. */
  74069. PhysicsEngine.prototype.getTimeStep = function () {
  74070. return this._physicsPlugin.getTimeStep();
  74071. };
  74072. PhysicsEngine.prototype.dispose = function () {
  74073. this._impostors.forEach(function (impostor) {
  74074. impostor.dispose();
  74075. });
  74076. this._physicsPlugin.dispose();
  74077. };
  74078. PhysicsEngine.prototype.getPhysicsPluginName = function () {
  74079. return this._physicsPlugin.name;
  74080. };
  74081. /**
  74082. * Adding a new impostor for the impostor tracking.
  74083. * This will be done by the impostor itself.
  74084. * @param {PhysicsImpostor} impostor the impostor to add
  74085. */
  74086. PhysicsEngine.prototype.addImpostor = function (impostor) {
  74087. impostor.uniqueId = this._impostors.push(impostor);
  74088. //if no parent, generate the body
  74089. if (!impostor.parent) {
  74090. this._physicsPlugin.generatePhysicsBody(impostor);
  74091. }
  74092. };
  74093. /**
  74094. * Remove an impostor from the engine.
  74095. * This impostor and its mesh will not longer be updated by the physics engine.
  74096. * @param {PhysicsImpostor} impostor the impostor to remove
  74097. */
  74098. PhysicsEngine.prototype.removeImpostor = function (impostor) {
  74099. var index = this._impostors.indexOf(impostor);
  74100. if (index > -1) {
  74101. var removed = this._impostors.splice(index, 1);
  74102. //Is it needed?
  74103. if (removed.length) {
  74104. //this will also remove it from the world.
  74105. removed[0].physicsBody = null;
  74106. }
  74107. }
  74108. };
  74109. /**
  74110. * Add a joint to the physics engine
  74111. * @param {PhysicsImpostor} mainImpostor the main impostor to which the joint is added.
  74112. * @param {PhysicsImpostor} connectedImpostor the impostor that is connected to the main impostor using this joint
  74113. * @param {PhysicsJoint} the joint that will connect both impostors.
  74114. */
  74115. PhysicsEngine.prototype.addJoint = function (mainImpostor, connectedImpostor, joint) {
  74116. var impostorJoint = {
  74117. mainImpostor: mainImpostor,
  74118. connectedImpostor: connectedImpostor,
  74119. joint: joint
  74120. };
  74121. joint.physicsPlugin = this._physicsPlugin;
  74122. this._joints.push(impostorJoint);
  74123. this._physicsPlugin.generateJoint(impostorJoint);
  74124. };
  74125. PhysicsEngine.prototype.removeJoint = function (mainImpostor, connectedImpostor, joint) {
  74126. var matchingJoints = this._joints.filter(function (impostorJoint) {
  74127. return (impostorJoint.connectedImpostor === connectedImpostor
  74128. && impostorJoint.joint === joint
  74129. && impostorJoint.mainImpostor === mainImpostor);
  74130. });
  74131. if (matchingJoints.length) {
  74132. this._physicsPlugin.removeJoint(matchingJoints[0]);
  74133. //TODO remove it from the list as well
  74134. }
  74135. };
  74136. /**
  74137. * Called by the scene. no need to call it.
  74138. */
  74139. PhysicsEngine.prototype._step = function (delta) {
  74140. var _this = this;
  74141. //check if any mesh has no body / requires an update
  74142. this._impostors.forEach(function (impostor) {
  74143. if (impostor.isBodyInitRequired()) {
  74144. _this._physicsPlugin.generatePhysicsBody(impostor);
  74145. }
  74146. });
  74147. if (delta > 0.1) {
  74148. delta = 0.1;
  74149. }
  74150. else if (delta <= 0) {
  74151. delta = 1.0 / 60.0;
  74152. }
  74153. this._physicsPlugin.executeStep(delta, this._impostors);
  74154. };
  74155. PhysicsEngine.prototype.getPhysicsPlugin = function () {
  74156. return this._physicsPlugin;
  74157. };
  74158. PhysicsEngine.prototype.getImpostors = function () {
  74159. return this._impostors;
  74160. };
  74161. PhysicsEngine.prototype.getImpostorForPhysicsObject = function (object) {
  74162. for (var i = 0; i < this._impostors.length; ++i) {
  74163. if (this._impostors[i].object === object) {
  74164. return this._impostors[i];
  74165. }
  74166. }
  74167. return null;
  74168. };
  74169. PhysicsEngine.prototype.getImpostorWithPhysicsBody = function (body) {
  74170. for (var i = 0; i < this._impostors.length; ++i) {
  74171. if (this._impostors[i].physicsBody === body) {
  74172. return this._impostors[i];
  74173. }
  74174. }
  74175. return null;
  74176. };
  74177. // Statics
  74178. PhysicsEngine.Epsilon = 0.001;
  74179. return PhysicsEngine;
  74180. }());
  74181. BABYLON.PhysicsEngine = PhysicsEngine;
  74182. })(BABYLON || (BABYLON = {}));
  74183. //# sourceMappingURL=babylon.physicsEngine.js.map
  74184. var BABYLON;
  74185. (function (BABYLON) {
  74186. var PhysicsHelper = /** @class */ (function () {
  74187. function PhysicsHelper(scene) {
  74188. this._scene = scene;
  74189. this._physicsEngine = this._scene.getPhysicsEngine();
  74190. if (!this._physicsEngine) {
  74191. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you can use the methods.');
  74192. }
  74193. }
  74194. /**
  74195. * @param {Vector3} origin the origin of the explosion
  74196. * @param {number} radius the explosion radius
  74197. * @param {number} strength the explosion strength
  74198. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear. Defaults to Constant
  74199. */
  74200. PhysicsHelper.prototype.applyRadialExplosionImpulse = function (origin, radius, strength, falloff) {
  74201. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  74202. if (!this._physicsEngine) {
  74203. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call this method.');
  74204. return null;
  74205. }
  74206. var impostors = this._physicsEngine.getImpostors();
  74207. if (impostors.length === 0) {
  74208. return null;
  74209. }
  74210. var event = new PhysicsRadialExplosionEvent(this._scene);
  74211. impostors.forEach(function (impostor) {
  74212. var impostorForceAndContactPoint = event.getImpostorForceAndContactPoint(impostor, origin, radius, strength, falloff);
  74213. if (!impostorForceAndContactPoint) {
  74214. return;
  74215. }
  74216. impostor.applyImpulse(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  74217. });
  74218. event.dispose(false);
  74219. return event;
  74220. };
  74221. /**
  74222. * @param {Vector3} origin the origin of the explosion
  74223. * @param {number} radius the explosion radius
  74224. * @param {number} strength the explosion strength
  74225. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear. Defaults to Constant
  74226. */
  74227. PhysicsHelper.prototype.applyRadialExplosionForce = function (origin, radius, strength, falloff) {
  74228. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  74229. if (!this._physicsEngine) {
  74230. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  74231. return null;
  74232. }
  74233. var impostors = this._physicsEngine.getImpostors();
  74234. if (impostors.length === 0) {
  74235. return null;
  74236. }
  74237. var event = new PhysicsRadialExplosionEvent(this._scene);
  74238. impostors.forEach(function (impostor) {
  74239. var impostorForceAndContactPoint = event.getImpostorForceAndContactPoint(impostor, origin, radius, strength, falloff);
  74240. if (!impostorForceAndContactPoint) {
  74241. return;
  74242. }
  74243. impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  74244. });
  74245. event.dispose(false);
  74246. return event;
  74247. };
  74248. /**
  74249. * @param {Vector3} origin the origin of the explosion
  74250. * @param {number} radius the explosion radius
  74251. * @param {number} strength the explosion strength
  74252. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear. Defaults to Constant
  74253. */
  74254. PhysicsHelper.prototype.gravitationalField = function (origin, radius, strength, falloff) {
  74255. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  74256. if (!this._physicsEngine) {
  74257. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  74258. return null;
  74259. }
  74260. var impostors = this._physicsEngine.getImpostors();
  74261. if (impostors.length === 0) {
  74262. return null;
  74263. }
  74264. var event = new PhysicsGravitationalFieldEvent(this, this._scene, origin, radius, strength, falloff);
  74265. event.dispose(false);
  74266. return event;
  74267. };
  74268. /**
  74269. * @param {Vector3} origin the origin of the updraft
  74270. * @param {number} radius the radius of the updraft
  74271. * @param {number} strength the strength of the updraft
  74272. * @param {number} height the height of the updraft
  74273. * @param {PhysicsUpdraftMode} updraftMode possible options: Center & Perpendicular. Defaults to Center
  74274. */
  74275. PhysicsHelper.prototype.updraft = function (origin, radius, strength, height, updraftMode) {
  74276. if (updraftMode === void 0) { updraftMode = PhysicsUpdraftMode.Center; }
  74277. if (!this._physicsEngine) {
  74278. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  74279. return null;
  74280. }
  74281. if (this._physicsEngine.getImpostors().length === 0) {
  74282. return null;
  74283. }
  74284. var event = new PhysicsUpdraftEvent(this._scene, origin, radius, strength, height, updraftMode);
  74285. event.dispose(false);
  74286. return event;
  74287. };
  74288. /**
  74289. * @param {Vector3} origin the of the vortex
  74290. * @param {number} radius the radius of the vortex
  74291. * @param {number} strength the strength of the vortex
  74292. * @param {number} height the height of the vortex
  74293. */
  74294. PhysicsHelper.prototype.vortex = function (origin, radius, strength, height) {
  74295. if (!this._physicsEngine) {
  74296. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  74297. return null;
  74298. }
  74299. if (this._physicsEngine.getImpostors().length === 0) {
  74300. return null;
  74301. }
  74302. var event = new PhysicsVortexEvent(this._scene, origin, radius, strength, height);
  74303. event.dispose(false);
  74304. return event;
  74305. };
  74306. return PhysicsHelper;
  74307. }());
  74308. BABYLON.PhysicsHelper = PhysicsHelper;
  74309. /***** Radial explosion *****/
  74310. var PhysicsRadialExplosionEvent = /** @class */ (function () {
  74311. function PhysicsRadialExplosionEvent(scene) {
  74312. this._sphereOptions = { segments: 32, diameter: 1 }; // TODO: make configurable
  74313. this._rays = [];
  74314. this._dataFetched = false; // check if the data has been fetched. If not, do cleanup
  74315. this._scene = scene;
  74316. }
  74317. /**
  74318. * Returns the data related to the radial explosion event (sphere & rays).
  74319. * @returns {PhysicsRadialExplosionEventData}
  74320. */
  74321. PhysicsRadialExplosionEvent.prototype.getData = function () {
  74322. this._dataFetched = true;
  74323. return {
  74324. sphere: this._sphere,
  74325. rays: this._rays,
  74326. };
  74327. };
  74328. /**
  74329. * Returns the force and contact point of the impostor or false, if the impostor is not affected by the force/impulse.
  74330. * @param impostor
  74331. * @param {Vector3} origin the origin of the explosion
  74332. * @param {number} radius the explosion radius
  74333. * @param {number} strength the explosion strength
  74334. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear
  74335. * @returns {Nullable<PhysicsForceAndContactPoint>}
  74336. */
  74337. PhysicsRadialExplosionEvent.prototype.getImpostorForceAndContactPoint = function (impostor, origin, radius, strength, falloff) {
  74338. if (impostor.mass === 0) {
  74339. return null;
  74340. }
  74341. if (!this._intersectsWithSphere(impostor, origin, radius)) {
  74342. return null;
  74343. }
  74344. if (impostor.object.getClassName() !== 'Mesh') {
  74345. return null;
  74346. }
  74347. var impostorObject = impostor.object;
  74348. var impostorObjectCenter = impostor.getObjectCenter();
  74349. var direction = impostorObjectCenter.subtract(origin);
  74350. var ray = new BABYLON.Ray(origin, direction, radius);
  74351. this._rays.push(ray);
  74352. var hit = ray.intersectsMesh(impostorObject);
  74353. var contactPoint = hit.pickedPoint;
  74354. if (!contactPoint) {
  74355. return null;
  74356. }
  74357. var distanceFromOrigin = BABYLON.Vector3.Distance(origin, contactPoint);
  74358. if (distanceFromOrigin > radius) {
  74359. return null;
  74360. }
  74361. var multiplier = falloff === PhysicsRadialImpulseFalloff.Constant
  74362. ? strength
  74363. : strength * (1 - (distanceFromOrigin / radius));
  74364. var force = direction.multiplyByFloats(multiplier, multiplier, multiplier);
  74365. return { force: force, contactPoint: contactPoint };
  74366. };
  74367. /**
  74368. * Disposes the sphere.
  74369. * @param {bolean} force
  74370. */
  74371. PhysicsRadialExplosionEvent.prototype.dispose = function (force) {
  74372. var _this = this;
  74373. if (force === void 0) { force = true; }
  74374. if (force) {
  74375. this._sphere.dispose();
  74376. }
  74377. else {
  74378. setTimeout(function () {
  74379. if (!_this._dataFetched) {
  74380. _this._sphere.dispose();
  74381. }
  74382. }, 0);
  74383. }
  74384. };
  74385. /*** Helpers ***/
  74386. PhysicsRadialExplosionEvent.prototype._prepareSphere = function () {
  74387. if (!this._sphere) {
  74388. this._sphere = BABYLON.MeshBuilder.CreateSphere("radialExplosionEventSphere", this._sphereOptions, this._scene);
  74389. this._sphere.isVisible = false;
  74390. }
  74391. };
  74392. PhysicsRadialExplosionEvent.prototype._intersectsWithSphere = function (impostor, origin, radius) {
  74393. var impostorObject = impostor.object;
  74394. this._prepareSphere();
  74395. this._sphere.position = origin;
  74396. this._sphere.scaling = new BABYLON.Vector3(radius * 2, radius * 2, radius * 2);
  74397. this._sphere._updateBoundingInfo();
  74398. this._sphere.computeWorldMatrix(true);
  74399. return this._sphere.intersectsMesh(impostorObject, true);
  74400. };
  74401. return PhysicsRadialExplosionEvent;
  74402. }());
  74403. BABYLON.PhysicsRadialExplosionEvent = PhysicsRadialExplosionEvent;
  74404. /***** Gravitational Field *****/
  74405. var PhysicsGravitationalFieldEvent = /** @class */ (function () {
  74406. function PhysicsGravitationalFieldEvent(physicsHelper, scene, origin, radius, strength, falloff) {
  74407. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  74408. this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup
  74409. this._physicsHelper = physicsHelper;
  74410. this._scene = scene;
  74411. this._origin = origin;
  74412. this._radius = radius;
  74413. this._strength = strength;
  74414. this._falloff = falloff;
  74415. this._tickCallback = this._tick.bind(this);
  74416. }
  74417. /**
  74418. * Returns the data related to the gravitational field event (sphere).
  74419. * @returns {PhysicsGravitationalFieldEventData}
  74420. */
  74421. PhysicsGravitationalFieldEvent.prototype.getData = function () {
  74422. this._dataFetched = true;
  74423. return {
  74424. sphere: this._sphere,
  74425. };
  74426. };
  74427. /**
  74428. * Enables the gravitational field.
  74429. */
  74430. PhysicsGravitationalFieldEvent.prototype.enable = function () {
  74431. this._tickCallback.call(this);
  74432. this._scene.registerBeforeRender(this._tickCallback);
  74433. };
  74434. /**
  74435. * Disables the gravitational field.
  74436. */
  74437. PhysicsGravitationalFieldEvent.prototype.disable = function () {
  74438. this._scene.unregisterBeforeRender(this._tickCallback);
  74439. };
  74440. /**
  74441. * Disposes the sphere.
  74442. * @param {bolean} force
  74443. */
  74444. PhysicsGravitationalFieldEvent.prototype.dispose = function (force) {
  74445. var _this = this;
  74446. if (force === void 0) { force = true; }
  74447. if (force) {
  74448. this._sphere.dispose();
  74449. }
  74450. else {
  74451. setTimeout(function () {
  74452. if (!_this._dataFetched) {
  74453. _this._sphere.dispose();
  74454. }
  74455. }, 0);
  74456. }
  74457. };
  74458. PhysicsGravitationalFieldEvent.prototype._tick = function () {
  74459. // Since the params won't change, we fetch the event only once
  74460. if (this._sphere) {
  74461. this._physicsHelper.applyRadialExplosionForce(this._origin, this._radius, this._strength * -1, this._falloff);
  74462. }
  74463. else {
  74464. var radialExplosionEvent = this._physicsHelper.applyRadialExplosionForce(this._origin, this._radius, this._strength * -1, this._falloff);
  74465. if (radialExplosionEvent) {
  74466. this._sphere = radialExplosionEvent.getData().sphere.clone('radialExplosionEventSphereClone');
  74467. }
  74468. }
  74469. };
  74470. return PhysicsGravitationalFieldEvent;
  74471. }());
  74472. BABYLON.PhysicsGravitationalFieldEvent = PhysicsGravitationalFieldEvent;
  74473. /***** Updraft *****/
  74474. var PhysicsUpdraftEvent = /** @class */ (function () {
  74475. function PhysicsUpdraftEvent(_scene, _origin, _radius, _strength, _height, _updraftMode) {
  74476. this._scene = _scene;
  74477. this._origin = _origin;
  74478. this._radius = _radius;
  74479. this._strength = _strength;
  74480. this._height = _height;
  74481. this._updraftMode = _updraftMode;
  74482. this._originTop = BABYLON.Vector3.Zero(); // the most upper part of the cylinder
  74483. this._originDirection = BABYLON.Vector3.Zero(); // used if the updraftMode is perpendicular
  74484. this._cylinderPosition = BABYLON.Vector3.Zero(); // to keep the cylinders position, because normally the origin is in the center and not on the bottom
  74485. this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup
  74486. this._physicsEngine = this._scene.getPhysicsEngine();
  74487. this._origin.addToRef(new BABYLON.Vector3(0, this._height / 2, 0), this._cylinderPosition);
  74488. this._origin.addToRef(new BABYLON.Vector3(0, this._height, 0), this._originTop);
  74489. if (this._updraftMode === PhysicsUpdraftMode.Perpendicular) {
  74490. this._originDirection = this._origin.subtract(this._originTop).normalize();
  74491. }
  74492. this._tickCallback = this._tick.bind(this);
  74493. }
  74494. /**
  74495. * Returns the data related to the updraft event (cylinder).
  74496. * @returns {PhysicsUpdraftEventData}
  74497. */
  74498. PhysicsUpdraftEvent.prototype.getData = function () {
  74499. this._dataFetched = true;
  74500. return {
  74501. cylinder: this._cylinder,
  74502. };
  74503. };
  74504. /**
  74505. * Enables the updraft.
  74506. */
  74507. PhysicsUpdraftEvent.prototype.enable = function () {
  74508. this._tickCallback.call(this);
  74509. this._scene.registerBeforeRender(this._tickCallback);
  74510. };
  74511. /**
  74512. * Disables the cortex.
  74513. */
  74514. PhysicsUpdraftEvent.prototype.disable = function () {
  74515. this._scene.unregisterBeforeRender(this._tickCallback);
  74516. };
  74517. /**
  74518. * Disposes the sphere.
  74519. * @param {bolean} force
  74520. */
  74521. PhysicsUpdraftEvent.prototype.dispose = function (force) {
  74522. var _this = this;
  74523. if (force === void 0) { force = true; }
  74524. if (force) {
  74525. this._cylinder.dispose();
  74526. }
  74527. else {
  74528. setTimeout(function () {
  74529. if (!_this._dataFetched) {
  74530. _this._cylinder.dispose();
  74531. }
  74532. }, 0);
  74533. }
  74534. };
  74535. PhysicsUpdraftEvent.prototype.getImpostorForceAndContactPoint = function (impostor) {
  74536. if (impostor.mass === 0) {
  74537. return null;
  74538. }
  74539. if (!this._intersectsWithCylinder(impostor)) {
  74540. return null;
  74541. }
  74542. var impostorObjectCenter = impostor.getObjectCenter();
  74543. if (this._updraftMode === PhysicsUpdraftMode.Perpendicular) {
  74544. var direction = this._originDirection;
  74545. }
  74546. else {
  74547. var direction = impostorObjectCenter.subtract(this._originTop);
  74548. }
  74549. var multiplier = this._strength * -1;
  74550. var force = direction.multiplyByFloats(multiplier, multiplier, multiplier);
  74551. return { force: force, contactPoint: impostorObjectCenter };
  74552. };
  74553. PhysicsUpdraftEvent.prototype._tick = function () {
  74554. var _this = this;
  74555. this._physicsEngine.getImpostors().forEach(function (impostor) {
  74556. var impostorForceAndContactPoint = _this.getImpostorForceAndContactPoint(impostor);
  74557. if (!impostorForceAndContactPoint) {
  74558. return;
  74559. }
  74560. impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  74561. });
  74562. };
  74563. /*** Helpers ***/
  74564. PhysicsUpdraftEvent.prototype._prepareCylinder = function () {
  74565. if (!this._cylinder) {
  74566. this._cylinder = BABYLON.MeshBuilder.CreateCylinder("updraftEventCylinder", {
  74567. height: this._height,
  74568. diameter: this._radius * 2,
  74569. }, this._scene);
  74570. this._cylinder.isVisible = false;
  74571. }
  74572. };
  74573. PhysicsUpdraftEvent.prototype._intersectsWithCylinder = function (impostor) {
  74574. var impostorObject = impostor.object;
  74575. this._prepareCylinder();
  74576. this._cylinder.position = this._cylinderPosition;
  74577. return this._cylinder.intersectsMesh(impostorObject, true);
  74578. };
  74579. return PhysicsUpdraftEvent;
  74580. }());
  74581. BABYLON.PhysicsUpdraftEvent = PhysicsUpdraftEvent;
  74582. /***** Vortex *****/
  74583. var PhysicsVortexEvent = /** @class */ (function () {
  74584. function PhysicsVortexEvent(_scene, _origin, _radius, _strength, _height) {
  74585. this._scene = _scene;
  74586. this._origin = _origin;
  74587. this._radius = _radius;
  74588. this._strength = _strength;
  74589. this._height = _height;
  74590. this._originTop = BABYLON.Vector3.Zero(); // the most upper part of the cylinder
  74591. this._centripetalForceThreshold = 0.7; // at which distance, relative to the radius the centripetal forces should kick in
  74592. this._updraftMultiplier = 0.02;
  74593. this._cylinderPosition = BABYLON.Vector3.Zero(); // to keep the cylinders position, because normally the origin is in the center and not on the bottom
  74594. this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup
  74595. this._physicsEngine = this._scene.getPhysicsEngine();
  74596. this._origin.addToRef(new BABYLON.Vector3(0, this._height / 2, 0), this._cylinderPosition);
  74597. this._origin.addToRef(new BABYLON.Vector3(0, this._height, 0), this._originTop);
  74598. this._tickCallback = this._tick.bind(this);
  74599. }
  74600. /**
  74601. * Returns the data related to the vortex event (cylinder).
  74602. * @returns {PhysicsVortexEventData}
  74603. */
  74604. PhysicsVortexEvent.prototype.getData = function () {
  74605. this._dataFetched = true;
  74606. return {
  74607. cylinder: this._cylinder,
  74608. };
  74609. };
  74610. /**
  74611. * Enables the vortex.
  74612. */
  74613. PhysicsVortexEvent.prototype.enable = function () {
  74614. this._tickCallback.call(this);
  74615. this._scene.registerBeforeRender(this._tickCallback);
  74616. };
  74617. /**
  74618. * Disables the cortex.
  74619. */
  74620. PhysicsVortexEvent.prototype.disable = function () {
  74621. this._scene.unregisterBeforeRender(this._tickCallback);
  74622. };
  74623. /**
  74624. * Disposes the sphere.
  74625. * @param {bolean} force
  74626. */
  74627. PhysicsVortexEvent.prototype.dispose = function (force) {
  74628. var _this = this;
  74629. if (force === void 0) { force = true; }
  74630. if (force) {
  74631. this._cylinder.dispose();
  74632. }
  74633. else {
  74634. setTimeout(function () {
  74635. if (!_this._dataFetched) {
  74636. _this._cylinder.dispose();
  74637. }
  74638. }, 0);
  74639. }
  74640. };
  74641. PhysicsVortexEvent.prototype.getImpostorForceAndContactPoint = function (impostor) {
  74642. if (impostor.mass === 0) {
  74643. return null;
  74644. }
  74645. if (!this._intersectsWithCylinder(impostor)) {
  74646. return null;
  74647. }
  74648. if (impostor.object.getClassName() !== 'Mesh') {
  74649. return null;
  74650. }
  74651. var impostorObject = impostor.object;
  74652. var impostorObjectCenter = impostor.getObjectCenter();
  74653. 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)
  74654. var originToImpostorDirection = impostorObjectCenter.subtract(originOnPlane);
  74655. var ray = new BABYLON.Ray(originOnPlane, originToImpostorDirection, this._radius);
  74656. var hit = ray.intersectsMesh(impostorObject);
  74657. var contactPoint = hit.pickedPoint;
  74658. if (!contactPoint) {
  74659. return null;
  74660. }
  74661. var absoluteDistanceFromOrigin = hit.distance / this._radius;
  74662. var perpendicularDirection = BABYLON.Vector3.Cross(originOnPlane, impostorObjectCenter).normalize();
  74663. var directionToOrigin = contactPoint.normalize();
  74664. if (absoluteDistanceFromOrigin > this._centripetalForceThreshold) {
  74665. directionToOrigin = directionToOrigin.negate();
  74666. }
  74667. // TODO: find a more physically based solution
  74668. if (absoluteDistanceFromOrigin > this._centripetalForceThreshold) {
  74669. var forceX = directionToOrigin.x * this._strength / 8;
  74670. var forceY = directionToOrigin.y * this._updraftMultiplier;
  74671. var forceZ = directionToOrigin.z * this._strength / 8;
  74672. }
  74673. else {
  74674. var forceX = (perpendicularDirection.x + directionToOrigin.x) / 2;
  74675. var forceY = this._originTop.y * this._updraftMultiplier;
  74676. var forceZ = (perpendicularDirection.z + directionToOrigin.z) / 2;
  74677. }
  74678. var force = new BABYLON.Vector3(forceX, forceY, forceZ);
  74679. force = force.multiplyByFloats(this._strength, this._strength, this._strength);
  74680. return { force: force, contactPoint: impostorObjectCenter };
  74681. };
  74682. PhysicsVortexEvent.prototype._tick = function () {
  74683. var _this = this;
  74684. this._physicsEngine.getImpostors().forEach(function (impostor) {
  74685. var impostorForceAndContactPoint = _this.getImpostorForceAndContactPoint(impostor);
  74686. if (!impostorForceAndContactPoint) {
  74687. return;
  74688. }
  74689. impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  74690. });
  74691. };
  74692. /*** Helpers ***/
  74693. PhysicsVortexEvent.prototype._prepareCylinder = function () {
  74694. if (!this._cylinder) {
  74695. this._cylinder = BABYLON.MeshBuilder.CreateCylinder("vortexEventCylinder", {
  74696. height: this._height,
  74697. diameter: this._radius * 2,
  74698. }, this._scene);
  74699. this._cylinder.isVisible = false;
  74700. }
  74701. };
  74702. PhysicsVortexEvent.prototype._intersectsWithCylinder = function (impostor) {
  74703. var impostorObject = impostor.object;
  74704. this._prepareCylinder();
  74705. this._cylinder.position = this._cylinderPosition;
  74706. return this._cylinder.intersectsMesh(impostorObject, true);
  74707. };
  74708. return PhysicsVortexEvent;
  74709. }());
  74710. BABYLON.PhysicsVortexEvent = PhysicsVortexEvent;
  74711. /***** Enums *****/
  74712. /**
  74713. * The strenght of the force in correspondence to the distance of the affected object
  74714. */
  74715. var PhysicsRadialImpulseFalloff;
  74716. (function (PhysicsRadialImpulseFalloff) {
  74717. PhysicsRadialImpulseFalloff[PhysicsRadialImpulseFalloff["Constant"] = 0] = "Constant";
  74718. PhysicsRadialImpulseFalloff[PhysicsRadialImpulseFalloff["Linear"] = 1] = "Linear"; // impulse gets weaker if it's further from the origin
  74719. })(PhysicsRadialImpulseFalloff = BABYLON.PhysicsRadialImpulseFalloff || (BABYLON.PhysicsRadialImpulseFalloff = {}));
  74720. /**
  74721. * The strenght of the force in correspondence to the distance of the affected object
  74722. */
  74723. var PhysicsUpdraftMode;
  74724. (function (PhysicsUpdraftMode) {
  74725. PhysicsUpdraftMode[PhysicsUpdraftMode["Center"] = 0] = "Center";
  74726. PhysicsUpdraftMode[PhysicsUpdraftMode["Perpendicular"] = 1] = "Perpendicular"; // once a impostor is inside the cylinder, it will shoot out perpendicular from the ground of the cylinder
  74727. })(PhysicsUpdraftMode = BABYLON.PhysicsUpdraftMode || (BABYLON.PhysicsUpdraftMode = {}));
  74728. })(BABYLON || (BABYLON = {}));
  74729. //# sourceMappingURL=babylon.physicsHelper.js.map
  74730. var BABYLON;
  74731. (function (BABYLON) {
  74732. var CannonJSPlugin = /** @class */ (function () {
  74733. function CannonJSPlugin(_useDeltaForWorldStep, iterations) {
  74734. if (_useDeltaForWorldStep === void 0) { _useDeltaForWorldStep = true; }
  74735. if (iterations === void 0) { iterations = 10; }
  74736. this._useDeltaForWorldStep = _useDeltaForWorldStep;
  74737. this.name = "CannonJSPlugin";
  74738. this._physicsMaterials = new Array();
  74739. this._fixedTimeStep = 1 / 60;
  74740. //See https://github.com/schteppe/CANNON.js/blob/gh-pages/demos/collisionFilter.html
  74741. this.BJSCANNON = typeof CANNON !== 'undefined' ? CANNON : (typeof require !== 'undefined' ? require('cannon') : undefined);
  74742. this._minus90X = new BABYLON.Quaternion(-0.7071067811865475, 0, 0, 0.7071067811865475);
  74743. this._plus90X = new BABYLON.Quaternion(0.7071067811865475, 0, 0, 0.7071067811865475);
  74744. this._tmpPosition = BABYLON.Vector3.Zero();
  74745. this._tmpDeltaPosition = BABYLON.Vector3.Zero();
  74746. this._tmpUnityRotation = new BABYLON.Quaternion();
  74747. if (!this.isSupported()) {
  74748. BABYLON.Tools.Error("CannonJS is not available. Please make sure you included the js file.");
  74749. return;
  74750. }
  74751. this._extendNamespace();
  74752. this.world = new this.BJSCANNON.World();
  74753. this.world.broadphase = new this.BJSCANNON.NaiveBroadphase();
  74754. this.world.solver.iterations = iterations;
  74755. }
  74756. CannonJSPlugin.prototype.setGravity = function (gravity) {
  74757. this.world.gravity.copy(gravity);
  74758. };
  74759. CannonJSPlugin.prototype.setTimeStep = function (timeStep) {
  74760. this._fixedTimeStep = timeStep;
  74761. };
  74762. CannonJSPlugin.prototype.getTimeStep = function () {
  74763. return this._fixedTimeStep;
  74764. };
  74765. CannonJSPlugin.prototype.executeStep = function (delta, impostors) {
  74766. this.world.step(this._fixedTimeStep, this._useDeltaForWorldStep ? delta : 0, 3);
  74767. };
  74768. CannonJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  74769. var worldPoint = new this.BJSCANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  74770. var impulse = new this.BJSCANNON.Vec3(force.x, force.y, force.z);
  74771. impostor.physicsBody.applyImpulse(impulse, worldPoint);
  74772. };
  74773. CannonJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  74774. var worldPoint = new this.BJSCANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  74775. var impulse = new this.BJSCANNON.Vec3(force.x, force.y, force.z);
  74776. impostor.physicsBody.applyForce(impulse, worldPoint);
  74777. };
  74778. CannonJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  74779. //parent-child relationship. Does this impostor has a parent impostor?
  74780. if (impostor.parent) {
  74781. if (impostor.physicsBody) {
  74782. this.removePhysicsBody(impostor);
  74783. //TODO is that needed?
  74784. impostor.forceUpdate();
  74785. }
  74786. return;
  74787. }
  74788. //should a new body be created for this impostor?
  74789. if (impostor.isBodyInitRequired()) {
  74790. var shape = this._createShape(impostor);
  74791. //unregister events, if body is being changed
  74792. var oldBody = impostor.physicsBody;
  74793. if (oldBody) {
  74794. this.removePhysicsBody(impostor);
  74795. }
  74796. //create the body and material
  74797. var material = this._addMaterial("mat-" + impostor.uniqueId, impostor.getParam("friction"), impostor.getParam("restitution"));
  74798. var bodyCreationObject = {
  74799. mass: impostor.getParam("mass"),
  74800. material: material
  74801. };
  74802. // A simple extend, in case native options were used.
  74803. var nativeOptions = impostor.getParam("nativeOptions");
  74804. for (var key in nativeOptions) {
  74805. if (nativeOptions.hasOwnProperty(key)) {
  74806. bodyCreationObject[key] = nativeOptions[key];
  74807. }
  74808. }
  74809. impostor.physicsBody = new this.BJSCANNON.Body(bodyCreationObject);
  74810. impostor.physicsBody.addEventListener("collide", impostor.onCollide);
  74811. this.world.addEventListener("preStep", impostor.beforeStep);
  74812. this.world.addEventListener("postStep", impostor.afterStep);
  74813. impostor.physicsBody.addShape(shape);
  74814. this.world.add(impostor.physicsBody);
  74815. //try to keep the body moving in the right direction by taking old properties.
  74816. //Should be tested!
  74817. if (oldBody) {
  74818. ['force', 'torque', 'velocity', 'angularVelocity'].forEach(function (param) {
  74819. impostor.physicsBody[param].copy(oldBody[param]);
  74820. });
  74821. }
  74822. this._processChildMeshes(impostor);
  74823. }
  74824. //now update the body's transformation
  74825. this._updatePhysicsBodyTransformation(impostor);
  74826. };
  74827. CannonJSPlugin.prototype._processChildMeshes = function (mainImpostor) {
  74828. var _this = this;
  74829. var meshChildren = mainImpostor.object.getChildMeshes ? mainImpostor.object.getChildMeshes(true) : [];
  74830. var currentRotation = mainImpostor.object.rotationQuaternion;
  74831. if (meshChildren.length) {
  74832. var processMesh = function (localPosition, mesh) {
  74833. if (!currentRotation || !mesh.rotationQuaternion) {
  74834. return;
  74835. }
  74836. var childImpostor = mesh.getPhysicsImpostor();
  74837. if (childImpostor) {
  74838. var parent = childImpostor.parent;
  74839. if (parent !== mainImpostor) {
  74840. var pPosition = mesh.getAbsolutePosition().subtract(mainImpostor.object.getAbsolutePosition());
  74841. var localRotation = mesh.rotationQuaternion.multiply(BABYLON.Quaternion.Inverse(currentRotation));
  74842. if (childImpostor.physicsBody) {
  74843. _this.removePhysicsBody(childImpostor);
  74844. childImpostor.physicsBody = null;
  74845. }
  74846. childImpostor.parent = mainImpostor;
  74847. childImpostor.resetUpdateFlags();
  74848. 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));
  74849. //Add the mass of the children.
  74850. mainImpostor.physicsBody.mass += childImpostor.getParam("mass");
  74851. }
  74852. }
  74853. currentRotation.multiplyInPlace(mesh.rotationQuaternion);
  74854. mesh.getChildMeshes(true).filter(function (m) { return !!m.physicsImpostor; }).forEach(processMesh.bind(_this, mesh.getAbsolutePosition()));
  74855. };
  74856. meshChildren.filter(function (m) { return !!m.physicsImpostor; }).forEach(processMesh.bind(this, mainImpostor.object.getAbsolutePosition()));
  74857. }
  74858. };
  74859. CannonJSPlugin.prototype.removePhysicsBody = function (impostor) {
  74860. impostor.physicsBody.removeEventListener("collide", impostor.onCollide);
  74861. this.world.removeEventListener("preStep", impostor.beforeStep);
  74862. this.world.removeEventListener("postStep", impostor.afterStep);
  74863. this.world.remove(impostor.physicsBody);
  74864. };
  74865. CannonJSPlugin.prototype.generateJoint = function (impostorJoint) {
  74866. var mainBody = impostorJoint.mainImpostor.physicsBody;
  74867. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  74868. if (!mainBody || !connectedBody) {
  74869. return;
  74870. }
  74871. var constraint;
  74872. var jointData = impostorJoint.joint.jointData;
  74873. //TODO - https://github.com/schteppe/this.BJSCANNON.js/blob/gh-pages/demos/collisionFilter.html
  74874. var constraintData = {
  74875. pivotA: jointData.mainPivot ? new this.BJSCANNON.Vec3().copy(jointData.mainPivot) : null,
  74876. pivotB: jointData.connectedPivot ? new this.BJSCANNON.Vec3().copy(jointData.connectedPivot) : null,
  74877. axisA: jointData.mainAxis ? new this.BJSCANNON.Vec3().copy(jointData.mainAxis) : null,
  74878. axisB: jointData.connectedAxis ? new this.BJSCANNON.Vec3().copy(jointData.connectedAxis) : null,
  74879. maxForce: jointData.nativeParams.maxForce,
  74880. collideConnected: !!jointData.collision
  74881. };
  74882. switch (impostorJoint.joint.type) {
  74883. case BABYLON.PhysicsJoint.HingeJoint:
  74884. case BABYLON.PhysicsJoint.Hinge2Joint:
  74885. constraint = new this.BJSCANNON.HingeConstraint(mainBody, connectedBody, constraintData);
  74886. break;
  74887. case BABYLON.PhysicsJoint.DistanceJoint:
  74888. constraint = new this.BJSCANNON.DistanceConstraint(mainBody, connectedBody, jointData.maxDistance || 2);
  74889. break;
  74890. case BABYLON.PhysicsJoint.SpringJoint:
  74891. var springData = jointData;
  74892. constraint = new this.BJSCANNON.Spring(mainBody, connectedBody, {
  74893. restLength: springData.length,
  74894. stiffness: springData.stiffness,
  74895. damping: springData.damping,
  74896. localAnchorA: constraintData.pivotA,
  74897. localAnchorB: constraintData.pivotB
  74898. });
  74899. break;
  74900. case BABYLON.PhysicsJoint.LockJoint:
  74901. constraint = new this.BJSCANNON.LockConstraint(mainBody, connectedBody, constraintData);
  74902. break;
  74903. case BABYLON.PhysicsJoint.PointToPointJoint:
  74904. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  74905. default:
  74906. constraint = new this.BJSCANNON.PointToPointConstraint(mainBody, constraintData.pivotA, connectedBody, constraintData.pivotA, constraintData.maxForce);
  74907. break;
  74908. }
  74909. //set the collideConnected flag after the creation, since DistanceJoint ignores it.
  74910. constraint.collideConnected = !!jointData.collision;
  74911. impostorJoint.joint.physicsJoint = constraint;
  74912. //don't add spring as constraint, as it is not one.
  74913. if (impostorJoint.joint.type !== BABYLON.PhysicsJoint.SpringJoint) {
  74914. this.world.addConstraint(constraint);
  74915. }
  74916. else {
  74917. impostorJoint.mainImpostor.registerAfterPhysicsStep(function () {
  74918. constraint.applyForce();
  74919. });
  74920. }
  74921. };
  74922. CannonJSPlugin.prototype.removeJoint = function (impostorJoint) {
  74923. this.world.removeConstraint(impostorJoint.joint.physicsJoint);
  74924. };
  74925. CannonJSPlugin.prototype._addMaterial = function (name, friction, restitution) {
  74926. var index;
  74927. var mat;
  74928. for (index = 0; index < this._physicsMaterials.length; index++) {
  74929. mat = this._physicsMaterials[index];
  74930. if (mat.friction === friction && mat.restitution === restitution) {
  74931. return mat;
  74932. }
  74933. }
  74934. var currentMat = new this.BJSCANNON.Material(name);
  74935. currentMat.friction = friction;
  74936. currentMat.restitution = restitution;
  74937. this._physicsMaterials.push(currentMat);
  74938. return currentMat;
  74939. };
  74940. CannonJSPlugin.prototype._checkWithEpsilon = function (value) {
  74941. return value < BABYLON.PhysicsEngine.Epsilon ? BABYLON.PhysicsEngine.Epsilon : value;
  74942. };
  74943. CannonJSPlugin.prototype._createShape = function (impostor) {
  74944. var object = impostor.object;
  74945. var returnValue;
  74946. var extendSize = impostor.getObjectExtendSize();
  74947. switch (impostor.type) {
  74948. case BABYLON.PhysicsImpostor.SphereImpostor:
  74949. var radiusX = extendSize.x;
  74950. var radiusY = extendSize.y;
  74951. var radiusZ = extendSize.z;
  74952. returnValue = new this.BJSCANNON.Sphere(Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2);
  74953. break;
  74954. //TMP also for cylinder - TODO Cannon supports cylinder natively.
  74955. case BABYLON.PhysicsImpostor.CylinderImpostor:
  74956. returnValue = new this.BJSCANNON.Cylinder(this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.y), 16);
  74957. break;
  74958. case BABYLON.PhysicsImpostor.BoxImpostor:
  74959. var box = extendSize.scale(0.5);
  74960. returnValue = new this.BJSCANNON.Box(new this.BJSCANNON.Vec3(this._checkWithEpsilon(box.x), this._checkWithEpsilon(box.y), this._checkWithEpsilon(box.z)));
  74961. break;
  74962. case BABYLON.PhysicsImpostor.PlaneImpostor:
  74963. BABYLON.Tools.Warn("Attention, PlaneImposter might not behave as you expect. Consider using BoxImposter instead");
  74964. returnValue = new this.BJSCANNON.Plane();
  74965. break;
  74966. case BABYLON.PhysicsImpostor.MeshImpostor:
  74967. // should transform the vertex data to world coordinates!!
  74968. var rawVerts = object.getVerticesData ? object.getVerticesData(BABYLON.VertexBuffer.PositionKind) : [];
  74969. var rawFaces = object.getIndices ? object.getIndices() : [];
  74970. if (!rawVerts)
  74971. return;
  74972. // get only scale! so the object could transform correctly.
  74973. var oldPosition = object.position.clone();
  74974. var oldRotation = object.rotation && object.rotation.clone();
  74975. var oldQuaternion = object.rotationQuaternion && object.rotationQuaternion.clone();
  74976. object.position.copyFromFloats(0, 0, 0);
  74977. object.rotation && object.rotation.copyFromFloats(0, 0, 0);
  74978. object.rotationQuaternion && object.rotationQuaternion.copyFrom(impostor.getParentsRotation());
  74979. object.rotationQuaternion && object.parent && object.rotationQuaternion.conjugateInPlace();
  74980. var transform = object.computeWorldMatrix(true);
  74981. // convert rawVerts to object space
  74982. var temp = new Array();
  74983. var index;
  74984. for (index = 0; index < rawVerts.length; index += 3) {
  74985. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(rawVerts, index), transform).toArray(temp, index);
  74986. }
  74987. BABYLON.Tools.Warn("MeshImpostor only collides against spheres.");
  74988. returnValue = new this.BJSCANNON.Trimesh(temp, rawFaces);
  74989. //now set back the transformation!
  74990. object.position.copyFrom(oldPosition);
  74991. oldRotation && object.rotation && object.rotation.copyFrom(oldRotation);
  74992. oldQuaternion && object.rotationQuaternion && object.rotationQuaternion.copyFrom(oldQuaternion);
  74993. break;
  74994. case BABYLON.PhysicsImpostor.HeightmapImpostor:
  74995. var oldPosition2 = object.position.clone();
  74996. var oldRotation2 = object.rotation && object.rotation.clone();
  74997. var oldQuaternion2 = object.rotationQuaternion && object.rotationQuaternion.clone();
  74998. object.position.copyFromFloats(0, 0, 0);
  74999. object.rotation && object.rotation.copyFromFloats(0, 0, 0);
  75000. object.rotationQuaternion && object.rotationQuaternion.copyFrom(impostor.getParentsRotation());
  75001. object.rotationQuaternion && object.parent && object.rotationQuaternion.conjugateInPlace();
  75002. object.rotationQuaternion && object.rotationQuaternion.multiplyInPlace(this._minus90X);
  75003. returnValue = this._createHeightmap(object);
  75004. object.position.copyFrom(oldPosition2);
  75005. oldRotation2 && object.rotation && object.rotation.copyFrom(oldRotation2);
  75006. oldQuaternion2 && object.rotationQuaternion && object.rotationQuaternion.copyFrom(oldQuaternion2);
  75007. object.computeWorldMatrix(true);
  75008. break;
  75009. case BABYLON.PhysicsImpostor.ParticleImpostor:
  75010. returnValue = new this.BJSCANNON.Particle();
  75011. break;
  75012. }
  75013. return returnValue;
  75014. };
  75015. CannonJSPlugin.prototype._createHeightmap = function (object, pointDepth) {
  75016. var pos = (object.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  75017. var transform = object.computeWorldMatrix(true);
  75018. // convert rawVerts to object space
  75019. var temp = new Array();
  75020. var index;
  75021. for (index = 0; index < pos.length; index += 3) {
  75022. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(pos, index), transform).toArray(temp, index);
  75023. }
  75024. pos = temp;
  75025. var matrix = new Array();
  75026. //For now pointDepth will not be used and will be automatically calculated.
  75027. //Future reference - try and find the best place to add a reference to the pointDepth variable.
  75028. var arraySize = pointDepth || ~~(Math.sqrt(pos.length / 3) - 1);
  75029. var boundingInfo = object.getBoundingInfo();
  75030. var dim = Math.min(boundingInfo.boundingBox.extendSizeWorld.x, boundingInfo.boundingBox.extendSizeWorld.y);
  75031. var minY = boundingInfo.boundingBox.extendSizeWorld.z;
  75032. var elementSize = dim * 2 / arraySize;
  75033. for (var i = 0; i < pos.length; i = i + 3) {
  75034. var x = Math.round((pos[i + 0]) / elementSize + arraySize / 2);
  75035. var z = Math.round(((pos[i + 1]) / elementSize - arraySize / 2) * -1);
  75036. var y = -pos[i + 2] + minY;
  75037. if (!matrix[x]) {
  75038. matrix[x] = [];
  75039. }
  75040. if (!matrix[x][z]) {
  75041. matrix[x][z] = y;
  75042. }
  75043. matrix[x][z] = Math.max(y, matrix[x][z]);
  75044. }
  75045. for (var x = 0; x <= arraySize; ++x) {
  75046. if (!matrix[x]) {
  75047. var loc = 1;
  75048. while (!matrix[(x + loc) % arraySize]) {
  75049. loc++;
  75050. }
  75051. matrix[x] = matrix[(x + loc) % arraySize].slice();
  75052. //console.log("missing x", x);
  75053. }
  75054. for (var z = 0; z <= arraySize; ++z) {
  75055. if (!matrix[x][z]) {
  75056. var loc = 1;
  75057. var newValue;
  75058. while (newValue === undefined) {
  75059. newValue = matrix[x][(z + loc++) % arraySize];
  75060. }
  75061. matrix[x][z] = newValue;
  75062. }
  75063. }
  75064. }
  75065. var shape = new this.BJSCANNON.Heightfield(matrix, {
  75066. elementSize: elementSize
  75067. });
  75068. //For future reference, needed for body transformation
  75069. shape.minY = minY;
  75070. return shape;
  75071. };
  75072. CannonJSPlugin.prototype._updatePhysicsBodyTransformation = function (impostor) {
  75073. var object = impostor.object;
  75074. //make sure it is updated...
  75075. object.computeWorldMatrix && object.computeWorldMatrix(true);
  75076. // The delta between the mesh position and the mesh bounding box center
  75077. var bInfo = object.getBoundingInfo();
  75078. if (!bInfo)
  75079. return;
  75080. var center = impostor.getObjectCenter();
  75081. //m.getAbsolutePosition().subtract(m.getBoundingInfo().boundingBox.centerWorld)
  75082. this._tmpDeltaPosition.copyFrom(object.getAbsolutePivotPoint().subtract(center));
  75083. this._tmpDeltaPosition.divideInPlace(impostor.object.scaling);
  75084. this._tmpPosition.copyFrom(center);
  75085. var quaternion = object.rotationQuaternion;
  75086. if (!quaternion) {
  75087. return;
  75088. }
  75089. //is shape is a plane or a heightmap, it must be rotated 90 degs in the X axis.
  75090. if (impostor.type === BABYLON.PhysicsImpostor.PlaneImpostor || impostor.type === BABYLON.PhysicsImpostor.HeightmapImpostor || impostor.type === BABYLON.PhysicsImpostor.CylinderImpostor) {
  75091. //-90 DEG in X, precalculated
  75092. quaternion = quaternion.multiply(this._minus90X);
  75093. //Invert! (Precalculated, 90 deg in X)
  75094. //No need to clone. this will never change.
  75095. impostor.setDeltaRotation(this._plus90X);
  75096. }
  75097. //If it is a heightfield, if should be centered.
  75098. if (impostor.type === BABYLON.PhysicsImpostor.HeightmapImpostor) {
  75099. var mesh = object;
  75100. var boundingInfo = mesh.getBoundingInfo();
  75101. //calculate the correct body position:
  75102. var rotationQuaternion = mesh.rotationQuaternion;
  75103. mesh.rotationQuaternion = this._tmpUnityRotation;
  75104. mesh.computeWorldMatrix(true);
  75105. //get original center with no rotation
  75106. var c = center.clone();
  75107. var oldPivot = mesh.getPivotMatrix() || BABYLON.Matrix.Translation(0, 0, 0);
  75108. //calculate the new center using a pivot (since this.BJSCANNON.js doesn't center height maps)
  75109. var p = BABYLON.Matrix.Translation(boundingInfo.boundingBox.extendSizeWorld.x, 0, -boundingInfo.boundingBox.extendSizeWorld.z);
  75110. mesh.setPreTransformMatrix(p);
  75111. mesh.computeWorldMatrix(true);
  75112. //calculate the translation
  75113. var translation = boundingInfo.boundingBox.centerWorld.subtract(center).subtract(mesh.position).negate();
  75114. this._tmpPosition.copyFromFloats(translation.x, translation.y - boundingInfo.boundingBox.extendSizeWorld.y, translation.z);
  75115. //add it inverted to the delta
  75116. this._tmpDeltaPosition.copyFrom(boundingInfo.boundingBox.centerWorld.subtract(c));
  75117. this._tmpDeltaPosition.y += boundingInfo.boundingBox.extendSizeWorld.y;
  75118. //rotation is back
  75119. mesh.rotationQuaternion = rotationQuaternion;
  75120. mesh.setPreTransformMatrix(oldPivot);
  75121. mesh.computeWorldMatrix(true);
  75122. }
  75123. else if (impostor.type === BABYLON.PhysicsImpostor.MeshImpostor) {
  75124. this._tmpDeltaPosition.copyFromFloats(0, 0, 0);
  75125. //this._tmpPosition.copyFrom(object.position);
  75126. }
  75127. impostor.setDeltaPosition(this._tmpDeltaPosition);
  75128. //Now update the impostor object
  75129. impostor.physicsBody.position.copy(this._tmpPosition);
  75130. impostor.physicsBody.quaternion.copy(quaternion);
  75131. };
  75132. CannonJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  75133. impostor.object.position.copyFrom(impostor.physicsBody.position);
  75134. if (impostor.object.rotationQuaternion) {
  75135. impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.quaternion);
  75136. }
  75137. };
  75138. CannonJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  75139. impostor.physicsBody.position.copy(newPosition);
  75140. impostor.physicsBody.quaternion.copy(newRotation);
  75141. };
  75142. CannonJSPlugin.prototype.isSupported = function () {
  75143. return this.BJSCANNON !== undefined;
  75144. };
  75145. CannonJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  75146. impostor.physicsBody.velocity.copy(velocity);
  75147. };
  75148. CannonJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  75149. impostor.physicsBody.angularVelocity.copy(velocity);
  75150. };
  75151. CannonJSPlugin.prototype.getLinearVelocity = function (impostor) {
  75152. var v = impostor.physicsBody.velocity;
  75153. if (!v) {
  75154. return null;
  75155. }
  75156. return new BABYLON.Vector3(v.x, v.y, v.z);
  75157. };
  75158. CannonJSPlugin.prototype.getAngularVelocity = function (impostor) {
  75159. var v = impostor.physicsBody.angularVelocity;
  75160. if (!v) {
  75161. return null;
  75162. }
  75163. return new BABYLON.Vector3(v.x, v.y, v.z);
  75164. };
  75165. CannonJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  75166. impostor.physicsBody.mass = mass;
  75167. impostor.physicsBody.updateMassProperties();
  75168. };
  75169. CannonJSPlugin.prototype.getBodyMass = function (impostor) {
  75170. return impostor.physicsBody.mass;
  75171. };
  75172. CannonJSPlugin.prototype.getBodyFriction = function (impostor) {
  75173. return impostor.physicsBody.material.friction;
  75174. };
  75175. CannonJSPlugin.prototype.setBodyFriction = function (impostor, friction) {
  75176. impostor.physicsBody.material.friction = friction;
  75177. };
  75178. CannonJSPlugin.prototype.getBodyRestitution = function (impostor) {
  75179. return impostor.physicsBody.material.restitution;
  75180. };
  75181. CannonJSPlugin.prototype.setBodyRestitution = function (impostor, restitution) {
  75182. impostor.physicsBody.material.restitution = restitution;
  75183. };
  75184. CannonJSPlugin.prototype.sleepBody = function (impostor) {
  75185. impostor.physicsBody.sleep();
  75186. };
  75187. CannonJSPlugin.prototype.wakeUpBody = function (impostor) {
  75188. impostor.physicsBody.wakeUp();
  75189. };
  75190. CannonJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
  75191. joint.physicsJoint.distance = maxDistance;
  75192. };
  75193. // private enableMotor(joint: IMotorEnabledJoint, motorIndex?: number) {
  75194. // if (!motorIndex) {
  75195. // joint.physicsJoint.enableMotor();
  75196. // }
  75197. // }
  75198. // private disableMotor(joint: IMotorEnabledJoint, motorIndex?: number) {
  75199. // if (!motorIndex) {
  75200. // joint.physicsJoint.disableMotor();
  75201. // }
  75202. // }
  75203. CannonJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
  75204. if (!motorIndex) {
  75205. joint.physicsJoint.enableMotor();
  75206. joint.physicsJoint.setMotorSpeed(speed);
  75207. if (maxForce) {
  75208. this.setLimit(joint, maxForce);
  75209. }
  75210. }
  75211. };
  75212. CannonJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit) {
  75213. joint.physicsJoint.motorEquation.maxForce = upperLimit;
  75214. joint.physicsJoint.motorEquation.minForce = lowerLimit === void 0 ? -upperLimit : lowerLimit;
  75215. };
  75216. CannonJSPlugin.prototype.syncMeshWithImpostor = function (mesh, impostor) {
  75217. var body = impostor.physicsBody;
  75218. mesh.position.x = body.position.x;
  75219. mesh.position.y = body.position.y;
  75220. mesh.position.z = body.position.z;
  75221. if (mesh.rotationQuaternion) {
  75222. mesh.rotationQuaternion.x = body.quaternion.x;
  75223. mesh.rotationQuaternion.y = body.quaternion.y;
  75224. mesh.rotationQuaternion.z = body.quaternion.z;
  75225. mesh.rotationQuaternion.w = body.quaternion.w;
  75226. }
  75227. };
  75228. CannonJSPlugin.prototype.getRadius = function (impostor) {
  75229. var shape = impostor.physicsBody.shapes[0];
  75230. return shape.boundingSphereRadius;
  75231. };
  75232. CannonJSPlugin.prototype.getBoxSizeToRef = function (impostor, result) {
  75233. var shape = impostor.physicsBody.shapes[0];
  75234. result.x = shape.halfExtents.x * 2;
  75235. result.y = shape.halfExtents.y * 2;
  75236. result.z = shape.halfExtents.z * 2;
  75237. };
  75238. CannonJSPlugin.prototype.dispose = function () {
  75239. };
  75240. CannonJSPlugin.prototype._extendNamespace = function () {
  75241. //this will force cannon to execute at least one step when using interpolation
  75242. var step_tmp1 = new this.BJSCANNON.Vec3();
  75243. var Engine = this.BJSCANNON;
  75244. this.BJSCANNON.World.prototype.step = function (dt, timeSinceLastCalled, maxSubSteps) {
  75245. maxSubSteps = maxSubSteps || 10;
  75246. timeSinceLastCalled = timeSinceLastCalled || 0;
  75247. if (timeSinceLastCalled === 0) {
  75248. this.internalStep(dt);
  75249. this.time += dt;
  75250. }
  75251. else {
  75252. var internalSteps = Math.floor((this.time + timeSinceLastCalled) / dt) - Math.floor(this.time / dt);
  75253. internalSteps = Math.min(internalSteps, maxSubSteps) || 1;
  75254. var t0 = performance.now();
  75255. for (var i = 0; i !== internalSteps; i++) {
  75256. this.internalStep(dt);
  75257. if (performance.now() - t0 > dt * 1000) {
  75258. break;
  75259. }
  75260. }
  75261. this.time += timeSinceLastCalled;
  75262. var h = this.time % dt;
  75263. var h_div_dt = h / dt;
  75264. var interpvelo = step_tmp1;
  75265. var bodies = this.bodies;
  75266. for (var j = 0; j !== bodies.length; j++) {
  75267. var b = bodies[j];
  75268. if (b.type !== Engine.Body.STATIC && b.sleepState !== Engine.Body.SLEEPING) {
  75269. b.position.vsub(b.previousPosition, interpvelo);
  75270. interpvelo.scale(h_div_dt, interpvelo);
  75271. b.position.vadd(interpvelo, b.interpolatedPosition);
  75272. }
  75273. else {
  75274. b.interpolatedPosition.copy(b.position);
  75275. b.interpolatedQuaternion.copy(b.quaternion);
  75276. }
  75277. }
  75278. }
  75279. };
  75280. };
  75281. return CannonJSPlugin;
  75282. }());
  75283. BABYLON.CannonJSPlugin = CannonJSPlugin;
  75284. })(BABYLON || (BABYLON = {}));
  75285. //# sourceMappingURL=babylon.cannonJSPlugin.js.map
  75286. var BABYLON;
  75287. (function (BABYLON) {
  75288. var OimoJSPlugin = /** @class */ (function () {
  75289. function OimoJSPlugin(iterations) {
  75290. this.name = "OimoJSPlugin";
  75291. this._tmpImpostorsArray = [];
  75292. this._tmpPositionVector = BABYLON.Vector3.Zero();
  75293. this.BJSOIMO = typeof OIMO !== 'undefined' ? OIMO : (typeof require !== 'undefined' ? require('./Oimo') : undefined);
  75294. this.world = new this.BJSOIMO.World(1 / 60, 2, iterations, true);
  75295. this.world.worldscale(1);
  75296. this.world.clear();
  75297. //making sure no stats are calculated
  75298. this.world.isNoStat = true;
  75299. }
  75300. OimoJSPlugin.prototype.setGravity = function (gravity) {
  75301. this.world.gravity.copy(gravity);
  75302. };
  75303. OimoJSPlugin.prototype.setTimeStep = function (timeStep) {
  75304. this.world.timeStep = timeStep;
  75305. };
  75306. OimoJSPlugin.prototype.getTimeStep = function () {
  75307. return this.world.timeStep;
  75308. };
  75309. OimoJSPlugin.prototype.executeStep = function (delta, impostors) {
  75310. var _this = this;
  75311. impostors.forEach(function (impostor) {
  75312. impostor.beforeStep();
  75313. });
  75314. this.world.step();
  75315. impostors.forEach(function (impostor) {
  75316. impostor.afterStep();
  75317. //update the ordered impostors array
  75318. _this._tmpImpostorsArray[impostor.uniqueId] = impostor;
  75319. });
  75320. //check for collisions
  75321. var contact = this.world.contacts;
  75322. while (contact !== null) {
  75323. if (contact.touching && !contact.body1.sleeping && !contact.body2.sleeping) {
  75324. contact = contact.next;
  75325. continue;
  75326. }
  75327. //is this body colliding with any other? get the impostor
  75328. var mainImpostor = this._tmpImpostorsArray[+contact.body1.name];
  75329. var collidingImpostor = this._tmpImpostorsArray[+contact.body2.name];
  75330. if (!mainImpostor || !collidingImpostor) {
  75331. contact = contact.next;
  75332. continue;
  75333. }
  75334. mainImpostor.onCollide({ body: collidingImpostor.physicsBody });
  75335. collidingImpostor.onCollide({ body: mainImpostor.physicsBody });
  75336. contact = contact.next;
  75337. }
  75338. };
  75339. OimoJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  75340. var mass = impostor.physicsBody.massInfo.mass;
  75341. impostor.physicsBody.applyImpulse(contactPoint.scale(this.BJSOIMO.INV_SCALE), force.scale(this.BJSOIMO.INV_SCALE * mass));
  75342. };
  75343. OimoJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  75344. BABYLON.Tools.Warn("Oimo doesn't support applying force. Using impule instead.");
  75345. this.applyImpulse(impostor, force, contactPoint);
  75346. };
  75347. OimoJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  75348. var _this = this;
  75349. //parent-child relationship. Does this impostor has a parent impostor?
  75350. if (impostor.parent) {
  75351. if (impostor.physicsBody) {
  75352. this.removePhysicsBody(impostor);
  75353. //TODO is that needed?
  75354. impostor.forceUpdate();
  75355. }
  75356. return;
  75357. }
  75358. if (impostor.isBodyInitRequired()) {
  75359. var bodyConfig = {
  75360. name: impostor.uniqueId,
  75361. //Oimo must have mass, also for static objects.
  75362. config: [impostor.getParam("mass") || 1, impostor.getParam("friction"), impostor.getParam("restitution")],
  75363. size: [],
  75364. type: [],
  75365. pos: [],
  75366. rot: [],
  75367. move: impostor.getParam("mass") !== 0,
  75368. //Supporting older versions of Oimo
  75369. world: this.world
  75370. };
  75371. var impostors = [impostor];
  75372. var addToArray = function (parent) {
  75373. if (!parent.getChildMeshes)
  75374. return;
  75375. parent.getChildMeshes().forEach(function (m) {
  75376. if (m.physicsImpostor) {
  75377. impostors.push(m.physicsImpostor);
  75378. //m.physicsImpostor._init();
  75379. }
  75380. });
  75381. };
  75382. addToArray(impostor.object);
  75383. var checkWithEpsilon_1 = function (value) {
  75384. return Math.max(value, BABYLON.PhysicsEngine.Epsilon);
  75385. };
  75386. impostors.forEach(function (i) {
  75387. if (!impostor.object.rotationQuaternion) {
  75388. return;
  75389. }
  75390. //get the correct bounding box
  75391. var oldQuaternion = i.object.rotationQuaternion;
  75392. var rot = new _this.BJSOIMO.Euler().setFromQuaternion({
  75393. x: impostor.object.rotationQuaternion.x,
  75394. y: impostor.object.rotationQuaternion.y,
  75395. z: impostor.object.rotationQuaternion.z,
  75396. s: impostor.object.rotationQuaternion.w
  75397. });
  75398. var extendSize = i.getObjectExtendSize();
  75399. if (i === impostor) {
  75400. var center = impostor.getObjectCenter();
  75401. impostor.object.getAbsolutePivotPoint().subtractToRef(center, _this._tmpPositionVector);
  75402. _this._tmpPositionVector.divideInPlace(impostor.object.scaling);
  75403. //Can also use Array.prototype.push.apply
  75404. bodyConfig.pos.push(center.x);
  75405. bodyConfig.pos.push(center.y);
  75406. bodyConfig.pos.push(center.z);
  75407. //tmp solution
  75408. bodyConfig.rot.push(rot.x / (_this.BJSOIMO.degtorad || _this.BJSOIMO.TO_RAD));
  75409. bodyConfig.rot.push(rot.y / (_this.BJSOIMO.degtorad || _this.BJSOIMO.TO_RAD));
  75410. bodyConfig.rot.push(rot.z / (_this.BJSOIMO.degtorad || _this.BJSOIMO.TO_RAD));
  75411. }
  75412. else {
  75413. var localPosition = i.object.getAbsolutePosition().subtract(impostor.object.getAbsolutePosition());
  75414. bodyConfig.pos.push(localPosition.x);
  75415. bodyConfig.pos.push(localPosition.y);
  75416. bodyConfig.pos.push(localPosition.z);
  75417. //tmp solution until https://github.com/lo-th/OIMO.js/pull/37 is merged
  75418. bodyConfig.rot.push(0);
  75419. bodyConfig.rot.push(0);
  75420. bodyConfig.rot.push(0);
  75421. }
  75422. // register mesh
  75423. switch (i.type) {
  75424. case BABYLON.PhysicsImpostor.ParticleImpostor:
  75425. BABYLON.Tools.Warn("No Particle support in this.BJSOIMO.js. using SphereImpostor instead");
  75426. case BABYLON.PhysicsImpostor.SphereImpostor:
  75427. var radiusX = extendSize.x;
  75428. var radiusY = extendSize.y;
  75429. var radiusZ = extendSize.z;
  75430. var size = Math.max(checkWithEpsilon_1(radiusX), checkWithEpsilon_1(radiusY), checkWithEpsilon_1(radiusZ)) / 2;
  75431. bodyConfig.type.push('sphere');
  75432. //due to the way oimo works with compounds, add 3 times
  75433. bodyConfig.size.push(size);
  75434. bodyConfig.size.push(size);
  75435. bodyConfig.size.push(size);
  75436. break;
  75437. case BABYLON.PhysicsImpostor.CylinderImpostor:
  75438. var sizeX = checkWithEpsilon_1(extendSize.x) / 2;
  75439. var sizeY = checkWithEpsilon_1(extendSize.y);
  75440. bodyConfig.type.push('cylinder');
  75441. bodyConfig.size.push(sizeX);
  75442. bodyConfig.size.push(sizeY);
  75443. //due to the way oimo works with compounds, add one more value.
  75444. bodyConfig.size.push(sizeY);
  75445. break;
  75446. case BABYLON.PhysicsImpostor.PlaneImpostor:
  75447. case BABYLON.PhysicsImpostor.BoxImpostor:
  75448. default:
  75449. var sizeX = checkWithEpsilon_1(extendSize.x);
  75450. var sizeY = checkWithEpsilon_1(extendSize.y);
  75451. var sizeZ = checkWithEpsilon_1(extendSize.z);
  75452. bodyConfig.type.push('box');
  75453. bodyConfig.size.push(sizeX);
  75454. bodyConfig.size.push(sizeY);
  75455. bodyConfig.size.push(sizeZ);
  75456. break;
  75457. }
  75458. //actually not needed, but hey...
  75459. i.object.rotationQuaternion = oldQuaternion;
  75460. });
  75461. impostor.physicsBody = new this.BJSOIMO.Body(bodyConfig).body; //this.world.add(bodyConfig);
  75462. }
  75463. else {
  75464. this._tmpPositionVector.copyFromFloats(0, 0, 0);
  75465. }
  75466. impostor.setDeltaPosition(this._tmpPositionVector);
  75467. //this._tmpPositionVector.addInPlace(impostor.mesh.getBoundingInfo().boundingBox.center);
  75468. //this.setPhysicsBodyTransformation(impostor, this._tmpPositionVector, impostor.mesh.rotationQuaternion);
  75469. };
  75470. OimoJSPlugin.prototype.removePhysicsBody = function (impostor) {
  75471. //impostor.physicsBody.dispose();
  75472. //Same as : (older oimo versions)
  75473. this.world.removeRigidBody(impostor.physicsBody);
  75474. };
  75475. OimoJSPlugin.prototype.generateJoint = function (impostorJoint) {
  75476. var mainBody = impostorJoint.mainImpostor.physicsBody;
  75477. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  75478. if (!mainBody || !connectedBody) {
  75479. return;
  75480. }
  75481. var jointData = impostorJoint.joint.jointData;
  75482. var options = jointData.nativeParams || {};
  75483. var type;
  75484. var nativeJointData = {
  75485. body1: mainBody,
  75486. body2: connectedBody,
  75487. axe1: options.axe1 || (jointData.mainAxis ? jointData.mainAxis.asArray() : null),
  75488. axe2: options.axe2 || (jointData.connectedAxis ? jointData.connectedAxis.asArray() : null),
  75489. pos1: options.pos1 || (jointData.mainPivot ? jointData.mainPivot.asArray() : null),
  75490. pos2: options.pos2 || (jointData.connectedPivot ? jointData.connectedPivot.asArray() : null),
  75491. min: options.min,
  75492. max: options.max,
  75493. collision: options.collision || jointData.collision,
  75494. spring: options.spring,
  75495. //supporting older version of Oimo
  75496. world: this.world
  75497. };
  75498. switch (impostorJoint.joint.type) {
  75499. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  75500. type = "jointBall";
  75501. break;
  75502. case BABYLON.PhysicsJoint.SpringJoint:
  75503. BABYLON.Tools.Warn("this.BJSOIMO.js doesn't support Spring Constraint. Simulating using DistanceJoint instead");
  75504. var springData = jointData;
  75505. nativeJointData.min = springData.length || nativeJointData.min;
  75506. //Max should also be set, just make sure it is at least min
  75507. nativeJointData.max = Math.max(nativeJointData.min, nativeJointData.max);
  75508. case BABYLON.PhysicsJoint.DistanceJoint:
  75509. type = "jointDistance";
  75510. nativeJointData.max = jointData.maxDistance;
  75511. break;
  75512. case BABYLON.PhysicsJoint.PrismaticJoint:
  75513. type = "jointPrisme";
  75514. break;
  75515. case BABYLON.PhysicsJoint.SliderJoint:
  75516. type = "jointSlide";
  75517. break;
  75518. case BABYLON.PhysicsJoint.WheelJoint:
  75519. type = "jointWheel";
  75520. break;
  75521. case BABYLON.PhysicsJoint.HingeJoint:
  75522. default:
  75523. type = "jointHinge";
  75524. break;
  75525. }
  75526. nativeJointData.type = type;
  75527. impostorJoint.joint.physicsJoint = new this.BJSOIMO.Link(nativeJointData).joint; //this.world.add(nativeJointData);
  75528. };
  75529. OimoJSPlugin.prototype.removeJoint = function (impostorJoint) {
  75530. //Bug in Oimo prevents us from disposing a joint in the playground
  75531. //joint.joint.physicsJoint.dispose();
  75532. //So we will bruteforce it!
  75533. try {
  75534. this.world.removeJoint(impostorJoint.joint.physicsJoint);
  75535. }
  75536. catch (e) {
  75537. BABYLON.Tools.Warn(e);
  75538. }
  75539. };
  75540. OimoJSPlugin.prototype.isSupported = function () {
  75541. return this.BJSOIMO !== undefined;
  75542. };
  75543. OimoJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  75544. if (!impostor.physicsBody.sleeping) {
  75545. //TODO check that
  75546. if (impostor.physicsBody.shapes.next) {
  75547. var parentShape = this._getLastShape(impostor.physicsBody);
  75548. impostor.object.position.x = parentShape.position.x * this.BJSOIMO.WORLD_SCALE;
  75549. impostor.object.position.y = parentShape.position.y * this.BJSOIMO.WORLD_SCALE;
  75550. impostor.object.position.z = parentShape.position.z * this.BJSOIMO.WORLD_SCALE;
  75551. }
  75552. else {
  75553. impostor.object.position.copyFrom(impostor.physicsBody.getPosition());
  75554. }
  75555. if (impostor.object.rotationQuaternion) {
  75556. impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.getQuaternion());
  75557. impostor.object.rotationQuaternion.normalize();
  75558. }
  75559. }
  75560. };
  75561. OimoJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  75562. var body = impostor.physicsBody;
  75563. body.position.init(newPosition.x * this.BJSOIMO.INV_SCALE, newPosition.y * this.BJSOIMO.INV_SCALE, newPosition.z * this.BJSOIMO.INV_SCALE);
  75564. body.orientation.init(newRotation.w, newRotation.x, newRotation.y, newRotation.z);
  75565. body.syncShapes();
  75566. body.awake();
  75567. };
  75568. OimoJSPlugin.prototype._getLastShape = function (body) {
  75569. var lastShape = body.shapes;
  75570. while (lastShape.next) {
  75571. lastShape = lastShape.next;
  75572. }
  75573. return lastShape;
  75574. };
  75575. OimoJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  75576. impostor.physicsBody.linearVelocity.init(velocity.x, velocity.y, velocity.z);
  75577. };
  75578. OimoJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  75579. impostor.physicsBody.angularVelocity.init(velocity.x, velocity.y, velocity.z);
  75580. };
  75581. OimoJSPlugin.prototype.getLinearVelocity = function (impostor) {
  75582. var v = impostor.physicsBody.linearVelocity;
  75583. if (!v) {
  75584. return null;
  75585. }
  75586. return new BABYLON.Vector3(v.x, v.y, v.z);
  75587. };
  75588. OimoJSPlugin.prototype.getAngularVelocity = function (impostor) {
  75589. var v = impostor.physicsBody.angularVelocity;
  75590. if (!v) {
  75591. return null;
  75592. }
  75593. return new BABYLON.Vector3(v.x, v.y, v.z);
  75594. };
  75595. OimoJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  75596. var staticBody = mass === 0;
  75597. //this will actually set the body's density and not its mass.
  75598. //But this is how oimo treats the mass variable.
  75599. impostor.physicsBody.shapes.density = staticBody ? 1 : mass;
  75600. impostor.physicsBody.setupMass(staticBody ? 0x2 : 0x1);
  75601. };
  75602. OimoJSPlugin.prototype.getBodyMass = function (impostor) {
  75603. return impostor.physicsBody.shapes.density;
  75604. };
  75605. OimoJSPlugin.prototype.getBodyFriction = function (impostor) {
  75606. return impostor.physicsBody.shapes.friction;
  75607. };
  75608. OimoJSPlugin.prototype.setBodyFriction = function (impostor, friction) {
  75609. impostor.physicsBody.shapes.friction = friction;
  75610. };
  75611. OimoJSPlugin.prototype.getBodyRestitution = function (impostor) {
  75612. return impostor.physicsBody.shapes.restitution;
  75613. };
  75614. OimoJSPlugin.prototype.setBodyRestitution = function (impostor, restitution) {
  75615. impostor.physicsBody.shapes.restitution = restitution;
  75616. };
  75617. OimoJSPlugin.prototype.sleepBody = function (impostor) {
  75618. impostor.physicsBody.sleep();
  75619. };
  75620. OimoJSPlugin.prototype.wakeUpBody = function (impostor) {
  75621. impostor.physicsBody.awake();
  75622. };
  75623. OimoJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
  75624. joint.physicsJoint.limitMotor.upperLimit = maxDistance;
  75625. if (minDistance !== void 0) {
  75626. joint.physicsJoint.limitMotor.lowerLimit = minDistance;
  75627. }
  75628. };
  75629. OimoJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
  75630. //TODO separate rotational and transational motors.
  75631. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;
  75632. if (motor) {
  75633. motor.setMotor(speed, maxForce);
  75634. }
  75635. };
  75636. OimoJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit, motorIndex) {
  75637. //TODO separate rotational and transational motors.
  75638. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;
  75639. if (motor) {
  75640. motor.setLimit(upperLimit, lowerLimit === void 0 ? -upperLimit : lowerLimit);
  75641. }
  75642. };
  75643. OimoJSPlugin.prototype.syncMeshWithImpostor = function (mesh, impostor) {
  75644. var body = impostor.physicsBody;
  75645. mesh.position.x = body.position.x;
  75646. mesh.position.y = body.position.y;
  75647. mesh.position.z = body.position.z;
  75648. if (mesh.rotationQuaternion) {
  75649. mesh.rotationQuaternion.x = body.orientation.x;
  75650. mesh.rotationQuaternion.y = body.orientation.y;
  75651. mesh.rotationQuaternion.z = body.orientation.z;
  75652. mesh.rotationQuaternion.w = body.orientation.s;
  75653. }
  75654. };
  75655. OimoJSPlugin.prototype.getRadius = function (impostor) {
  75656. return impostor.physicsBody.shapes.radius;
  75657. };
  75658. OimoJSPlugin.prototype.getBoxSizeToRef = function (impostor, result) {
  75659. var shape = impostor.physicsBody.shapes;
  75660. result.x = shape.halfWidth * 2;
  75661. result.y = shape.halfHeight * 2;
  75662. result.z = shape.halfDepth * 2;
  75663. };
  75664. OimoJSPlugin.prototype.dispose = function () {
  75665. this.world.clear();
  75666. };
  75667. return OimoJSPlugin;
  75668. }());
  75669. BABYLON.OimoJSPlugin = OimoJSPlugin;
  75670. })(BABYLON || (BABYLON = {}));
  75671. //# sourceMappingURL=babylon.oimoJSPlugin.js.map
  75672. var BABYLON;
  75673. (function (BABYLON) {
  75674. /*
  75675. * Based on jsTGALoader - Javascript loader for TGA file
  75676. * By Vincent Thibault
  75677. * @blog http://blog.robrowser.com/javascript-tga-loader.html
  75678. */
  75679. var TGATools = /** @class */ (function () {
  75680. function TGATools() {
  75681. }
  75682. TGATools.GetTGAHeader = function (data) {
  75683. var offset = 0;
  75684. var header = {
  75685. id_length: data[offset++],
  75686. colormap_type: data[offset++],
  75687. image_type: data[offset++],
  75688. colormap_index: data[offset++] | data[offset++] << 8,
  75689. colormap_length: data[offset++] | data[offset++] << 8,
  75690. colormap_size: data[offset++],
  75691. origin: [
  75692. data[offset++] | data[offset++] << 8,
  75693. data[offset++] | data[offset++] << 8
  75694. ],
  75695. width: data[offset++] | data[offset++] << 8,
  75696. height: data[offset++] | data[offset++] << 8,
  75697. pixel_size: data[offset++],
  75698. flags: data[offset++]
  75699. };
  75700. return header;
  75701. };
  75702. TGATools.UploadContent = function (gl, data) {
  75703. // Not enough data to contain header ?
  75704. if (data.length < 19) {
  75705. BABYLON.Tools.Error("Unable to load TGA file - Not enough data to contain header");
  75706. return;
  75707. }
  75708. // Read Header
  75709. var offset = 18;
  75710. var header = TGATools.GetTGAHeader(data);
  75711. // Assume it's a valid Targa file.
  75712. if (header.id_length + offset > data.length) {
  75713. BABYLON.Tools.Error("Unable to load TGA file - Not enough data");
  75714. return;
  75715. }
  75716. // Skip not needed data
  75717. offset += header.id_length;
  75718. var use_rle = false;
  75719. var use_pal = false;
  75720. var use_grey = false;
  75721. // Get some informations.
  75722. switch (header.image_type) {
  75723. case TGATools._TYPE_RLE_INDEXED:
  75724. use_rle = true;
  75725. case TGATools._TYPE_INDEXED:
  75726. use_pal = true;
  75727. break;
  75728. case TGATools._TYPE_RLE_RGB:
  75729. use_rle = true;
  75730. case TGATools._TYPE_RGB:
  75731. // use_rgb = true;
  75732. break;
  75733. case TGATools._TYPE_RLE_GREY:
  75734. use_rle = true;
  75735. case TGATools._TYPE_GREY:
  75736. use_grey = true;
  75737. break;
  75738. }
  75739. var pixel_data;
  75740. // var numAlphaBits = header.flags & 0xf;
  75741. var pixel_size = header.pixel_size >> 3;
  75742. var pixel_total = header.width * header.height * pixel_size;
  75743. // Read palettes
  75744. var palettes;
  75745. if (use_pal) {
  75746. palettes = data.subarray(offset, offset += header.colormap_length * (header.colormap_size >> 3));
  75747. }
  75748. // Read LRE
  75749. if (use_rle) {
  75750. pixel_data = new Uint8Array(pixel_total);
  75751. var c, count, i;
  75752. var localOffset = 0;
  75753. var pixels = new Uint8Array(pixel_size);
  75754. while (offset < pixel_total && localOffset < pixel_total) {
  75755. c = data[offset++];
  75756. count = (c & 0x7f) + 1;
  75757. // RLE pixels
  75758. if (c & 0x80) {
  75759. // Bind pixel tmp array
  75760. for (i = 0; i < pixel_size; ++i) {
  75761. pixels[i] = data[offset++];
  75762. }
  75763. // Copy pixel array
  75764. for (i = 0; i < count; ++i) {
  75765. pixel_data.set(pixels, localOffset + i * pixel_size);
  75766. }
  75767. localOffset += pixel_size * count;
  75768. }
  75769. else {
  75770. count *= pixel_size;
  75771. for (i = 0; i < count; ++i) {
  75772. pixel_data[localOffset + i] = data[offset++];
  75773. }
  75774. localOffset += count;
  75775. }
  75776. }
  75777. }
  75778. else {
  75779. pixel_data = data.subarray(offset, offset += (use_pal ? header.width * header.height : pixel_total));
  75780. }
  75781. // Load to texture
  75782. var x_start, y_start, x_step, y_step, y_end, x_end;
  75783. switch ((header.flags & TGATools._ORIGIN_MASK) >> TGATools._ORIGIN_SHIFT) {
  75784. default:
  75785. case TGATools._ORIGIN_UL:
  75786. x_start = 0;
  75787. x_step = 1;
  75788. x_end = header.width;
  75789. y_start = 0;
  75790. y_step = 1;
  75791. y_end = header.height;
  75792. break;
  75793. case TGATools._ORIGIN_BL:
  75794. x_start = 0;
  75795. x_step = 1;
  75796. x_end = header.width;
  75797. y_start = header.height - 1;
  75798. y_step = -1;
  75799. y_end = -1;
  75800. break;
  75801. case TGATools._ORIGIN_UR:
  75802. x_start = header.width - 1;
  75803. x_step = -1;
  75804. x_end = -1;
  75805. y_start = 0;
  75806. y_step = 1;
  75807. y_end = header.height;
  75808. break;
  75809. case TGATools._ORIGIN_BR:
  75810. x_start = header.width - 1;
  75811. x_step = -1;
  75812. x_end = -1;
  75813. y_start = header.height - 1;
  75814. y_step = -1;
  75815. y_end = -1;
  75816. break;
  75817. }
  75818. // Load the specify method
  75819. var func = '_getImageData' + (use_grey ? 'Grey' : '') + (header.pixel_size) + 'bits';
  75820. var imageData = TGATools[func](header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end);
  75821. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, header.width, header.height, 0, gl.RGBA, gl.UNSIGNED_BYTE, imageData);
  75822. };
  75823. TGATools._getImageData8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  75824. var image = pixel_data, colormap = palettes;
  75825. var width = header.width, height = header.height;
  75826. var color, i = 0, x, y;
  75827. var imageData = new Uint8Array(width * height * 4);
  75828. for (y = y_start; y !== y_end; y += y_step) {
  75829. for (x = x_start; x !== x_end; x += x_step, i++) {
  75830. color = image[i];
  75831. imageData[(x + width * y) * 4 + 3] = 255;
  75832. imageData[(x + width * y) * 4 + 2] = colormap[(color * 3) + 0];
  75833. imageData[(x + width * y) * 4 + 1] = colormap[(color * 3) + 1];
  75834. imageData[(x + width * y) * 4 + 0] = colormap[(color * 3) + 2];
  75835. }
  75836. }
  75837. return imageData;
  75838. };
  75839. TGATools._getImageData16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  75840. var image = pixel_data;
  75841. var width = header.width, height = header.height;
  75842. var color, i = 0, x, y;
  75843. var imageData = new Uint8Array(width * height * 4);
  75844. for (y = y_start; y !== y_end; y += y_step) {
  75845. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  75846. color = image[i + 0] + (image[i + 1] << 8); // Inversed ?
  75847. imageData[(x + width * y) * 4 + 0] = (color & 0x7C00) >> 7;
  75848. imageData[(x + width * y) * 4 + 1] = (color & 0x03E0) >> 2;
  75849. imageData[(x + width * y) * 4 + 2] = (color & 0x001F) >> 3;
  75850. imageData[(x + width * y) * 4 + 3] = (color & 0x8000) ? 0 : 255;
  75851. }
  75852. }
  75853. return imageData;
  75854. };
  75855. TGATools._getImageData24bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  75856. var image = pixel_data;
  75857. var width = header.width, height = header.height;
  75858. var i = 0, x, y;
  75859. var imageData = new Uint8Array(width * height * 4);
  75860. for (y = y_start; y !== y_end; y += y_step) {
  75861. for (x = x_start; x !== x_end; x += x_step, i += 3) {
  75862. imageData[(x + width * y) * 4 + 3] = 255;
  75863. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  75864. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  75865. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  75866. }
  75867. }
  75868. return imageData;
  75869. };
  75870. TGATools._getImageData32bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  75871. var image = pixel_data;
  75872. var width = header.width, height = header.height;
  75873. var i = 0, x, y;
  75874. var imageData = new Uint8Array(width * height * 4);
  75875. for (y = y_start; y !== y_end; y += y_step) {
  75876. for (x = x_start; x !== x_end; x += x_step, i += 4) {
  75877. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  75878. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  75879. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  75880. imageData[(x + width * y) * 4 + 3] = image[i + 3];
  75881. }
  75882. }
  75883. return imageData;
  75884. };
  75885. TGATools._getImageDataGrey8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  75886. var image = pixel_data;
  75887. var width = header.width, height = header.height;
  75888. var color, i = 0, x, y;
  75889. var imageData = new Uint8Array(width * height * 4);
  75890. for (y = y_start; y !== y_end; y += y_step) {
  75891. for (x = x_start; x !== x_end; x += x_step, i++) {
  75892. color = image[i];
  75893. imageData[(x + width * y) * 4 + 0] = color;
  75894. imageData[(x + width * y) * 4 + 1] = color;
  75895. imageData[(x + width * y) * 4 + 2] = color;
  75896. imageData[(x + width * y) * 4 + 3] = 255;
  75897. }
  75898. }
  75899. return imageData;
  75900. };
  75901. TGATools._getImageDataGrey16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  75902. var image = pixel_data;
  75903. var width = header.width, height = header.height;
  75904. var i = 0, x, y;
  75905. var imageData = new Uint8Array(width * height * 4);
  75906. for (y = y_start; y !== y_end; y += y_step) {
  75907. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  75908. imageData[(x + width * y) * 4 + 0] = image[i + 0];
  75909. imageData[(x + width * y) * 4 + 1] = image[i + 0];
  75910. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  75911. imageData[(x + width * y) * 4 + 3] = image[i + 1];
  75912. }
  75913. }
  75914. return imageData;
  75915. };
  75916. //private static _TYPE_NO_DATA = 0;
  75917. TGATools._TYPE_INDEXED = 1;
  75918. TGATools._TYPE_RGB = 2;
  75919. TGATools._TYPE_GREY = 3;
  75920. TGATools._TYPE_RLE_INDEXED = 9;
  75921. TGATools._TYPE_RLE_RGB = 10;
  75922. TGATools._TYPE_RLE_GREY = 11;
  75923. TGATools._ORIGIN_MASK = 0x30;
  75924. TGATools._ORIGIN_SHIFT = 0x04;
  75925. TGATools._ORIGIN_BL = 0x00;
  75926. TGATools._ORIGIN_BR = 0x01;
  75927. TGATools._ORIGIN_UL = 0x02;
  75928. TGATools._ORIGIN_UR = 0x03;
  75929. return TGATools;
  75930. }());
  75931. BABYLON.TGATools = TGATools;
  75932. })(BABYLON || (BABYLON = {}));
  75933. //# sourceMappingURL=babylon.tga.js.map
  75934. var BABYLON;
  75935. (function (BABYLON) {
  75936. // Based on demo done by Brandon Jones - http://media.tojicode.com/webgl-samples/dds.html
  75937. // All values and structures referenced from:
  75938. // http://msdn.microsoft.com/en-us/library/bb943991.aspx/
  75939. var DDS_MAGIC = 0x20534444;
  75940. var
  75941. //DDSD_CAPS = 0x1,
  75942. //DDSD_HEIGHT = 0x2,
  75943. //DDSD_WIDTH = 0x4,
  75944. //DDSD_PITCH = 0x8,
  75945. //DDSD_PIXELFORMAT = 0x1000,
  75946. DDSD_MIPMAPCOUNT = 0x20000;
  75947. //DDSD_LINEARSIZE = 0x80000,
  75948. //DDSD_DEPTH = 0x800000;
  75949. // var DDSCAPS_COMPLEX = 0x8,
  75950. // DDSCAPS_MIPMAP = 0x400000,
  75951. // DDSCAPS_TEXTURE = 0x1000;
  75952. var DDSCAPS2_CUBEMAP = 0x200;
  75953. // DDSCAPS2_CUBEMAP_POSITIVEX = 0x400,
  75954. // DDSCAPS2_CUBEMAP_NEGATIVEX = 0x800,
  75955. // DDSCAPS2_CUBEMAP_POSITIVEY = 0x1000,
  75956. // DDSCAPS2_CUBEMAP_NEGATIVEY = 0x2000,
  75957. // DDSCAPS2_CUBEMAP_POSITIVEZ = 0x4000,
  75958. // DDSCAPS2_CUBEMAP_NEGATIVEZ = 0x8000,
  75959. // DDSCAPS2_VOLUME = 0x200000;
  75960. var
  75961. //DDPF_ALPHAPIXELS = 0x1,
  75962. //DDPF_ALPHA = 0x2,
  75963. DDPF_FOURCC = 0x4, DDPF_RGB = 0x40,
  75964. //DDPF_YUV = 0x200,
  75965. DDPF_LUMINANCE = 0x20000;
  75966. function FourCCToInt32(value) {
  75967. return value.charCodeAt(0) +
  75968. (value.charCodeAt(1) << 8) +
  75969. (value.charCodeAt(2) << 16) +
  75970. (value.charCodeAt(3) << 24);
  75971. }
  75972. function Int32ToFourCC(value) {
  75973. return String.fromCharCode(value & 0xff, (value >> 8) & 0xff, (value >> 16) & 0xff, (value >> 24) & 0xff);
  75974. }
  75975. var FOURCC_DXT1 = FourCCToInt32("DXT1");
  75976. var FOURCC_DXT3 = FourCCToInt32("DXT3");
  75977. var FOURCC_DXT5 = FourCCToInt32("DXT5");
  75978. var FOURCC_DX10 = FourCCToInt32("DX10");
  75979. var FOURCC_D3DFMT_R16G16B16A16F = 113;
  75980. var FOURCC_D3DFMT_R32G32B32A32F = 116;
  75981. var DXGI_FORMAT_R16G16B16A16_FLOAT = 10;
  75982. var DXGI_FORMAT_B8G8R8X8_UNORM = 88;
  75983. var headerLengthInt = 31; // The header length in 32 bit ints
  75984. // Offsets into the header array
  75985. var off_magic = 0;
  75986. var off_size = 1;
  75987. var off_flags = 2;
  75988. var off_height = 3;
  75989. var off_width = 4;
  75990. var off_mipmapCount = 7;
  75991. var off_pfFlags = 20;
  75992. var off_pfFourCC = 21;
  75993. var off_RGBbpp = 22;
  75994. var off_RMask = 23;
  75995. var off_GMask = 24;
  75996. var off_BMask = 25;
  75997. var off_AMask = 26;
  75998. // var off_caps1 = 27;
  75999. var off_caps2 = 28;
  76000. // var off_caps3 = 29;
  76001. // var off_caps4 = 30;
  76002. var off_dxgiFormat = 32;
  76003. ;
  76004. var DDSTools = /** @class */ (function () {
  76005. function DDSTools() {
  76006. }
  76007. DDSTools.GetDDSInfo = function (arrayBuffer) {
  76008. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  76009. var extendedHeader = new Int32Array(arrayBuffer, 0, headerLengthInt + 4);
  76010. var mipmapCount = 1;
  76011. if (header[off_flags] & DDSD_MIPMAPCOUNT) {
  76012. mipmapCount = Math.max(1, header[off_mipmapCount]);
  76013. }
  76014. var fourCC = header[off_pfFourCC];
  76015. var dxgiFormat = (fourCC === FOURCC_DX10) ? extendedHeader[off_dxgiFormat] : 0;
  76016. var textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  76017. switch (fourCC) {
  76018. case FOURCC_D3DFMT_R16G16B16A16F:
  76019. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  76020. break;
  76021. case FOURCC_D3DFMT_R32G32B32A32F:
  76022. textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  76023. break;
  76024. case FOURCC_DX10:
  76025. if (dxgiFormat === DXGI_FORMAT_R16G16B16A16_FLOAT) {
  76026. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  76027. break;
  76028. }
  76029. }
  76030. return {
  76031. width: header[off_width],
  76032. height: header[off_height],
  76033. mipmapCount: mipmapCount,
  76034. isFourCC: (header[off_pfFlags] & DDPF_FOURCC) === DDPF_FOURCC,
  76035. isRGB: (header[off_pfFlags] & DDPF_RGB) === DDPF_RGB,
  76036. isLuminance: (header[off_pfFlags] & DDPF_LUMINANCE) === DDPF_LUMINANCE,
  76037. isCube: (header[off_caps2] & DDSCAPS2_CUBEMAP) === DDSCAPS2_CUBEMAP,
  76038. isCompressed: (fourCC === FOURCC_DXT1 || fourCC === FOURCC_DXT3 || fourCC === FOURCC_DXT5),
  76039. dxgiFormat: dxgiFormat,
  76040. textureType: textureType
  76041. };
  76042. };
  76043. DDSTools._ToHalfFloat = function (value) {
  76044. if (!DDSTools._FloatView) {
  76045. DDSTools._FloatView = new Float32Array(1);
  76046. DDSTools._Int32View = new Int32Array(DDSTools._FloatView.buffer);
  76047. }
  76048. DDSTools._FloatView[0] = value;
  76049. var x = DDSTools._Int32View[0];
  76050. var bits = (x >> 16) & 0x8000; /* Get the sign */
  76051. var m = (x >> 12) & 0x07ff; /* Keep one extra bit for rounding */
  76052. var e = (x >> 23) & 0xff; /* Using int is faster here */
  76053. /* If zero, or denormal, or exponent underflows too much for a denormal
  76054. * half, return signed zero. */
  76055. if (e < 103) {
  76056. return bits;
  76057. }
  76058. /* If NaN, return NaN. If Inf or exponent overflow, return Inf. */
  76059. if (e > 142) {
  76060. bits |= 0x7c00;
  76061. /* If exponent was 0xff and one mantissa bit was set, it means NaN,
  76062. * not Inf, so make sure we set one mantissa bit too. */
  76063. bits |= ((e == 255) ? 0 : 1) && (x & 0x007fffff);
  76064. return bits;
  76065. }
  76066. /* If exponent underflows but not too much, return a denormal */
  76067. if (e < 113) {
  76068. m |= 0x0800;
  76069. /* Extra rounding may overflow and set mantissa to 0 and exponent
  76070. * to 1, which is OK. */
  76071. bits |= (m >> (114 - e)) + ((m >> (113 - e)) & 1);
  76072. return bits;
  76073. }
  76074. bits |= ((e - 112) << 10) | (m >> 1);
  76075. bits += m & 1;
  76076. return bits;
  76077. };
  76078. DDSTools._FromHalfFloat = function (value) {
  76079. var s = (value & 0x8000) >> 15;
  76080. var e = (value & 0x7C00) >> 10;
  76081. var f = value & 0x03FF;
  76082. if (e === 0) {
  76083. return (s ? -1 : 1) * Math.pow(2, -14) * (f / Math.pow(2, 10));
  76084. }
  76085. else if (e == 0x1F) {
  76086. return f ? NaN : ((s ? -1 : 1) * Infinity);
  76087. }
  76088. return (s ? -1 : 1) * Math.pow(2, e - 15) * (1 + (f / Math.pow(2, 10)));
  76089. };
  76090. DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  76091. var destArray = new Float32Array(dataLength);
  76092. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  76093. var index = 0;
  76094. for (var y = 0; y < height; y++) {
  76095. for (var x = 0; x < width; x++) {
  76096. var srcPos = (x + y * width) * 4;
  76097. destArray[index] = DDSTools._FromHalfFloat(srcData[srcPos]);
  76098. destArray[index + 1] = DDSTools._FromHalfFloat(srcData[srcPos + 1]);
  76099. destArray[index + 2] = DDSTools._FromHalfFloat(srcData[srcPos + 2]);
  76100. if (DDSTools.StoreLODInAlphaChannel) {
  76101. destArray[index + 3] = lod;
  76102. }
  76103. else {
  76104. destArray[index + 3] = DDSTools._FromHalfFloat(srcData[srcPos + 3]);
  76105. }
  76106. index += 4;
  76107. }
  76108. }
  76109. return destArray;
  76110. };
  76111. DDSTools._GetHalfFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  76112. if (DDSTools.StoreLODInAlphaChannel) {
  76113. var destArray = new Uint16Array(dataLength);
  76114. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  76115. var index = 0;
  76116. for (var y = 0; y < height; y++) {
  76117. for (var x = 0; x < width; x++) {
  76118. var srcPos = (x + y * width) * 4;
  76119. destArray[index] = srcData[srcPos];
  76120. destArray[index + 1] = srcData[srcPos + 1];
  76121. destArray[index + 2] = srcData[srcPos + 2];
  76122. destArray[index + 3] = DDSTools._ToHalfFloat(lod);
  76123. index += 4;
  76124. }
  76125. }
  76126. return destArray;
  76127. }
  76128. return new Uint16Array(arrayBuffer, dataOffset, dataLength);
  76129. };
  76130. DDSTools._GetFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  76131. if (DDSTools.StoreLODInAlphaChannel) {
  76132. var destArray = new Float32Array(dataLength);
  76133. var srcData = new Float32Array(arrayBuffer, dataOffset);
  76134. var index = 0;
  76135. for (var y = 0; y < height; y++) {
  76136. for (var x = 0; x < width; x++) {
  76137. var srcPos = (x + y * width) * 4;
  76138. destArray[index] = srcData[srcPos];
  76139. destArray[index + 1] = srcData[srcPos + 1];
  76140. destArray[index + 2] = srcData[srcPos + 2];
  76141. destArray[index + 3] = lod;
  76142. index += 4;
  76143. }
  76144. }
  76145. return destArray;
  76146. }
  76147. return new Float32Array(arrayBuffer, dataOffset, dataLength);
  76148. };
  76149. DDSTools._GetFloatAsUIntRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  76150. var destArray = new Uint8Array(dataLength);
  76151. var srcData = new Float32Array(arrayBuffer, dataOffset);
  76152. var index = 0;
  76153. for (var y = 0; y < height; y++) {
  76154. for (var x = 0; x < width; x++) {
  76155. var srcPos = (x + y * width) * 4;
  76156. destArray[index] = BABYLON.Scalar.Clamp(srcData[srcPos]) * 255;
  76157. destArray[index + 1] = BABYLON.Scalar.Clamp(srcData[srcPos + 1]) * 255;
  76158. destArray[index + 2] = BABYLON.Scalar.Clamp(srcData[srcPos + 2]) * 255;
  76159. if (DDSTools.StoreLODInAlphaChannel) {
  76160. destArray[index + 3] = lod;
  76161. }
  76162. else {
  76163. destArray[index + 3] = BABYLON.Scalar.Clamp(srcData[srcPos + 3]) * 255;
  76164. }
  76165. index += 4;
  76166. }
  76167. }
  76168. return destArray;
  76169. };
  76170. DDSTools._GetHalfFloatAsUIntRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  76171. var destArray = new Uint8Array(dataLength);
  76172. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  76173. var index = 0;
  76174. for (var y = 0; y < height; y++) {
  76175. for (var x = 0; x < width; x++) {
  76176. var srcPos = (x + y * width) * 4;
  76177. destArray[index] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos])) * 255;
  76178. destArray[index + 1] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 1])) * 255;
  76179. destArray[index + 2] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 2])) * 255;
  76180. if (DDSTools.StoreLODInAlphaChannel) {
  76181. destArray[index + 3] = lod;
  76182. }
  76183. else {
  76184. destArray[index + 3] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 3])) * 255;
  76185. }
  76186. index += 4;
  76187. }
  76188. }
  76189. return destArray;
  76190. };
  76191. DDSTools._GetRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset, aOffset) {
  76192. var byteArray = new Uint8Array(dataLength);
  76193. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  76194. var index = 0;
  76195. for (var y = 0; y < height; y++) {
  76196. for (var x = 0; x < width; x++) {
  76197. var srcPos = (x + y * width) * 4;
  76198. byteArray[index] = srcData[srcPos + rOffset];
  76199. byteArray[index + 1] = srcData[srcPos + gOffset];
  76200. byteArray[index + 2] = srcData[srcPos + bOffset];
  76201. byteArray[index + 3] = srcData[srcPos + aOffset];
  76202. index += 4;
  76203. }
  76204. }
  76205. return byteArray;
  76206. };
  76207. DDSTools._ExtractLongWordOrder = function (value) {
  76208. if (value === 0 || value === 255 || value === -16777216) {
  76209. return 0;
  76210. }
  76211. return 1 + DDSTools._ExtractLongWordOrder(value >> 8);
  76212. };
  76213. DDSTools._GetRGBArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset) {
  76214. var byteArray = new Uint8Array(dataLength);
  76215. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  76216. var index = 0;
  76217. for (var y = 0; y < height; y++) {
  76218. for (var x = 0; x < width; x++) {
  76219. var srcPos = (x + y * width) * 3;
  76220. byteArray[index] = srcData[srcPos + rOffset];
  76221. byteArray[index + 1] = srcData[srcPos + gOffset];
  76222. byteArray[index + 2] = srcData[srcPos + bOffset];
  76223. index += 3;
  76224. }
  76225. }
  76226. return byteArray;
  76227. };
  76228. DDSTools._GetLuminanceArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  76229. var byteArray = new Uint8Array(dataLength);
  76230. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  76231. var index = 0;
  76232. for (var y = 0; y < height; y++) {
  76233. for (var x = 0; x < width; x++) {
  76234. var srcPos = (x + y * width);
  76235. byteArray[index] = srcData[srcPos];
  76236. index++;
  76237. }
  76238. }
  76239. return byteArray;
  76240. };
  76241. DDSTools.UploadDDSLevels = function (engine, gl, arrayBuffer, info, loadMipmaps, faces, lodIndex, currentFace) {
  76242. if (lodIndex === void 0) { lodIndex = -1; }
  76243. var ext = engine.getCaps().s3tc;
  76244. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  76245. var fourCC, width, height, dataLength = 0, dataOffset;
  76246. var byteArray, mipmapCount, mip;
  76247. var internalFormat = 0;
  76248. var format = 0;
  76249. var blockBytes = 1;
  76250. if (header[off_magic] !== DDS_MAGIC) {
  76251. BABYLON.Tools.Error("Invalid magic number in DDS header");
  76252. return;
  76253. }
  76254. if (!info.isFourCC && !info.isRGB && !info.isLuminance) {
  76255. BABYLON.Tools.Error("Unsupported format, must contain a FourCC, RGB or LUMINANCE code");
  76256. return;
  76257. }
  76258. if (info.isCompressed && !ext) {
  76259. BABYLON.Tools.Error("Compressed textures are not supported on this platform.");
  76260. return;
  76261. }
  76262. var bpp = header[off_RGBbpp];
  76263. dataOffset = header[off_size] + 4;
  76264. var computeFormats = false;
  76265. if (info.isFourCC) {
  76266. fourCC = header[off_pfFourCC];
  76267. switch (fourCC) {
  76268. case FOURCC_DXT1:
  76269. blockBytes = 8;
  76270. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  76271. break;
  76272. case FOURCC_DXT3:
  76273. blockBytes = 16;
  76274. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  76275. break;
  76276. case FOURCC_DXT5:
  76277. blockBytes = 16;
  76278. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  76279. break;
  76280. case FOURCC_D3DFMT_R16G16B16A16F:
  76281. computeFormats = true;
  76282. break;
  76283. case FOURCC_D3DFMT_R32G32B32A32F:
  76284. computeFormats = true;
  76285. break;
  76286. case FOURCC_DX10:
  76287. // There is an additionnal header so dataOffset need to be changed
  76288. dataOffset += 5 * 4; // 5 uints
  76289. var supported = false;
  76290. switch (info.dxgiFormat) {
  76291. case DXGI_FORMAT_R16G16B16A16_FLOAT:
  76292. computeFormats = true;
  76293. supported = true;
  76294. break;
  76295. case DXGI_FORMAT_B8G8R8X8_UNORM:
  76296. info.isRGB = true;
  76297. info.isFourCC = false;
  76298. bpp = 32;
  76299. supported = true;
  76300. break;
  76301. }
  76302. if (supported) {
  76303. break;
  76304. }
  76305. default:
  76306. console.error("Unsupported FourCC code:", Int32ToFourCC(fourCC));
  76307. return;
  76308. }
  76309. }
  76310. var rOffset = DDSTools._ExtractLongWordOrder(header[off_RMask]);
  76311. var gOffset = DDSTools._ExtractLongWordOrder(header[off_GMask]);
  76312. var bOffset = DDSTools._ExtractLongWordOrder(header[off_BMask]);
  76313. var aOffset = DDSTools._ExtractLongWordOrder(header[off_AMask]);
  76314. if (computeFormats) {
  76315. format = engine._getWebGLTextureType(info.textureType);
  76316. internalFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  76317. }
  76318. mipmapCount = 1;
  76319. if (header[off_flags] & DDSD_MIPMAPCOUNT && loadMipmaps !== false) {
  76320. mipmapCount = Math.max(1, header[off_mipmapCount]);
  76321. }
  76322. for (var face = 0; face < faces; face++) {
  76323. var sampler = faces === 1 ? gl.TEXTURE_2D : (gl.TEXTURE_CUBE_MAP_POSITIVE_X + face + (currentFace ? currentFace : 0));
  76324. width = header[off_width];
  76325. height = header[off_height];
  76326. for (mip = 0; mip < mipmapCount; ++mip) {
  76327. if (lodIndex === -1 || lodIndex === mip) {
  76328. // In case of fixed LOD, if the lod has just been uploaded, early exit.
  76329. var i = (lodIndex === -1) ? mip : 0;
  76330. if (!info.isCompressed && info.isFourCC) {
  76331. dataLength = width * height * 4;
  76332. var floatArray = null;
  76333. if (engine.badOS || engine.badDesktopOS || (!engine.getCaps().textureHalfFloat && !engine.getCaps().textureFloat)) {
  76334. if (bpp === 128) {
  76335. floatArray = DDSTools._GetFloatAsUIntRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  76336. }
  76337. else if (bpp === 64) {
  76338. floatArray = DDSTools._GetHalfFloatAsUIntRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  76339. }
  76340. info.textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  76341. format = engine._getWebGLTextureType(info.textureType);
  76342. internalFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  76343. }
  76344. else {
  76345. if (bpp === 128) {
  76346. floatArray = DDSTools._GetFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  76347. }
  76348. else if (bpp === 64 && !engine.getCaps().textureHalfFloat) {
  76349. floatArray = DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  76350. info.textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  76351. format = engine._getWebGLTextureType(info.textureType);
  76352. internalFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  76353. }
  76354. else {
  76355. floatArray = DDSTools._GetHalfFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  76356. }
  76357. }
  76358. if (floatArray) {
  76359. engine._uploadDataToTexture(sampler, i, internalFormat, width, height, gl.RGBA, format, floatArray);
  76360. }
  76361. }
  76362. else if (info.isRGB) {
  76363. if (bpp === 24) {
  76364. dataLength = width * height * 3;
  76365. byteArray = DDSTools._GetRGBArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset);
  76366. engine._uploadDataToTexture(sampler, i, gl.RGB, width, height, gl.RGB, gl.UNSIGNED_BYTE, byteArray);
  76367. }
  76368. else {
  76369. dataLength = width * height * 4;
  76370. byteArray = DDSTools._GetRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset, aOffset);
  76371. engine._uploadDataToTexture(sampler, i, gl.RGBA, width, height, gl.RGBA, gl.UNSIGNED_BYTE, byteArray);
  76372. }
  76373. }
  76374. else if (info.isLuminance) {
  76375. var unpackAlignment = gl.getParameter(gl.UNPACK_ALIGNMENT);
  76376. var unpaddedRowSize = width;
  76377. var paddedRowSize = Math.floor((width + unpackAlignment - 1) / unpackAlignment) * unpackAlignment;
  76378. dataLength = paddedRowSize * (height - 1) + unpaddedRowSize;
  76379. byteArray = DDSTools._GetLuminanceArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  76380. engine._uploadDataToTexture(sampler, i, gl.LUMINANCE, width, height, gl.LUMINANCE, gl.UNSIGNED_BYTE, byteArray);
  76381. }
  76382. else {
  76383. dataLength = Math.max(4, width) / 4 * Math.max(4, height) / 4 * blockBytes;
  76384. byteArray = new Uint8Array(arrayBuffer, dataOffset, dataLength);
  76385. engine._uploadCompressedDataToTexture(sampler, i, internalFormat, width, height, byteArray);
  76386. }
  76387. }
  76388. dataOffset += bpp ? (width * height * (bpp / 8)) : dataLength;
  76389. width *= 0.5;
  76390. height *= 0.5;
  76391. width = Math.max(1.0, width);
  76392. height = Math.max(1.0, height);
  76393. }
  76394. if (currentFace !== undefined) {
  76395. // Loading a single face
  76396. break;
  76397. }
  76398. }
  76399. };
  76400. DDSTools.StoreLODInAlphaChannel = false;
  76401. return DDSTools;
  76402. }());
  76403. BABYLON.DDSTools = DDSTools;
  76404. })(BABYLON || (BABYLON = {}));
  76405. //# sourceMappingURL=babylon.dds.js.map
  76406. var BABYLON;
  76407. (function (BABYLON) {
  76408. /**
  76409. * for description see https://www.khronos.org/opengles/sdk/tools/KTX/
  76410. * for file layout see https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/
  76411. */
  76412. var KhronosTextureContainer = /** @class */ (function () {
  76413. /**
  76414. * @param {ArrayBuffer} arrayBuffer- contents of the KTX container file
  76415. * @param {number} facesExpected- should be either 1 or 6, based whether a cube texture or or
  76416. * @param {boolean} threeDExpected- provision for indicating that data should be a 3D texture, not implemented
  76417. * @param {boolean} textureArrayExpected- provision for indicating that data should be a texture array, not implemented
  76418. */
  76419. function KhronosTextureContainer(arrayBuffer, facesExpected, threeDExpected, textureArrayExpected) {
  76420. this.arrayBuffer = arrayBuffer;
  76421. // Test that it is a ktx formatted file, based on the first 12 bytes, character representation is:
  76422. // '�', 'K', 'T', 'X', ' ', '1', '1', '�', '\r', '\n', '\x1A', '\n'
  76423. // 0xAB, 0x4B, 0x54, 0x58, 0x20, 0x31, 0x31, 0xBB, 0x0D, 0x0A, 0x1A, 0x0A
  76424. var identifier = new Uint8Array(this.arrayBuffer, 0, 12);
  76425. if (identifier[0] !== 0xAB || identifier[1] !== 0x4B || identifier[2] !== 0x54 || identifier[3] !== 0x58 || identifier[4] !== 0x20 || identifier[5] !== 0x31 ||
  76426. identifier[6] !== 0x31 || identifier[7] !== 0xBB || identifier[8] !== 0x0D || identifier[9] !== 0x0A || identifier[10] !== 0x1A || identifier[11] !== 0x0A) {
  76427. BABYLON.Tools.Error("texture missing KTX identifier");
  76428. return;
  76429. }
  76430. // load the reset of the header in native 32 bit int
  76431. var header = new Int32Array(this.arrayBuffer, 12, 13);
  76432. // determine of the remaining header values are recorded in the opposite endianness & require conversion
  76433. var oppositeEndianess = header[0] === 0x01020304;
  76434. // read all the header elements in order they exist in the file, without modification (sans endainness)
  76435. this.glType = oppositeEndianess ? this.switchEndainness(header[1]) : header[1]; // must be 0 for compressed textures
  76436. this.glTypeSize = oppositeEndianess ? this.switchEndainness(header[2]) : header[2]; // must be 1 for compressed textures
  76437. this.glFormat = oppositeEndianess ? this.switchEndainness(header[3]) : header[3]; // must be 0 for compressed textures
  76438. this.glInternalFormat = oppositeEndianess ? this.switchEndainness(header[4]) : header[4]; // the value of arg passed to gl.compressedTexImage2D(,,x,,,,)
  76439. this.glBaseInternalFormat = oppositeEndianess ? this.switchEndainness(header[5]) : header[5]; // specify GL_RGB, GL_RGBA, GL_ALPHA, etc (un-compressed only)
  76440. this.pixelWidth = oppositeEndianess ? this.switchEndainness(header[6]) : header[6]; // level 0 value of arg passed to gl.compressedTexImage2D(,,,x,,,)
  76441. this.pixelHeight = oppositeEndianess ? this.switchEndainness(header[7]) : header[7]; // level 0 value of arg passed to gl.compressedTexImage2D(,,,,x,,)
  76442. this.pixelDepth = oppositeEndianess ? this.switchEndainness(header[8]) : header[8]; // level 0 value of arg passed to gl.compressedTexImage3D(,,,,,x,,)
  76443. this.numberOfArrayElements = oppositeEndianess ? this.switchEndainness(header[9]) : header[9]; // used for texture arrays
  76444. this.numberOfFaces = oppositeEndianess ? this.switchEndainness(header[10]) : header[10]; // used for cubemap textures, should either be 1 or 6
  76445. this.numberOfMipmapLevels = oppositeEndianess ? this.switchEndainness(header[11]) : header[11]; // number of levels; disregard possibility of 0 for compressed textures
  76446. this.bytesOfKeyValueData = oppositeEndianess ? this.switchEndainness(header[12]) : header[12]; // the amount of space after the header for meta-data
  76447. // Make sure we have a compressed type. Not only reduces work, but probably better to let dev know they are not compressing.
  76448. if (this.glType !== 0) {
  76449. BABYLON.Tools.Error("only compressed formats currently supported");
  76450. return;
  76451. }
  76452. else {
  76453. // value of zero is an indication to generate mipmaps @ runtime. Not usually allowed for compressed, so disregard.
  76454. this.numberOfMipmapLevels = Math.max(1, this.numberOfMipmapLevels);
  76455. }
  76456. if (this.pixelHeight === 0 || this.pixelDepth !== 0) {
  76457. BABYLON.Tools.Error("only 2D textures currently supported");
  76458. return;
  76459. }
  76460. if (this.numberOfArrayElements !== 0) {
  76461. BABYLON.Tools.Error("texture arrays not currently supported");
  76462. return;
  76463. }
  76464. if (this.numberOfFaces !== facesExpected) {
  76465. BABYLON.Tools.Error("number of faces expected" + facesExpected + ", but found " + this.numberOfFaces);
  76466. return;
  76467. }
  76468. // we now have a completely validated file, so could use existence of loadType as success
  76469. // would need to make this more elaborate & adjust checks above to support more than one load type
  76470. this.loadType = KhronosTextureContainer.COMPRESSED_2D;
  76471. }
  76472. // not as fast hardware based, but will probably never need to use
  76473. KhronosTextureContainer.prototype.switchEndainness = function (val) {
  76474. return ((val & 0xFF) << 24)
  76475. | ((val & 0xFF00) << 8)
  76476. | ((val >> 8) & 0xFF00)
  76477. | ((val >> 24) & 0xFF);
  76478. };
  76479. /**
  76480. * It is assumed that the texture has already been created & is currently bound
  76481. */
  76482. KhronosTextureContainer.prototype.uploadLevels = function (gl, loadMipmaps) {
  76483. switch (this.loadType) {
  76484. case KhronosTextureContainer.COMPRESSED_2D:
  76485. this._upload2DCompressedLevels(gl, loadMipmaps);
  76486. break;
  76487. case KhronosTextureContainer.TEX_2D:
  76488. case KhronosTextureContainer.COMPRESSED_3D:
  76489. case KhronosTextureContainer.TEX_3D:
  76490. }
  76491. };
  76492. KhronosTextureContainer.prototype._upload2DCompressedLevels = function (gl, loadMipmaps) {
  76493. // initialize width & height for level 1
  76494. var dataOffset = KhronosTextureContainer.HEADER_LEN + this.bytesOfKeyValueData;
  76495. var width = this.pixelWidth;
  76496. var height = this.pixelHeight;
  76497. var mipmapCount = loadMipmaps ? this.numberOfMipmapLevels : 1;
  76498. for (var level = 0; level < mipmapCount; level++) {
  76499. var imageSize = new Int32Array(this.arrayBuffer, dataOffset, 1)[0]; // size per face, since not supporting array cubemaps
  76500. for (var face = 0; face < this.numberOfFaces; face++) {
  76501. var sampler = this.numberOfFaces === 1 ? gl.TEXTURE_2D : (gl.TEXTURE_CUBE_MAP_POSITIVE_X + face);
  76502. var byteArray = new Uint8Array(this.arrayBuffer, dataOffset + 4, imageSize);
  76503. gl.compressedTexImage2D(sampler, level, this.glInternalFormat, width, height, 0, byteArray);
  76504. dataOffset += imageSize + 4; // size of the image + 4 for the imageSize field
  76505. dataOffset += 3 - ((imageSize + 3) % 4); // add padding for odd sized image
  76506. }
  76507. width = Math.max(1.0, width * 0.5);
  76508. height = Math.max(1.0, height * 0.5);
  76509. }
  76510. };
  76511. KhronosTextureContainer.HEADER_LEN = 12 + (13 * 4); // identifier + header elements (not including key value meta-data pairs)
  76512. // load types
  76513. KhronosTextureContainer.COMPRESSED_2D = 0; // uses a gl.compressedTexImage2D()
  76514. KhronosTextureContainer.COMPRESSED_3D = 1; // uses a gl.compressedTexImage3D()
  76515. KhronosTextureContainer.TEX_2D = 2; // uses a gl.texImage2D()
  76516. KhronosTextureContainer.TEX_3D = 3; // uses a gl.texImage3D()
  76517. return KhronosTextureContainer;
  76518. }());
  76519. BABYLON.KhronosTextureContainer = KhronosTextureContainer;
  76520. })(BABYLON || (BABYLON = {}));
  76521. //# sourceMappingURL=babylon.khronosTextureContainer.js.map
  76522. var BABYLON;
  76523. (function (BABYLON) {
  76524. var Debug = /** @class */ (function () {
  76525. function Debug() {
  76526. }
  76527. Debug.AxesViewer = /** @class */ (function () {
  76528. function AxesViewer(scene, scaleLines) {
  76529. if (scaleLines === void 0) { scaleLines = 1; }
  76530. this._xline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  76531. this._yline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  76532. this._zline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  76533. this.scaleLines = 1;
  76534. this.scaleLines = scaleLines;
  76535. this._xmesh = BABYLON.Mesh.CreateLines("xline", this._xline, scene, true);
  76536. this._ymesh = BABYLON.Mesh.CreateLines("yline", this._yline, scene, true);
  76537. this._zmesh = BABYLON.Mesh.CreateLines("zline", this._zline, scene, true);
  76538. this._xmesh.renderingGroupId = 2;
  76539. this._ymesh.renderingGroupId = 2;
  76540. this._zmesh.renderingGroupId = 2;
  76541. this._xmesh.material.checkReadyOnlyOnce = true;
  76542. this._xmesh.color = new BABYLON.Color3(1, 0, 0);
  76543. this._ymesh.material.checkReadyOnlyOnce = true;
  76544. this._ymesh.color = new BABYLON.Color3(0, 1, 0);
  76545. this._zmesh.material.checkReadyOnlyOnce = true;
  76546. this._zmesh.color = new BABYLON.Color3(0, 0, 1);
  76547. this.scene = scene;
  76548. }
  76549. AxesViewer.prototype.update = function (position, xaxis, yaxis, zaxis) {
  76550. var scaleLines = this.scaleLines;
  76551. if (this._xmesh) {
  76552. this._xmesh.position.copyFrom(position);
  76553. }
  76554. if (this._ymesh) {
  76555. this._ymesh.position.copyFrom(position);
  76556. }
  76557. if (this._zmesh) {
  76558. this._zmesh.position.copyFrom(position);
  76559. }
  76560. var point2 = this._xline[1];
  76561. point2.x = xaxis.x * scaleLines;
  76562. point2.y = xaxis.y * scaleLines;
  76563. point2.z = xaxis.z * scaleLines;
  76564. BABYLON.Mesh.CreateLines("", this._xline, null, false, this._xmesh);
  76565. point2 = this._yline[1];
  76566. point2.x = yaxis.x * scaleLines;
  76567. point2.y = yaxis.y * scaleLines;
  76568. point2.z = yaxis.z * scaleLines;
  76569. BABYLON.Mesh.CreateLines("", this._yline, null, false, this._ymesh);
  76570. point2 = this._zline[1];
  76571. point2.x = zaxis.x * scaleLines;
  76572. point2.y = zaxis.y * scaleLines;
  76573. point2.z = zaxis.z * scaleLines;
  76574. BABYLON.Mesh.CreateLines("", this._zline, null, false, this._zmesh);
  76575. };
  76576. AxesViewer.prototype.dispose = function () {
  76577. if (this._xmesh) {
  76578. this._xmesh.dispose();
  76579. }
  76580. if (this._ymesh) {
  76581. this._ymesh.dispose();
  76582. }
  76583. if (this._zmesh) {
  76584. this._zmesh.dispose();
  76585. }
  76586. this._xmesh = null;
  76587. this._ymesh = null;
  76588. this._zmesh = null;
  76589. this.scene = null;
  76590. };
  76591. return AxesViewer;
  76592. }());
  76593. Debug.BoneAxesViewer = /** @class */ (function (_super) {
  76594. __extends(BoneAxesViewer, _super);
  76595. function BoneAxesViewer(scene, bone, mesh, scaleLines) {
  76596. if (scaleLines === void 0) { scaleLines = 1; }
  76597. var _this = _super.call(this, scene, scaleLines) || this;
  76598. _this.pos = BABYLON.Vector3.Zero();
  76599. _this.xaxis = BABYLON.Vector3.Zero();
  76600. _this.yaxis = BABYLON.Vector3.Zero();
  76601. _this.zaxis = BABYLON.Vector3.Zero();
  76602. _this.mesh = mesh;
  76603. _this.bone = bone;
  76604. return _this;
  76605. }
  76606. BoneAxesViewer.prototype.update = function () {
  76607. if (!this.mesh || !this.bone) {
  76608. return;
  76609. }
  76610. var bone = this.bone;
  76611. bone.getAbsolutePositionToRef(this.mesh, this.pos);
  76612. bone.getDirectionToRef(BABYLON.Axis.X, this.mesh, this.xaxis);
  76613. bone.getDirectionToRef(BABYLON.Axis.Y, this.mesh, this.yaxis);
  76614. bone.getDirectionToRef(BABYLON.Axis.Z, this.mesh, this.zaxis);
  76615. _super.prototype.update.call(this, this.pos, this.xaxis, this.yaxis, this.zaxis);
  76616. };
  76617. BoneAxesViewer.prototype.dispose = function () {
  76618. if (this.mesh) {
  76619. this.mesh = null;
  76620. this.bone = null;
  76621. _super.prototype.dispose.call(this);
  76622. }
  76623. };
  76624. return BoneAxesViewer;
  76625. }(Debug.AxesViewer));
  76626. Debug.PhysicsViewer = /** @class */ (function () {
  76627. function PhysicsViewer(scene) {
  76628. this._impostors = [];
  76629. this._meshes = [];
  76630. this._numMeshes = 0;
  76631. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  76632. var physicEngine = this._scene.getPhysicsEngine();
  76633. if (physicEngine) {
  76634. this._physicsEnginePlugin = physicEngine.getPhysicsPlugin();
  76635. }
  76636. }
  76637. PhysicsViewer.prototype._updateDebugMeshes = function () {
  76638. var plugin = this._physicsEnginePlugin;
  76639. for (var i = 0; i < this._numMeshes; i++) {
  76640. var impostor = this._impostors[i];
  76641. if (!impostor) {
  76642. continue;
  76643. }
  76644. if (impostor.isDisposed) {
  76645. this.hideImpostor(this._impostors[i--]);
  76646. }
  76647. else {
  76648. var mesh = this._meshes[i];
  76649. if (mesh && plugin) {
  76650. plugin.syncMeshWithImpostor(mesh, impostor);
  76651. }
  76652. }
  76653. }
  76654. };
  76655. PhysicsViewer.prototype.showImpostor = function (impostor) {
  76656. if (!this._scene) {
  76657. return;
  76658. }
  76659. for (var i = 0; i < this._numMeshes; i++) {
  76660. if (this._impostors[i] == impostor) {
  76661. return;
  76662. }
  76663. }
  76664. var debugMesh = this._getDebugMesh(impostor, this._scene);
  76665. if (debugMesh) {
  76666. this._impostors[this._numMeshes] = impostor;
  76667. this._meshes[this._numMeshes] = debugMesh;
  76668. if (this._numMeshes === 0) {
  76669. this._renderFunction = this._updateDebugMeshes.bind(this);
  76670. this._scene.registerBeforeRender(this._renderFunction);
  76671. }
  76672. this._numMeshes++;
  76673. }
  76674. };
  76675. PhysicsViewer.prototype.hideImpostor = function (impostor) {
  76676. if (!impostor || !this._scene) {
  76677. return;
  76678. }
  76679. var removed = false;
  76680. for (var i = 0; i < this._numMeshes; i++) {
  76681. if (this._impostors[i] == impostor) {
  76682. var mesh = this._meshes[i];
  76683. if (!mesh) {
  76684. continue;
  76685. }
  76686. this._scene.removeMesh(mesh);
  76687. mesh.dispose();
  76688. this._numMeshes--;
  76689. if (this._numMeshes > 0) {
  76690. this._meshes[i] = this._meshes[this._numMeshes];
  76691. this._impostors[i] = this._impostors[this._numMeshes];
  76692. this._meshes[this._numMeshes] = null;
  76693. this._impostors[this._numMeshes] = null;
  76694. }
  76695. else {
  76696. this._meshes[0] = null;
  76697. this._impostors[0] = null;
  76698. }
  76699. removed = true;
  76700. break;
  76701. }
  76702. }
  76703. if (removed && this._numMeshes === 0) {
  76704. this._scene.unregisterBeforeRender(this._renderFunction);
  76705. }
  76706. };
  76707. PhysicsViewer.prototype._getDebugMaterial = function (scene) {
  76708. if (!this._debugMaterial) {
  76709. this._debugMaterial = new BABYLON.StandardMaterial('', scene);
  76710. this._debugMaterial.wireframe = true;
  76711. }
  76712. return this._debugMaterial;
  76713. };
  76714. PhysicsViewer.prototype._getDebugBoxMesh = function (scene) {
  76715. if (!this._debugBoxMesh) {
  76716. this._debugBoxMesh = BABYLON.MeshBuilder.CreateBox('physicsBodyBoxViewMesh', { size: 1 }, scene);
  76717. this._debugBoxMesh.renderingGroupId = 1;
  76718. this._debugBoxMesh.rotationQuaternion = BABYLON.Quaternion.Identity();
  76719. this._debugBoxMesh.material = this._getDebugMaterial(scene);
  76720. scene.removeMesh(this._debugBoxMesh);
  76721. }
  76722. return this._debugBoxMesh.createInstance('physicsBodyBoxViewInstance');
  76723. };
  76724. PhysicsViewer.prototype._getDebugSphereMesh = function (scene) {
  76725. if (!this._debugSphereMesh) {
  76726. this._debugSphereMesh = BABYLON.MeshBuilder.CreateSphere('physicsBodySphereViewMesh', { diameter: 1 }, scene);
  76727. this._debugSphereMesh.renderingGroupId = 1;
  76728. this._debugSphereMesh.rotationQuaternion = BABYLON.Quaternion.Identity();
  76729. this._debugSphereMesh.material = this._getDebugMaterial(scene);
  76730. scene.removeMesh(this._debugSphereMesh);
  76731. }
  76732. return this._debugSphereMesh.createInstance('physicsBodyBoxViewInstance');
  76733. };
  76734. PhysicsViewer.prototype._getDebugMesh = function (impostor, scene) {
  76735. var mesh = null;
  76736. if (impostor.type == BABYLON.PhysicsImpostor.BoxImpostor) {
  76737. mesh = this._getDebugBoxMesh(scene);
  76738. impostor.getBoxSizeToRef(mesh.scaling);
  76739. }
  76740. else if (impostor.type == BABYLON.PhysicsImpostor.SphereImpostor) {
  76741. mesh = this._getDebugSphereMesh(scene);
  76742. var radius = impostor.getRadius();
  76743. mesh.scaling.x = radius * 2;
  76744. mesh.scaling.y = radius * 2;
  76745. mesh.scaling.z = radius * 2;
  76746. }
  76747. return mesh;
  76748. };
  76749. PhysicsViewer.prototype.dispose = function () {
  76750. for (var i = 0; i < this._numMeshes; i++) {
  76751. this.hideImpostor(this._impostors[i]);
  76752. }
  76753. if (this._debugBoxMesh) {
  76754. this._debugBoxMesh.dispose();
  76755. }
  76756. if (this._debugSphereMesh) {
  76757. this._debugSphereMesh.dispose();
  76758. }
  76759. if (this._debugMaterial) {
  76760. this._debugMaterial.dispose();
  76761. }
  76762. this._impostors.length = 0;
  76763. this._scene = null;
  76764. this._physicsEnginePlugin = null;
  76765. };
  76766. return PhysicsViewer;
  76767. }());
  76768. Debug.SkeletonViewer = /** @class */ (function () {
  76769. function SkeletonViewer(skeleton, mesh, scene, autoUpdateBonesMatrices, renderingGroupId) {
  76770. if (autoUpdateBonesMatrices === void 0) { autoUpdateBonesMatrices = true; }
  76771. if (renderingGroupId === void 0) { renderingGroupId = 1; }
  76772. this.skeleton = skeleton;
  76773. this.mesh = mesh;
  76774. this.autoUpdateBonesMatrices = autoUpdateBonesMatrices;
  76775. this.renderingGroupId = renderingGroupId;
  76776. this.color = BABYLON.Color3.White();
  76777. this._debugLines = new Array();
  76778. this._isEnabled = false;
  76779. this._scene = scene;
  76780. this.update();
  76781. this._renderFunction = this.update.bind(this);
  76782. }
  76783. Object.defineProperty(SkeletonViewer.prototype, "isEnabled", {
  76784. get: function () {
  76785. return this._isEnabled;
  76786. },
  76787. set: function (value) {
  76788. if (this._isEnabled === value) {
  76789. return;
  76790. }
  76791. this._isEnabled = value;
  76792. if (value) {
  76793. this._scene.registerBeforeRender(this._renderFunction);
  76794. }
  76795. else {
  76796. this._scene.unregisterBeforeRender(this._renderFunction);
  76797. }
  76798. },
  76799. enumerable: true,
  76800. configurable: true
  76801. });
  76802. SkeletonViewer.prototype._getBonePosition = function (position, bone, meshMat, x, y, z) {
  76803. if (x === void 0) { x = 0; }
  76804. if (y === void 0) { y = 0; }
  76805. if (z === void 0) { z = 0; }
  76806. var tmat = BABYLON.Tmp.Matrix[0];
  76807. var parentBone = bone.getParent();
  76808. tmat.copyFrom(bone.getLocalMatrix());
  76809. if (x !== 0 || y !== 0 || z !== 0) {
  76810. var tmat2 = BABYLON.Tmp.Matrix[1];
  76811. BABYLON.Matrix.IdentityToRef(tmat2);
  76812. tmat2.m[12] = x;
  76813. tmat2.m[13] = y;
  76814. tmat2.m[14] = z;
  76815. tmat2.multiplyToRef(tmat, tmat);
  76816. }
  76817. if (parentBone) {
  76818. tmat.multiplyToRef(parentBone.getAbsoluteTransform(), tmat);
  76819. }
  76820. tmat.multiplyToRef(meshMat, tmat);
  76821. position.x = tmat.m[12];
  76822. position.y = tmat.m[13];
  76823. position.z = tmat.m[14];
  76824. };
  76825. SkeletonViewer.prototype._getLinesForBonesWithLength = function (bones, meshMat) {
  76826. var len = bones.length;
  76827. var meshPos = this.mesh.position;
  76828. for (var i = 0; i < len; i++) {
  76829. var bone = bones[i];
  76830. var points = this._debugLines[i];
  76831. if (!points) {
  76832. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  76833. this._debugLines[i] = points;
  76834. }
  76835. this._getBonePosition(points[0], bone, meshMat);
  76836. this._getBonePosition(points[1], bone, meshMat, 0, bone.length, 0);
  76837. points[0].subtractInPlace(meshPos);
  76838. points[1].subtractInPlace(meshPos);
  76839. }
  76840. };
  76841. SkeletonViewer.prototype._getLinesForBonesNoLength = function (bones, meshMat) {
  76842. var len = bones.length;
  76843. var boneNum = 0;
  76844. var meshPos = this.mesh.position;
  76845. for (var i = len - 1; i >= 0; i--) {
  76846. var childBone = bones[i];
  76847. var parentBone = childBone.getParent();
  76848. if (!parentBone) {
  76849. continue;
  76850. }
  76851. var points = this._debugLines[boneNum];
  76852. if (!points) {
  76853. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  76854. this._debugLines[boneNum] = points;
  76855. }
  76856. childBone.getAbsolutePositionToRef(this.mesh, points[0]);
  76857. parentBone.getAbsolutePositionToRef(this.mesh, points[1]);
  76858. points[0].subtractInPlace(meshPos);
  76859. points[1].subtractInPlace(meshPos);
  76860. boneNum++;
  76861. }
  76862. };
  76863. SkeletonViewer.prototype.update = function () {
  76864. if (this.autoUpdateBonesMatrices) {
  76865. this.skeleton.computeAbsoluteTransforms();
  76866. }
  76867. if (this.skeleton.bones[0].length === undefined) {
  76868. this._getLinesForBonesNoLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  76869. }
  76870. else {
  76871. this._getLinesForBonesWithLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  76872. }
  76873. if (!this._debugMesh) {
  76874. this._debugMesh = BABYLON.MeshBuilder.CreateLineSystem("", { lines: this._debugLines, updatable: true, instance: null }, this._scene);
  76875. this._debugMesh.renderingGroupId = this.renderingGroupId;
  76876. }
  76877. else {
  76878. BABYLON.MeshBuilder.CreateLineSystem("", { lines: this._debugLines, updatable: true, instance: this._debugMesh }, this._scene);
  76879. }
  76880. this._debugMesh.position.copyFrom(this.mesh.position);
  76881. this._debugMesh.color = this.color;
  76882. };
  76883. SkeletonViewer.prototype.dispose = function () {
  76884. if (this._debugMesh) {
  76885. this.isEnabled = false;
  76886. this._debugMesh.dispose();
  76887. this._debugMesh = null;
  76888. }
  76889. };
  76890. return SkeletonViewer;
  76891. }());
  76892. return Debug;
  76893. }());
  76894. BABYLON.Debug = Debug;
  76895. })(BABYLON || (BABYLON = {}));
  76896. //# sourceMappingURL=babylon.debugModules.js.map
  76897. var BABYLON;
  76898. (function (BABYLON) {
  76899. var RayHelper = /** @class */ (function () {
  76900. function RayHelper(ray) {
  76901. this.ray = ray;
  76902. }
  76903. RayHelper.CreateAndShow = function (ray, scene, color) {
  76904. var helper = new RayHelper(ray);
  76905. helper.show(scene, color);
  76906. return helper;
  76907. };
  76908. RayHelper.prototype.show = function (scene, color) {
  76909. if (!this._renderFunction && this.ray) {
  76910. var ray = this.ray;
  76911. this._renderFunction = this._render.bind(this);
  76912. this._scene = scene;
  76913. this._renderPoints = [ray.origin, ray.origin.add(ray.direction.scale(ray.length))];
  76914. this._renderLine = BABYLON.Mesh.CreateLines("ray", this._renderPoints, scene, true);
  76915. if (this._renderFunction) {
  76916. this._scene.registerBeforeRender(this._renderFunction);
  76917. }
  76918. }
  76919. if (color && this._renderLine) {
  76920. this._renderLine.color.copyFrom(color);
  76921. }
  76922. };
  76923. RayHelper.prototype.hide = function () {
  76924. if (this._renderFunction && this._scene) {
  76925. this._scene.unregisterBeforeRender(this._renderFunction);
  76926. this._scene = null;
  76927. this._renderFunction = null;
  76928. if (this._renderLine) {
  76929. this._renderLine.dispose();
  76930. this._renderLine = null;
  76931. }
  76932. this._renderPoints = [];
  76933. }
  76934. };
  76935. RayHelper.prototype._render = function () {
  76936. var ray = this.ray;
  76937. if (!ray) {
  76938. return;
  76939. }
  76940. var point = this._renderPoints[1];
  76941. var len = Math.min(ray.length, 1000000);
  76942. point.copyFrom(ray.direction);
  76943. point.scaleInPlace(len);
  76944. point.addInPlace(ray.origin);
  76945. BABYLON.Mesh.CreateLines("ray", this._renderPoints, this._scene, true, this._renderLine);
  76946. };
  76947. RayHelper.prototype.attachToMesh = function (mesh, meshSpaceDirection, meshSpaceOrigin, length) {
  76948. this._attachedToMesh = mesh;
  76949. var ray = this.ray;
  76950. if (!ray) {
  76951. return;
  76952. }
  76953. if (!ray.direction) {
  76954. ray.direction = BABYLON.Vector3.Zero();
  76955. }
  76956. if (!ray.origin) {
  76957. ray.origin = BABYLON.Vector3.Zero();
  76958. }
  76959. if (length) {
  76960. ray.length = length;
  76961. }
  76962. if (!meshSpaceOrigin) {
  76963. meshSpaceOrigin = BABYLON.Vector3.Zero();
  76964. }
  76965. if (!meshSpaceDirection) {
  76966. // -1 so that this will work with Mesh.lookAt
  76967. meshSpaceDirection = new BABYLON.Vector3(0, 0, -1);
  76968. }
  76969. if (!this._meshSpaceDirection) {
  76970. this._meshSpaceDirection = meshSpaceDirection.clone();
  76971. this._meshSpaceOrigin = meshSpaceOrigin.clone();
  76972. }
  76973. else {
  76974. this._meshSpaceDirection.copyFrom(meshSpaceDirection);
  76975. this._meshSpaceOrigin.copyFrom(meshSpaceOrigin);
  76976. }
  76977. if (!this._updateToMeshFunction) {
  76978. this._updateToMeshFunction = this._updateToMesh.bind(this);
  76979. this._attachedToMesh.getScene().registerBeforeRender(this._updateToMeshFunction);
  76980. }
  76981. this._updateToMesh();
  76982. };
  76983. RayHelper.prototype.detachFromMesh = function () {
  76984. if (this._attachedToMesh) {
  76985. if (this._updateToMeshFunction) {
  76986. this._attachedToMesh.getScene().unregisterBeforeRender(this._updateToMeshFunction);
  76987. }
  76988. this._attachedToMesh = null;
  76989. this._updateToMeshFunction = null;
  76990. }
  76991. };
  76992. RayHelper.prototype._updateToMesh = function () {
  76993. var ray = this.ray;
  76994. if (!this._attachedToMesh || !ray) {
  76995. return;
  76996. }
  76997. if (this._attachedToMesh._isDisposed) {
  76998. this.detachFromMesh();
  76999. return;
  77000. }
  77001. this._attachedToMesh.getDirectionToRef(this._meshSpaceDirection, ray.direction);
  77002. BABYLON.Vector3.TransformCoordinatesToRef(this._meshSpaceOrigin, this._attachedToMesh.getWorldMatrix(), ray.origin);
  77003. };
  77004. RayHelper.prototype.dispose = function () {
  77005. this.hide();
  77006. this.detachFromMesh();
  77007. this.ray = null;
  77008. };
  77009. return RayHelper;
  77010. }());
  77011. BABYLON.RayHelper = RayHelper;
  77012. })(BABYLON || (BABYLON = {}));
  77013. //# sourceMappingURL=babylon.rayHelper.js.map
  77014. var BABYLON;
  77015. (function (BABYLON) {
  77016. // load the inspector using require, if not present in the global namespace.
  77017. var DebugLayer = /** @class */ (function () {
  77018. function DebugLayer(scene) {
  77019. this.BJSINSPECTOR = typeof INSPECTOR !== 'undefined' ? INSPECTOR : undefined;
  77020. this._scene = scene;
  77021. // load inspector using require, if it doesn't exist on the global namespace.
  77022. }
  77023. /** Creates the inspector window. */
  77024. DebugLayer.prototype._createInspector = function (config) {
  77025. if (config === void 0) { config = {}; }
  77026. var popup = config.popup || false;
  77027. var initialTab = config.initialTab || 0;
  77028. var parentElement = config.parentElement || null;
  77029. if (!this._inspector) {
  77030. this.BJSINSPECTOR = this.BJSINSPECTOR || typeof INSPECTOR !== 'undefined' ? INSPECTOR : undefined;
  77031. this._inspector = new this.BJSINSPECTOR.Inspector(this._scene, popup, initialTab, parentElement, config.newColors);
  77032. } // else nothing to do,; instance is already existing
  77033. };
  77034. DebugLayer.prototype.isVisible = function () {
  77035. if (!this._inspector) {
  77036. return false;
  77037. }
  77038. return true;
  77039. };
  77040. DebugLayer.prototype.hide = function () {
  77041. if (this._inspector) {
  77042. try {
  77043. this._inspector.dispose();
  77044. }
  77045. catch (e) {
  77046. // If the inspector has been removed directly from the inspector tool
  77047. }
  77048. this._inspector = null;
  77049. }
  77050. };
  77051. DebugLayer.prototype.show = function (config) {
  77052. if (config === void 0) { config = {}; }
  77053. if (typeof this.BJSINSPECTOR == 'undefined') {
  77054. // Load inspector and add it to the DOM
  77055. BABYLON.Tools.LoadScript(DebugLayer.InspectorURL, this._createInspector.bind(this, config));
  77056. }
  77057. else {
  77058. // Otherwise creates the inspector
  77059. this._createInspector(config);
  77060. }
  77061. };
  77062. DebugLayer.InspectorURL = 'https://preview.babylonjs.com/inspector/babylon.inspector.bundle.js';
  77063. return DebugLayer;
  77064. }());
  77065. BABYLON.DebugLayer = DebugLayer;
  77066. })(BABYLON || (BABYLON = {}));
  77067. //# sourceMappingURL=babylon.debugLayer.js.map
  77068. var BABYLON;
  77069. (function (BABYLON) {
  77070. var BoundingBoxRenderer = /** @class */ (function () {
  77071. function BoundingBoxRenderer(scene) {
  77072. this.frontColor = new BABYLON.Color3(1, 1, 1);
  77073. this.backColor = new BABYLON.Color3(0.1, 0.1, 0.1);
  77074. this.showBackLines = true;
  77075. this.renderList = new BABYLON.SmartArray(32);
  77076. this._vertexBuffers = {};
  77077. this._scene = scene;
  77078. }
  77079. BoundingBoxRenderer.prototype._prepareRessources = function () {
  77080. if (this._colorShader) {
  77081. return;
  77082. }
  77083. this._colorShader = new BABYLON.ShaderMaterial("colorShader", this._scene, "color", {
  77084. attributes: [BABYLON.VertexBuffer.PositionKind],
  77085. uniforms: ["world", "viewProjection", "color"]
  77086. });
  77087. var engine = this._scene.getEngine();
  77088. var boxdata = BABYLON.VertexData.CreateBox({ size: 1.0 });
  77089. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, boxdata.positions, BABYLON.VertexBuffer.PositionKind, false);
  77090. this._createIndexBuffer();
  77091. };
  77092. BoundingBoxRenderer.prototype._createIndexBuffer = function () {
  77093. var engine = this._scene.getEngine();
  77094. 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]);
  77095. };
  77096. BoundingBoxRenderer.prototype._rebuild = function () {
  77097. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  77098. if (vb) {
  77099. vb._rebuild();
  77100. }
  77101. this._createIndexBuffer();
  77102. };
  77103. BoundingBoxRenderer.prototype.reset = function () {
  77104. this.renderList.reset();
  77105. };
  77106. BoundingBoxRenderer.prototype.render = function () {
  77107. if (this.renderList.length === 0) {
  77108. return;
  77109. }
  77110. this._prepareRessources();
  77111. if (!this._colorShader.isReady()) {
  77112. return;
  77113. }
  77114. var engine = this._scene.getEngine();
  77115. engine.setDepthWrite(false);
  77116. this._colorShader._preBind();
  77117. for (var boundingBoxIndex = 0; boundingBoxIndex < this.renderList.length; boundingBoxIndex++) {
  77118. var boundingBox = this.renderList.data[boundingBoxIndex];
  77119. var min = boundingBox.minimum;
  77120. var max = boundingBox.maximum;
  77121. var diff = max.subtract(min);
  77122. var median = min.add(diff.scale(0.5));
  77123. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  77124. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  77125. .multiply(boundingBox.getWorldMatrix());
  77126. // VBOs
  77127. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._colorShader.getEffect());
  77128. if (this.showBackLines) {
  77129. // Back
  77130. engine.setDepthFunctionToGreaterOrEqual();
  77131. this._scene.resetCachedMaterial();
  77132. this._colorShader.setColor4("color", this.backColor.toColor4());
  77133. this._colorShader.bind(worldMatrix);
  77134. // Draw order
  77135. engine.drawElementsType(BABYLON.Material.LineListDrawMode, 0, 24);
  77136. }
  77137. // Front
  77138. engine.setDepthFunctionToLess();
  77139. this._scene.resetCachedMaterial();
  77140. this._colorShader.setColor4("color", this.frontColor.toColor4());
  77141. this._colorShader.bind(worldMatrix);
  77142. // Draw order
  77143. engine.drawElementsType(BABYLON.Material.LineListDrawMode, 0, 24);
  77144. }
  77145. this._colorShader.unbind();
  77146. engine.setDepthFunctionToLessOrEqual();
  77147. engine.setDepthWrite(true);
  77148. };
  77149. BoundingBoxRenderer.prototype.renderOcclusionBoundingBox = function (mesh) {
  77150. this._prepareRessources();
  77151. if (!this._colorShader.isReady() || !mesh._boundingInfo) {
  77152. return;
  77153. }
  77154. var engine = this._scene.getEngine();
  77155. engine.setDepthWrite(false);
  77156. engine.setColorWrite(false);
  77157. this._colorShader._preBind();
  77158. var boundingBox = mesh._boundingInfo.boundingBox;
  77159. var min = boundingBox.minimum;
  77160. var max = boundingBox.maximum;
  77161. var diff = max.subtract(min);
  77162. var median = min.add(diff.scale(0.5));
  77163. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  77164. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  77165. .multiply(boundingBox.getWorldMatrix());
  77166. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._colorShader.getEffect());
  77167. engine.setDepthFunctionToLess();
  77168. this._scene.resetCachedMaterial();
  77169. this._colorShader.bind(worldMatrix);
  77170. engine.drawElementsType(BABYLON.Material.LineListDrawMode, 0, 24);
  77171. this._colorShader.unbind();
  77172. engine.setDepthFunctionToLessOrEqual();
  77173. engine.setDepthWrite(true);
  77174. engine.setColorWrite(true);
  77175. };
  77176. BoundingBoxRenderer.prototype.dispose = function () {
  77177. if (!this._colorShader) {
  77178. return;
  77179. }
  77180. this.renderList.dispose();
  77181. this._colorShader.dispose();
  77182. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  77183. if (buffer) {
  77184. buffer.dispose();
  77185. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  77186. }
  77187. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  77188. };
  77189. return BoundingBoxRenderer;
  77190. }());
  77191. BABYLON.BoundingBoxRenderer = BoundingBoxRenderer;
  77192. })(BABYLON || (BABYLON = {}));
  77193. //# sourceMappingURL=babylon.boundingBoxRenderer.js.map
  77194. var BABYLON;
  77195. (function (BABYLON) {
  77196. var MorphTarget = /** @class */ (function () {
  77197. function MorphTarget(name, influence) {
  77198. if (influence === void 0) { influence = 0; }
  77199. this.name = name;
  77200. this.animations = new Array();
  77201. this._positions = null;
  77202. this._normals = null;
  77203. this._tangents = null;
  77204. this.onInfluenceChanged = new BABYLON.Observable();
  77205. this.influence = influence;
  77206. }
  77207. Object.defineProperty(MorphTarget.prototype, "influence", {
  77208. get: function () {
  77209. return this._influence;
  77210. },
  77211. set: function (influence) {
  77212. if (this._influence === influence) {
  77213. return;
  77214. }
  77215. var previous = this._influence;
  77216. this._influence = influence;
  77217. if (this.onInfluenceChanged.hasObservers) {
  77218. this.onInfluenceChanged.notifyObservers(previous === 0 || influence === 0);
  77219. }
  77220. },
  77221. enumerable: true,
  77222. configurable: true
  77223. });
  77224. Object.defineProperty(MorphTarget.prototype, "hasPositions", {
  77225. get: function () {
  77226. return !!this._positions;
  77227. },
  77228. enumerable: true,
  77229. configurable: true
  77230. });
  77231. Object.defineProperty(MorphTarget.prototype, "hasNormals", {
  77232. get: function () {
  77233. return !!this._normals;
  77234. },
  77235. enumerable: true,
  77236. configurable: true
  77237. });
  77238. Object.defineProperty(MorphTarget.prototype, "hasTangents", {
  77239. get: function () {
  77240. return !!this._tangents;
  77241. },
  77242. enumerable: true,
  77243. configurable: true
  77244. });
  77245. MorphTarget.prototype.setPositions = function (data) {
  77246. this._positions = data;
  77247. };
  77248. MorphTarget.prototype.getPositions = function () {
  77249. return this._positions;
  77250. };
  77251. MorphTarget.prototype.setNormals = function (data) {
  77252. this._normals = data;
  77253. };
  77254. MorphTarget.prototype.getNormals = function () {
  77255. return this._normals;
  77256. };
  77257. MorphTarget.prototype.setTangents = function (data) {
  77258. this._tangents = data;
  77259. };
  77260. MorphTarget.prototype.getTangents = function () {
  77261. return this._tangents;
  77262. };
  77263. /**
  77264. * Serializes the current target into a Serialization object.
  77265. * Returns the serialized object.
  77266. */
  77267. MorphTarget.prototype.serialize = function () {
  77268. var serializationObject = {};
  77269. serializationObject.name = this.name;
  77270. serializationObject.influence = this.influence;
  77271. serializationObject.positions = Array.prototype.slice.call(this.getPositions());
  77272. if (this.hasNormals) {
  77273. serializationObject.normals = Array.prototype.slice.call(this.getNormals());
  77274. }
  77275. if (this.hasTangents) {
  77276. serializationObject.tangents = Array.prototype.slice.call(this.getTangents());
  77277. }
  77278. // Animations
  77279. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  77280. return serializationObject;
  77281. };
  77282. // Statics
  77283. MorphTarget.Parse = function (serializationObject) {
  77284. var result = new MorphTarget(serializationObject.name, serializationObject.influence);
  77285. result.setPositions(serializationObject.positions);
  77286. if (serializationObject.normals) {
  77287. result.setNormals(serializationObject.normals);
  77288. }
  77289. if (serializationObject.tangents) {
  77290. result.setTangents(serializationObject.tangents);
  77291. }
  77292. // Animations
  77293. if (serializationObject.animations) {
  77294. for (var animationIndex = 0; animationIndex < serializationObject.animations.length; animationIndex++) {
  77295. var parsedAnimation = serializationObject.animations[animationIndex];
  77296. result.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  77297. }
  77298. }
  77299. return result;
  77300. };
  77301. MorphTarget.FromMesh = function (mesh, name, influence) {
  77302. if (!name) {
  77303. name = mesh.name;
  77304. }
  77305. var result = new MorphTarget(name, influence);
  77306. result.setPositions(mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  77307. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  77308. result.setNormals(mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind));
  77309. }
  77310. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  77311. result.setTangents(mesh.getVerticesData(BABYLON.VertexBuffer.TangentKind));
  77312. }
  77313. return result;
  77314. };
  77315. return MorphTarget;
  77316. }());
  77317. BABYLON.MorphTarget = MorphTarget;
  77318. })(BABYLON || (BABYLON = {}));
  77319. //# sourceMappingURL=babylon.morphTarget.js.map
  77320. var BABYLON;
  77321. (function (BABYLON) {
  77322. var MorphTargetManager = /** @class */ (function () {
  77323. function MorphTargetManager(scene) {
  77324. if (scene === void 0) { scene = null; }
  77325. this._targets = new Array();
  77326. this._targetObservable = new Array();
  77327. this._activeTargets = new BABYLON.SmartArray(16);
  77328. this._supportsNormals = false;
  77329. this._supportsTangents = false;
  77330. this._vertexCount = 0;
  77331. this._uniqueId = 0;
  77332. this._tempInfluences = new Array();
  77333. if (!scene) {
  77334. scene = BABYLON.Engine.LastCreatedScene;
  77335. }
  77336. this._scene = scene;
  77337. if (this._scene) {
  77338. this._scene.morphTargetManagers.push(this);
  77339. this._uniqueId = this._scene.getUniqueId();
  77340. }
  77341. }
  77342. Object.defineProperty(MorphTargetManager.prototype, "uniqueId", {
  77343. get: function () {
  77344. return this._uniqueId;
  77345. },
  77346. enumerable: true,
  77347. configurable: true
  77348. });
  77349. Object.defineProperty(MorphTargetManager.prototype, "vertexCount", {
  77350. get: function () {
  77351. return this._vertexCount;
  77352. },
  77353. enumerable: true,
  77354. configurable: true
  77355. });
  77356. Object.defineProperty(MorphTargetManager.prototype, "supportsNormals", {
  77357. get: function () {
  77358. return this._supportsNormals;
  77359. },
  77360. enumerable: true,
  77361. configurable: true
  77362. });
  77363. Object.defineProperty(MorphTargetManager.prototype, "supportsTangents", {
  77364. get: function () {
  77365. return this._supportsTangents;
  77366. },
  77367. enumerable: true,
  77368. configurable: true
  77369. });
  77370. Object.defineProperty(MorphTargetManager.prototype, "numTargets", {
  77371. get: function () {
  77372. return this._targets.length;
  77373. },
  77374. enumerable: true,
  77375. configurable: true
  77376. });
  77377. Object.defineProperty(MorphTargetManager.prototype, "numInfluencers", {
  77378. get: function () {
  77379. return this._activeTargets.length;
  77380. },
  77381. enumerable: true,
  77382. configurable: true
  77383. });
  77384. Object.defineProperty(MorphTargetManager.prototype, "influences", {
  77385. get: function () {
  77386. return this._influences;
  77387. },
  77388. enumerable: true,
  77389. configurable: true
  77390. });
  77391. MorphTargetManager.prototype.getActiveTarget = function (index) {
  77392. return this._activeTargets.data[index];
  77393. };
  77394. MorphTargetManager.prototype.getTarget = function (index) {
  77395. return this._targets[index];
  77396. };
  77397. MorphTargetManager.prototype.addTarget = function (target) {
  77398. var _this = this;
  77399. this._targets.push(target);
  77400. this._targetObservable.push(target.onInfluenceChanged.add(function (needUpdate) {
  77401. _this._syncActiveTargets(needUpdate);
  77402. }));
  77403. this._syncActiveTargets(true);
  77404. };
  77405. MorphTargetManager.prototype.removeTarget = function (target) {
  77406. var index = this._targets.indexOf(target);
  77407. if (index >= 0) {
  77408. this._targets.splice(index, 1);
  77409. target.onInfluenceChanged.remove(this._targetObservable.splice(index, 1)[0]);
  77410. this._syncActiveTargets(true);
  77411. }
  77412. };
  77413. /**
  77414. * Serializes the current manager into a Serialization object.
  77415. * Returns the serialized object.
  77416. */
  77417. MorphTargetManager.prototype.serialize = function () {
  77418. var serializationObject = {};
  77419. serializationObject.id = this.uniqueId;
  77420. serializationObject.targets = [];
  77421. for (var _i = 0, _a = this._targets; _i < _a.length; _i++) {
  77422. var target = _a[_i];
  77423. serializationObject.targets.push(target.serialize());
  77424. }
  77425. return serializationObject;
  77426. };
  77427. MorphTargetManager.prototype._syncActiveTargets = function (needUpdate) {
  77428. var influenceCount = 0;
  77429. this._activeTargets.reset();
  77430. this._supportsNormals = true;
  77431. this._supportsTangents = true;
  77432. this._vertexCount = 0;
  77433. for (var _i = 0, _a = this._targets; _i < _a.length; _i++) {
  77434. var target = _a[_i];
  77435. this._activeTargets.push(target);
  77436. this._tempInfluences[influenceCount++] = target.influence;
  77437. var positions = target.getPositions();
  77438. if (positions) {
  77439. this._supportsNormals = this._supportsNormals && target.hasNormals;
  77440. this._supportsTangents = this._supportsTangents && target.hasTangents;
  77441. var vertexCount = positions.length / 3;
  77442. if (this._vertexCount === 0) {
  77443. this._vertexCount = vertexCount;
  77444. }
  77445. else if (this._vertexCount !== vertexCount) {
  77446. BABYLON.Tools.Error("Incompatible target. Targets must all have the same vertices count.");
  77447. return;
  77448. }
  77449. }
  77450. }
  77451. if (!this._influences || this._influences.length !== influenceCount) {
  77452. this._influences = new Float32Array(influenceCount);
  77453. }
  77454. for (var index = 0; index < influenceCount; index++) {
  77455. this._influences[index] = this._tempInfluences[index];
  77456. }
  77457. if (needUpdate && this._scene) {
  77458. // Flag meshes as dirty to resync with the active targets
  77459. for (var _b = 0, _c = this._scene.meshes; _b < _c.length; _b++) {
  77460. var mesh = _c[_b];
  77461. if (mesh.morphTargetManager === this) {
  77462. mesh._syncGeometryWithMorphTargetManager();
  77463. }
  77464. }
  77465. }
  77466. };
  77467. // Statics
  77468. MorphTargetManager.Parse = function (serializationObject, scene) {
  77469. var result = new MorphTargetManager(scene);
  77470. result._uniqueId = serializationObject.id;
  77471. for (var _i = 0, _a = serializationObject.targets; _i < _a.length; _i++) {
  77472. var targetData = _a[_i];
  77473. result.addTarget(BABYLON.MorphTarget.Parse(targetData));
  77474. }
  77475. return result;
  77476. };
  77477. return MorphTargetManager;
  77478. }());
  77479. BABYLON.MorphTargetManager = MorphTargetManager;
  77480. })(BABYLON || (BABYLON = {}));
  77481. //# sourceMappingURL=babylon.morphTargetManager.js.map
  77482. var BABYLON;
  77483. (function (BABYLON) {
  77484. var Octree = /** @class */ (function () {
  77485. function Octree(creationFunc, maxBlockCapacity, maxDepth) {
  77486. if (maxDepth === void 0) { maxDepth = 2; }
  77487. this.maxDepth = maxDepth;
  77488. this.dynamicContent = new Array();
  77489. this._maxBlockCapacity = maxBlockCapacity || 64;
  77490. this._selectionContent = new BABYLON.SmartArrayNoDuplicate(1024);
  77491. this._creationFunc = creationFunc;
  77492. }
  77493. // Methods
  77494. Octree.prototype.update = function (worldMin, worldMax, entries) {
  77495. Octree._CreateBlocks(worldMin, worldMax, entries, this._maxBlockCapacity, 0, this.maxDepth, this, this._creationFunc);
  77496. };
  77497. Octree.prototype.addMesh = function (entry) {
  77498. for (var index = 0; index < this.blocks.length; index++) {
  77499. var block = this.blocks[index];
  77500. block.addEntry(entry);
  77501. }
  77502. };
  77503. Octree.prototype.select = function (frustumPlanes, allowDuplicate) {
  77504. this._selectionContent.reset();
  77505. for (var index = 0; index < this.blocks.length; index++) {
  77506. var block = this.blocks[index];
  77507. block.select(frustumPlanes, this._selectionContent, allowDuplicate);
  77508. }
  77509. if (allowDuplicate) {
  77510. this._selectionContent.concat(this.dynamicContent);
  77511. }
  77512. else {
  77513. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  77514. }
  77515. return this._selectionContent;
  77516. };
  77517. Octree.prototype.intersects = function (sphereCenter, sphereRadius, allowDuplicate) {
  77518. this._selectionContent.reset();
  77519. for (var index = 0; index < this.blocks.length; index++) {
  77520. var block = this.blocks[index];
  77521. block.intersects(sphereCenter, sphereRadius, this._selectionContent, allowDuplicate);
  77522. }
  77523. if (allowDuplicate) {
  77524. this._selectionContent.concat(this.dynamicContent);
  77525. }
  77526. else {
  77527. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  77528. }
  77529. return this._selectionContent;
  77530. };
  77531. Octree.prototype.intersectsRay = function (ray) {
  77532. this._selectionContent.reset();
  77533. for (var index = 0; index < this.blocks.length; index++) {
  77534. var block = this.blocks[index];
  77535. block.intersectsRay(ray, this._selectionContent);
  77536. }
  77537. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  77538. return this._selectionContent;
  77539. };
  77540. Octree._CreateBlocks = function (worldMin, worldMax, entries, maxBlockCapacity, currentDepth, maxDepth, target, creationFunc) {
  77541. target.blocks = new Array();
  77542. var blockSize = new BABYLON.Vector3((worldMax.x - worldMin.x) / 2, (worldMax.y - worldMin.y) / 2, (worldMax.z - worldMin.z) / 2);
  77543. // Segmenting space
  77544. for (var x = 0; x < 2; x++) {
  77545. for (var y = 0; y < 2; y++) {
  77546. for (var z = 0; z < 2; z++) {
  77547. var localMin = worldMin.add(blockSize.multiplyByFloats(x, y, z));
  77548. var localMax = worldMin.add(blockSize.multiplyByFloats(x + 1, y + 1, z + 1));
  77549. var block = new BABYLON.OctreeBlock(localMin, localMax, maxBlockCapacity, currentDepth + 1, maxDepth, creationFunc);
  77550. block.addEntries(entries);
  77551. target.blocks.push(block);
  77552. }
  77553. }
  77554. }
  77555. };
  77556. Octree.CreationFuncForMeshes = function (entry, block) {
  77557. var boundingInfo = entry.getBoundingInfo();
  77558. if (!entry.isBlocked && boundingInfo.boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  77559. block.entries.push(entry);
  77560. }
  77561. };
  77562. Octree.CreationFuncForSubMeshes = function (entry, block) {
  77563. var boundingInfo = entry.getBoundingInfo();
  77564. if (boundingInfo.boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  77565. block.entries.push(entry);
  77566. }
  77567. };
  77568. return Octree;
  77569. }());
  77570. BABYLON.Octree = Octree;
  77571. })(BABYLON || (BABYLON = {}));
  77572. //# sourceMappingURL=babylon.octree.js.map
  77573. var BABYLON;
  77574. (function (BABYLON) {
  77575. var OctreeBlock = /** @class */ (function () {
  77576. function OctreeBlock(minPoint, maxPoint, capacity, depth, maxDepth, creationFunc) {
  77577. this.entries = new Array();
  77578. this._boundingVectors = new Array();
  77579. this._capacity = capacity;
  77580. this._depth = depth;
  77581. this._maxDepth = maxDepth;
  77582. this._creationFunc = creationFunc;
  77583. this._minPoint = minPoint;
  77584. this._maxPoint = maxPoint;
  77585. this._boundingVectors.push(minPoint.clone());
  77586. this._boundingVectors.push(maxPoint.clone());
  77587. this._boundingVectors.push(minPoint.clone());
  77588. this._boundingVectors[2].x = maxPoint.x;
  77589. this._boundingVectors.push(minPoint.clone());
  77590. this._boundingVectors[3].y = maxPoint.y;
  77591. this._boundingVectors.push(minPoint.clone());
  77592. this._boundingVectors[4].z = maxPoint.z;
  77593. this._boundingVectors.push(maxPoint.clone());
  77594. this._boundingVectors[5].z = minPoint.z;
  77595. this._boundingVectors.push(maxPoint.clone());
  77596. this._boundingVectors[6].x = minPoint.x;
  77597. this._boundingVectors.push(maxPoint.clone());
  77598. this._boundingVectors[7].y = minPoint.y;
  77599. }
  77600. Object.defineProperty(OctreeBlock.prototype, "capacity", {
  77601. // Property
  77602. get: function () {
  77603. return this._capacity;
  77604. },
  77605. enumerable: true,
  77606. configurable: true
  77607. });
  77608. Object.defineProperty(OctreeBlock.prototype, "minPoint", {
  77609. get: function () {
  77610. return this._minPoint;
  77611. },
  77612. enumerable: true,
  77613. configurable: true
  77614. });
  77615. Object.defineProperty(OctreeBlock.prototype, "maxPoint", {
  77616. get: function () {
  77617. return this._maxPoint;
  77618. },
  77619. enumerable: true,
  77620. configurable: true
  77621. });
  77622. // Methods
  77623. OctreeBlock.prototype.addEntry = function (entry) {
  77624. if (this.blocks) {
  77625. for (var index = 0; index < this.blocks.length; index++) {
  77626. var block = this.blocks[index];
  77627. block.addEntry(entry);
  77628. }
  77629. return;
  77630. }
  77631. this._creationFunc(entry, this);
  77632. if (this.entries.length > this.capacity && this._depth < this._maxDepth) {
  77633. this.createInnerBlocks();
  77634. }
  77635. };
  77636. OctreeBlock.prototype.addEntries = function (entries) {
  77637. for (var index = 0; index < entries.length; index++) {
  77638. var mesh = entries[index];
  77639. this.addEntry(mesh);
  77640. }
  77641. };
  77642. OctreeBlock.prototype.select = function (frustumPlanes, selection, allowDuplicate) {
  77643. if (BABYLON.BoundingBox.IsInFrustum(this._boundingVectors, frustumPlanes)) {
  77644. if (this.blocks) {
  77645. for (var index = 0; index < this.blocks.length; index++) {
  77646. var block = this.blocks[index];
  77647. block.select(frustumPlanes, selection, allowDuplicate);
  77648. }
  77649. return;
  77650. }
  77651. if (allowDuplicate) {
  77652. selection.concat(this.entries);
  77653. }
  77654. else {
  77655. selection.concatWithNoDuplicate(this.entries);
  77656. }
  77657. }
  77658. };
  77659. OctreeBlock.prototype.intersects = function (sphereCenter, sphereRadius, selection, allowDuplicate) {
  77660. if (BABYLON.BoundingBox.IntersectsSphere(this._minPoint, this._maxPoint, sphereCenter, sphereRadius)) {
  77661. if (this.blocks) {
  77662. for (var index = 0; index < this.blocks.length; index++) {
  77663. var block = this.blocks[index];
  77664. block.intersects(sphereCenter, sphereRadius, selection, allowDuplicate);
  77665. }
  77666. return;
  77667. }
  77668. if (allowDuplicate) {
  77669. selection.concat(this.entries);
  77670. }
  77671. else {
  77672. selection.concatWithNoDuplicate(this.entries);
  77673. }
  77674. }
  77675. };
  77676. OctreeBlock.prototype.intersectsRay = function (ray, selection) {
  77677. if (ray.intersectsBoxMinMax(this._minPoint, this._maxPoint)) {
  77678. if (this.blocks) {
  77679. for (var index = 0; index < this.blocks.length; index++) {
  77680. var block = this.blocks[index];
  77681. block.intersectsRay(ray, selection);
  77682. }
  77683. return;
  77684. }
  77685. selection.concatWithNoDuplicate(this.entries);
  77686. }
  77687. };
  77688. OctreeBlock.prototype.createInnerBlocks = function () {
  77689. BABYLON.Octree._CreateBlocks(this._minPoint, this._maxPoint, this.entries, this._capacity, this._depth, this._maxDepth, this, this._creationFunc);
  77690. };
  77691. return OctreeBlock;
  77692. }());
  77693. BABYLON.OctreeBlock = OctreeBlock;
  77694. })(BABYLON || (BABYLON = {}));
  77695. //# sourceMappingURL=babylon.octreeBlock.js.map
  77696. var BABYLON;
  77697. (function (BABYLON) {
  77698. var VRDistortionCorrectionPostProcess = /** @class */ (function (_super) {
  77699. __extends(VRDistortionCorrectionPostProcess, _super);
  77700. function VRDistortionCorrectionPostProcess(name, camera, isRightEye, vrMetrics) {
  77701. var _this = _super.call(this, name, "vrDistortionCorrection", [
  77702. 'LensCenter',
  77703. 'Scale',
  77704. 'ScaleIn',
  77705. 'HmdWarpParam'
  77706. ], null, vrMetrics.postProcessScaleFactor, camera, BABYLON.Texture.BILINEAR_SAMPLINGMODE) || this;
  77707. _this._isRightEye = isRightEye;
  77708. _this._distortionFactors = vrMetrics.distortionK;
  77709. _this._postProcessScaleFactor = vrMetrics.postProcessScaleFactor;
  77710. _this._lensCenterOffset = vrMetrics.lensCenterOffset;
  77711. _this.adaptScaleToCurrentViewport = true;
  77712. _this.onSizeChangedObservable.add(function () {
  77713. _this.aspectRatio = _this.width * .5 / _this.height;
  77714. _this._scaleIn = new BABYLON.Vector2(2, 2 / _this.aspectRatio);
  77715. _this._scaleFactor = new BABYLON.Vector2(.5 * (1 / _this._postProcessScaleFactor), .5 * (1 / _this._postProcessScaleFactor) * _this.aspectRatio);
  77716. _this._lensCenter = new BABYLON.Vector2(_this._isRightEye ? 0.5 - _this._lensCenterOffset * 0.5 : 0.5 + _this._lensCenterOffset * 0.5, 0.5);
  77717. });
  77718. _this.onApplyObservable.add(function (effect) {
  77719. effect.setFloat2("LensCenter", _this._lensCenter.x, _this._lensCenter.y);
  77720. effect.setFloat2("Scale", _this._scaleFactor.x, _this._scaleFactor.y);
  77721. effect.setFloat2("ScaleIn", _this._scaleIn.x, _this._scaleIn.y);
  77722. effect.setFloat4("HmdWarpParam", _this._distortionFactors[0], _this._distortionFactors[1], _this._distortionFactors[2], _this._distortionFactors[3]);
  77723. });
  77724. return _this;
  77725. }
  77726. return VRDistortionCorrectionPostProcess;
  77727. }(BABYLON.PostProcess));
  77728. BABYLON.VRDistortionCorrectionPostProcess = VRDistortionCorrectionPostProcess;
  77729. })(BABYLON || (BABYLON = {}));
  77730. //# sourceMappingURL=babylon.vrDistortionCorrectionPostProcess.js.map
  77731. var BABYLON;
  77732. (function (BABYLON) {
  77733. var AnaglyphPostProcess = /** @class */ (function (_super) {
  77734. __extends(AnaglyphPostProcess, _super);
  77735. function AnaglyphPostProcess(name, options, rigCameras, samplingMode, engine, reusable) {
  77736. var _this = _super.call(this, name, "anaglyph", null, ["leftSampler"], options, rigCameras[1], samplingMode, engine, reusable) || this;
  77737. _this._passedProcess = rigCameras[0]._rigPostProcess;
  77738. _this.onApplyObservable.add(function (effect) {
  77739. effect.setTextureFromPostProcess("leftSampler", _this._passedProcess);
  77740. });
  77741. return _this;
  77742. }
  77743. return AnaglyphPostProcess;
  77744. }(BABYLON.PostProcess));
  77745. BABYLON.AnaglyphPostProcess = AnaglyphPostProcess;
  77746. })(BABYLON || (BABYLON = {}));
  77747. //# sourceMappingURL=babylon.anaglyphPostProcess.js.map
  77748. var BABYLON;
  77749. (function (BABYLON) {
  77750. var StereoscopicInterlacePostProcess = /** @class */ (function (_super) {
  77751. __extends(StereoscopicInterlacePostProcess, _super);
  77752. function StereoscopicInterlacePostProcess(name, rigCameras, isStereoscopicHoriz, samplingMode, engine, reusable) {
  77753. var _this = _super.call(this, name, "stereoscopicInterlace", ['stepSize'], ['camASampler'], 1, rigCameras[1], samplingMode, engine, reusable, isStereoscopicHoriz ? "#define IS_STEREOSCOPIC_HORIZ 1" : undefined) || this;
  77754. _this._passedProcess = rigCameras[0]._rigPostProcess;
  77755. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  77756. _this.onSizeChangedObservable.add(function () {
  77757. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  77758. });
  77759. _this.onApplyObservable.add(function (effect) {
  77760. effect.setTextureFromPostProcess("camASampler", _this._passedProcess);
  77761. effect.setFloat2("stepSize", _this._stepSize.x, _this._stepSize.y);
  77762. });
  77763. return _this;
  77764. }
  77765. return StereoscopicInterlacePostProcess;
  77766. }(BABYLON.PostProcess));
  77767. BABYLON.StereoscopicInterlacePostProcess = StereoscopicInterlacePostProcess;
  77768. })(BABYLON || (BABYLON = {}));
  77769. //# sourceMappingURL=babylon.stereoscopicInterlacePostProcess.js.map
  77770. var BABYLON;
  77771. (function (BABYLON) {
  77772. /**
  77773. * Takes information about the orientation of the device as reported by the deviceorientation event to orient the camera.
  77774. * Screen rotation is taken into account.
  77775. */
  77776. var FreeCameraDeviceOrientationInput = /** @class */ (function () {
  77777. function FreeCameraDeviceOrientationInput() {
  77778. var _this = this;
  77779. this._screenOrientationAngle = 0;
  77780. this._screenQuaternion = new BABYLON.Quaternion();
  77781. this._alpha = 0;
  77782. this._beta = 0;
  77783. this._gamma = 0;
  77784. this._orientationChanged = function () {
  77785. _this._screenOrientationAngle = (window.orientation !== undefined ? +window.orientation : (window.screen.orientation && window.screen.orientation['angle'] ? window.screen.orientation.angle : 0));
  77786. _this._screenOrientationAngle = -BABYLON.Tools.ToRadians(_this._screenOrientationAngle / 2);
  77787. _this._screenQuaternion.copyFromFloats(0, Math.sin(_this._screenOrientationAngle), 0, Math.cos(_this._screenOrientationAngle));
  77788. };
  77789. this._deviceOrientation = function (evt) {
  77790. _this._alpha = evt.alpha !== null ? evt.alpha : 0;
  77791. _this._beta = evt.beta !== null ? evt.beta : 0;
  77792. _this._gamma = evt.gamma !== null ? evt.gamma : 0;
  77793. };
  77794. this._constantTranform = new BABYLON.Quaternion(-Math.sqrt(0.5), 0, 0, Math.sqrt(0.5));
  77795. this._orientationChanged();
  77796. }
  77797. Object.defineProperty(FreeCameraDeviceOrientationInput.prototype, "camera", {
  77798. get: function () {
  77799. return this._camera;
  77800. },
  77801. set: function (camera) {
  77802. this._camera = camera;
  77803. if (this._camera != null && !this._camera.rotationQuaternion) {
  77804. this._camera.rotationQuaternion = new BABYLON.Quaternion();
  77805. }
  77806. },
  77807. enumerable: true,
  77808. configurable: true
  77809. });
  77810. FreeCameraDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  77811. window.addEventListener("orientationchange", this._orientationChanged);
  77812. window.addEventListener("deviceorientation", this._deviceOrientation);
  77813. //In certain cases, the attach control is called AFTER orientation was changed,
  77814. //So this is needed.
  77815. this._orientationChanged();
  77816. };
  77817. FreeCameraDeviceOrientationInput.prototype.detachControl = function (element) {
  77818. window.removeEventListener("orientationchange", this._orientationChanged);
  77819. window.removeEventListener("deviceorientation", this._deviceOrientation);
  77820. };
  77821. FreeCameraDeviceOrientationInput.prototype.checkInputs = function () {
  77822. //if no device orientation provided, don't update the rotation.
  77823. //Only testing against alpha under the assumption thatnorientation will never be so exact when set.
  77824. if (!this._alpha)
  77825. return;
  77826. BABYLON.Quaternion.RotationYawPitchRollToRef(BABYLON.Tools.ToRadians(this._alpha), BABYLON.Tools.ToRadians(this._beta), -BABYLON.Tools.ToRadians(this._gamma), this.camera.rotationQuaternion);
  77827. this._camera.rotationQuaternion.multiplyInPlace(this._screenQuaternion);
  77828. this._camera.rotationQuaternion.multiplyInPlace(this._constantTranform);
  77829. //Mirror on XY Plane
  77830. this._camera.rotationQuaternion.z *= -1;
  77831. this._camera.rotationQuaternion.w *= -1;
  77832. };
  77833. FreeCameraDeviceOrientationInput.prototype.getClassName = function () {
  77834. return "FreeCameraDeviceOrientationInput";
  77835. };
  77836. FreeCameraDeviceOrientationInput.prototype.getSimpleName = function () {
  77837. return "deviceOrientation";
  77838. };
  77839. return FreeCameraDeviceOrientationInput;
  77840. }());
  77841. BABYLON.FreeCameraDeviceOrientationInput = FreeCameraDeviceOrientationInput;
  77842. BABYLON.CameraInputTypes["FreeCameraDeviceOrientationInput"] = FreeCameraDeviceOrientationInput;
  77843. })(BABYLON || (BABYLON = {}));
  77844. //# sourceMappingURL=babylon.freeCameraDeviceOrientationInput.js.map
  77845. var BABYLON;
  77846. (function (BABYLON) {
  77847. var ArcRotateCameraVRDeviceOrientationInput = /** @class */ (function () {
  77848. function ArcRotateCameraVRDeviceOrientationInput() {
  77849. this.alphaCorrection = 1;
  77850. this.betaCorrection = 1;
  77851. this.gammaCorrection = 1;
  77852. this._alpha = 0;
  77853. this._gamma = 0;
  77854. this._dirty = false;
  77855. this._deviceOrientationHandler = this._onOrientationEvent.bind(this);
  77856. }
  77857. ArcRotateCameraVRDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  77858. this.camera.attachControl(element, noPreventDefault);
  77859. window.addEventListener("deviceorientation", this._deviceOrientationHandler);
  77860. };
  77861. ArcRotateCameraVRDeviceOrientationInput.prototype._onOrientationEvent = function (evt) {
  77862. if (evt.alpha !== null) {
  77863. this._alpha = +evt.alpha | 0;
  77864. }
  77865. if (evt.gamma !== null) {
  77866. this._gamma = +evt.gamma | 0;
  77867. }
  77868. this._dirty = true;
  77869. };
  77870. ArcRotateCameraVRDeviceOrientationInput.prototype.checkInputs = function () {
  77871. if (this._dirty) {
  77872. this._dirty = false;
  77873. if (this._gamma < 0) {
  77874. this._gamma = 180 + this._gamma;
  77875. }
  77876. this.camera.alpha = (-this._alpha / 180.0 * Math.PI) % Math.PI * 2;
  77877. this.camera.beta = (this._gamma / 180.0 * Math.PI);
  77878. }
  77879. };
  77880. ArcRotateCameraVRDeviceOrientationInput.prototype.detachControl = function (element) {
  77881. window.removeEventListener("deviceorientation", this._deviceOrientationHandler);
  77882. };
  77883. ArcRotateCameraVRDeviceOrientationInput.prototype.getClassName = function () {
  77884. return "ArcRotateCameraVRDeviceOrientationInput";
  77885. };
  77886. ArcRotateCameraVRDeviceOrientationInput.prototype.getSimpleName = function () {
  77887. return "VRDeviceOrientation";
  77888. };
  77889. return ArcRotateCameraVRDeviceOrientationInput;
  77890. }());
  77891. BABYLON.ArcRotateCameraVRDeviceOrientationInput = ArcRotateCameraVRDeviceOrientationInput;
  77892. BABYLON.CameraInputTypes["ArcRotateCameraVRDeviceOrientationInput"] = ArcRotateCameraVRDeviceOrientationInput;
  77893. })(BABYLON || (BABYLON = {}));
  77894. //# sourceMappingURL=babylon.arcRotateCameraVRDeviceOrientationInput.js.map
  77895. var BABYLON;
  77896. (function (BABYLON) {
  77897. var VRCameraMetrics = /** @class */ (function () {
  77898. function VRCameraMetrics() {
  77899. this.compensateDistortion = true;
  77900. }
  77901. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatio", {
  77902. get: function () {
  77903. return this.hResolution / (2 * this.vResolution);
  77904. },
  77905. enumerable: true,
  77906. configurable: true
  77907. });
  77908. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatioFov", {
  77909. get: function () {
  77910. return (2 * Math.atan((this.postProcessScaleFactor * this.vScreenSize) / (2 * this.eyeToScreenDistance)));
  77911. },
  77912. enumerable: true,
  77913. configurable: true
  77914. });
  77915. Object.defineProperty(VRCameraMetrics.prototype, "leftHMatrix", {
  77916. get: function () {
  77917. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  77918. var h = (4 * meters) / this.hScreenSize;
  77919. return BABYLON.Matrix.Translation(h, 0, 0);
  77920. },
  77921. enumerable: true,
  77922. configurable: true
  77923. });
  77924. Object.defineProperty(VRCameraMetrics.prototype, "rightHMatrix", {
  77925. get: function () {
  77926. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  77927. var h = (4 * meters) / this.hScreenSize;
  77928. return BABYLON.Matrix.Translation(-h, 0, 0);
  77929. },
  77930. enumerable: true,
  77931. configurable: true
  77932. });
  77933. Object.defineProperty(VRCameraMetrics.prototype, "leftPreViewMatrix", {
  77934. get: function () {
  77935. return BABYLON.Matrix.Translation(0.5 * this.interpupillaryDistance, 0, 0);
  77936. },
  77937. enumerable: true,
  77938. configurable: true
  77939. });
  77940. Object.defineProperty(VRCameraMetrics.prototype, "rightPreViewMatrix", {
  77941. get: function () {
  77942. return BABYLON.Matrix.Translation(-0.5 * this.interpupillaryDistance, 0, 0);
  77943. },
  77944. enumerable: true,
  77945. configurable: true
  77946. });
  77947. VRCameraMetrics.GetDefault = function () {
  77948. var result = new VRCameraMetrics();
  77949. result.hResolution = 1280;
  77950. result.vResolution = 800;
  77951. result.hScreenSize = 0.149759993;
  77952. result.vScreenSize = 0.0935999975;
  77953. result.vScreenCenter = 0.0467999987;
  77954. result.eyeToScreenDistance = 0.0410000011;
  77955. result.lensSeparationDistance = 0.0635000020;
  77956. result.interpupillaryDistance = 0.0640000030;
  77957. result.distortionK = [1.0, 0.219999999, 0.239999995, 0.0];
  77958. result.chromaAbCorrection = [0.995999992, -0.00400000019, 1.01400006, 0.0];
  77959. result.postProcessScaleFactor = 1.714605507808412;
  77960. result.lensCenterOffset = 0.151976421;
  77961. return result;
  77962. };
  77963. return VRCameraMetrics;
  77964. }());
  77965. BABYLON.VRCameraMetrics = VRCameraMetrics;
  77966. })(BABYLON || (BABYLON = {}));
  77967. //# sourceMappingURL=babylon.vrCameraMetrics.js.map
  77968. var BABYLON;
  77969. (function (BABYLON) {
  77970. /**
  77971. * This represents a WebVR camera.
  77972. * The WebVR camera is Babylon's simple interface to interaction with Windows Mixed Reality, HTC Vive and Oculus Rift.
  77973. * @example http://doc.babylonjs.com/how_to/webvr_camera
  77974. */
  77975. var WebVRFreeCamera = /** @class */ (function (_super) {
  77976. __extends(WebVRFreeCamera, _super);
  77977. /**
  77978. * Instantiates a WebVRFreeCamera.
  77979. * @param name The name of the WebVRFreeCamera
  77980. * @param position The starting anchor position for the camera
  77981. * @param scene The scene the camera belongs to
  77982. * @param webVROptions a set of customizable options for the webVRCamera
  77983. */
  77984. function WebVRFreeCamera(name, position, scene, webVROptions) {
  77985. if (webVROptions === void 0) { webVROptions = {}; }
  77986. var _this = _super.call(this, name, position, scene) || this;
  77987. _this.webVROptions = webVROptions;
  77988. /**
  77989. * The vrDisplay tied to the camera. See https://developer.mozilla.org/en-US/docs/Web/API/VRDisplay
  77990. */
  77991. _this._vrDevice = null;
  77992. /**
  77993. * The rawPose of the vrDevice.
  77994. */
  77995. _this.rawPose = null;
  77996. _this._specsVersion = "1.1";
  77997. _this._attached = false;
  77998. _this._descendants = [];
  77999. // Represents device position and rotation in room space. Should only be used to help calculate babylon space values
  78000. _this._deviceRoomPosition = BABYLON.Vector3.Zero();
  78001. _this._deviceRoomRotationQuaternion = BABYLON.Quaternion.Identity();
  78002. _this._standingMatrix = null;
  78003. /**
  78004. * Represents device position in babylon space.
  78005. */
  78006. _this.devicePosition = BABYLON.Vector3.Zero();
  78007. /**
  78008. * Represents device rotation in babylon space.
  78009. */
  78010. _this.deviceRotationQuaternion = BABYLON.Quaternion.Identity();
  78011. /**
  78012. * The scale of the device to be used when translating from device space to babylon space.
  78013. */
  78014. _this.deviceScaleFactor = 1;
  78015. _this._deviceToWorld = BABYLON.Matrix.Identity();
  78016. _this._worldToDevice = BABYLON.Matrix.Identity();
  78017. /**
  78018. * References to the webVR controllers for the vrDevice.
  78019. */
  78020. _this.controllers = [];
  78021. /**
  78022. * Emits an event when a controller is attached.
  78023. */
  78024. _this.onControllersAttachedObservable = new BABYLON.Observable();
  78025. /**
  78026. * Emits an event when a controller's mesh has been loaded;
  78027. */
  78028. _this.onControllerMeshLoadedObservable = new BABYLON.Observable();
  78029. /**
  78030. * If the rig cameras be used as parent instead of this camera.
  78031. */
  78032. _this.rigParenting = true;
  78033. _this._defaultHeight = undefined;
  78034. _this._workingVector = BABYLON.Vector3.Zero();
  78035. _this._oneVector = BABYLON.Vector3.One();
  78036. _this._workingMatrix = BABYLON.Matrix.Identity();
  78037. _this._cache.position = BABYLON.Vector3.Zero();
  78038. if (webVROptions.defaultHeight) {
  78039. _this._defaultHeight = webVROptions.defaultHeight;
  78040. _this.position.y = _this._defaultHeight;
  78041. }
  78042. _this.minZ = 0.1;
  78043. //legacy support - the compensation boolean was removed.
  78044. if (arguments.length === 5) {
  78045. _this.webVROptions = arguments[4];
  78046. }
  78047. // default webVR options
  78048. if (_this.webVROptions.trackPosition == undefined) {
  78049. _this.webVROptions.trackPosition = true;
  78050. }
  78051. if (_this.webVROptions.controllerMeshes == undefined) {
  78052. _this.webVROptions.controllerMeshes = true;
  78053. }
  78054. if (_this.webVROptions.defaultLightingOnControllers == undefined) {
  78055. _this.webVROptions.defaultLightingOnControllers = true;
  78056. }
  78057. _this.rotationQuaternion = new BABYLON.Quaternion();
  78058. if (_this.webVROptions && _this.webVROptions.positionScale) {
  78059. _this.deviceScaleFactor = _this.webVROptions.positionScale;
  78060. }
  78061. //enable VR
  78062. var engine = _this.getEngine();
  78063. _this._onVREnabled = function (success) { if (success) {
  78064. _this.initControllers();
  78065. } };
  78066. engine.onVRRequestPresentComplete.add(_this._onVREnabled);
  78067. engine.initWebVR().add(function (event) {
  78068. if (!event.vrDisplay || _this._vrDevice === event.vrDisplay) {
  78069. return;
  78070. }
  78071. _this._vrDevice = event.vrDisplay;
  78072. //reset the rig parameters.
  78073. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_WEBVR, { parentCamera: _this, vrDisplay: _this._vrDevice, frameData: _this._frameData, specs: _this._specsVersion });
  78074. if (_this._attached) {
  78075. _this.getEngine().enableVR();
  78076. }
  78077. });
  78078. if (typeof (VRFrameData) !== "undefined")
  78079. _this._frameData = new VRFrameData();
  78080. /**
  78081. * The idea behind the following lines:
  78082. * objects that have the camera as parent should actually have the rig cameras as a parent.
  78083. * BUT, each of those cameras has a different view matrix, which means that if we set the parent to the first rig camera,
  78084. * the second will not show it correctly.
  78085. *
  78086. * To solve this - each object that has the camera as parent will be added to a protected array.
  78087. * When the rig camera renders, it will take this array and set all of those to be its children.
  78088. * This way, the right camera will be used as a parent, and the mesh will be rendered correctly.
  78089. * Amazing!
  78090. */
  78091. scene.onBeforeCameraRenderObservable.add(function (camera) {
  78092. if (camera.parent === _this && _this.rigParenting) {
  78093. _this._descendants = _this.getDescendants(true, function (n) {
  78094. // don't take the cameras or the controllers!
  78095. var isController = _this.controllers.some(function (controller) { return controller._mesh === n; });
  78096. var isRigCamera = _this._rigCameras.indexOf(n) !== -1;
  78097. return !isController && !isRigCamera;
  78098. });
  78099. _this._descendants.forEach(function (node) {
  78100. node.parent = camera;
  78101. });
  78102. }
  78103. });
  78104. scene.onAfterCameraRenderObservable.add(function (camera) {
  78105. if (camera.parent === _this && _this.rigParenting) {
  78106. _this._descendants.forEach(function (node) {
  78107. node.parent = _this;
  78108. });
  78109. }
  78110. });
  78111. return _this;
  78112. }
  78113. /**
  78114. * Gets the device distance from the ground in meters.
  78115. * @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.
  78116. */
  78117. WebVRFreeCamera.prototype.deviceDistanceToRoomGround = function () {
  78118. if (this._standingMatrix) {
  78119. // Add standing matrix offset to get real offset from ground in room
  78120. this._standingMatrix.getTranslationToRef(this._workingVector);
  78121. return this._deviceRoomPosition.y + this._workingVector.y;
  78122. }
  78123. //If VRDisplay does not inform stage parameters and no default height is set we fallback to zero.
  78124. return this._defaultHeight || 0;
  78125. };
  78126. /**
  78127. * Enables the standing matrix when supported. This can be used to position the user's view the correct height from the ground.
  78128. * @param callback will be called when the standing matrix is set. Callback parameter is if the standing matrix is supported.
  78129. */
  78130. WebVRFreeCamera.prototype.useStandingMatrix = function (callback) {
  78131. var _this = this;
  78132. if (callback === void 0) { callback = function (bool) { }; }
  78133. // Use standing matrix if available
  78134. this.getEngine().initWebVRAsync().then(function (result) {
  78135. if (!result.vrDisplay || !result.vrDisplay.stageParameters || !result.vrDisplay.stageParameters.sittingToStandingTransform) {
  78136. callback(false);
  78137. }
  78138. else {
  78139. _this._standingMatrix = new BABYLON.Matrix();
  78140. BABYLON.Matrix.FromFloat32ArrayToRefScaled(result.vrDisplay.stageParameters.sittingToStandingTransform, 0, 1, _this._standingMatrix);
  78141. if (!_this.getScene().useRightHandedSystem) {
  78142. [2, 6, 8, 9, 14].forEach(function (num) {
  78143. if (_this._standingMatrix) {
  78144. _this._standingMatrix.m[num] *= -1;
  78145. }
  78146. });
  78147. }
  78148. callback(true);
  78149. }
  78150. });
  78151. };
  78152. /**
  78153. * Enables the standing matrix when supported. This can be used to position the user's view the correct height from the ground.
  78154. * @returns A promise with a boolean set to if the standing matrix is supported.
  78155. */
  78156. WebVRFreeCamera.prototype.useStandingMatrixAsync = function () {
  78157. var _this = this;
  78158. return new Promise(function (res, rej) {
  78159. _this.useStandingMatrix(function (supported) {
  78160. res(supported);
  78161. });
  78162. });
  78163. };
  78164. /**
  78165. * Disposes the camera
  78166. */
  78167. WebVRFreeCamera.prototype.dispose = function () {
  78168. this.getEngine().onVRRequestPresentComplete.removeCallback(this._onVREnabled);
  78169. _super.prototype.dispose.call(this);
  78170. };
  78171. /**
  78172. * Gets a vrController by name.
  78173. * @param name The name of the controller to retreive
  78174. * @returns the controller matching the name specified or null if not found
  78175. */
  78176. WebVRFreeCamera.prototype.getControllerByName = function (name) {
  78177. for (var _i = 0, _a = this.controllers; _i < _a.length; _i++) {
  78178. var gp = _a[_i];
  78179. if (gp.hand === name) {
  78180. return gp;
  78181. }
  78182. }
  78183. return null;
  78184. };
  78185. Object.defineProperty(WebVRFreeCamera.prototype, "leftController", {
  78186. /**
  78187. * The controller corrisponding to the users left hand.
  78188. */
  78189. get: function () {
  78190. if (!this._leftController) {
  78191. this._leftController = this.getControllerByName("left");
  78192. }
  78193. return this._leftController;
  78194. },
  78195. enumerable: true,
  78196. configurable: true
  78197. });
  78198. ;
  78199. Object.defineProperty(WebVRFreeCamera.prototype, "rightController", {
  78200. /**
  78201. * The controller corrisponding to the users right hand.
  78202. */
  78203. get: function () {
  78204. if (!this._rightController) {
  78205. this._rightController = this.getControllerByName("right");
  78206. }
  78207. return this._rightController;
  78208. },
  78209. enumerable: true,
  78210. configurable: true
  78211. });
  78212. ;
  78213. /**
  78214. * Casts a ray forward from the vrCamera's gaze.
  78215. * @param length Length of the ray (default: 100)
  78216. * @returns the ray corrisponding to the gaze
  78217. */
  78218. WebVRFreeCamera.prototype.getForwardRay = function (length) {
  78219. if (length === void 0) { length = 100; }
  78220. if (this.leftCamera) {
  78221. // Use left eye to avoid computation to compute center on every call
  78222. return _super.prototype.getForwardRay.call(this, length, this.leftCamera.getWorldMatrix(), this.leftCamera.globalPosition); // Need the actual rendered camera
  78223. }
  78224. else {
  78225. return _super.prototype.getForwardRay.call(this, length);
  78226. }
  78227. };
  78228. /**
  78229. * Updates the camera based on device's frame data
  78230. */
  78231. WebVRFreeCamera.prototype._checkInputs = function () {
  78232. if (this._vrDevice && this._vrDevice.isPresenting) {
  78233. this._vrDevice.getFrameData(this._frameData);
  78234. this.updateFromDevice(this._frameData.pose);
  78235. }
  78236. _super.prototype._checkInputs.call(this);
  78237. };
  78238. /**
  78239. * Updates the poseControlled values based on the input device pose.
  78240. * @param poseData Pose coming from the device
  78241. */
  78242. WebVRFreeCamera.prototype.updateFromDevice = function (poseData) {
  78243. if (poseData && poseData.orientation) {
  78244. this.rawPose = poseData;
  78245. this._deviceRoomRotationQuaternion.copyFromFloats(poseData.orientation[0], poseData.orientation[1], -poseData.orientation[2], -poseData.orientation[3]);
  78246. if (this.getScene().useRightHandedSystem) {
  78247. this._deviceRoomRotationQuaternion.z *= -1;
  78248. this._deviceRoomRotationQuaternion.w *= -1;
  78249. }
  78250. if (this.webVROptions.trackPosition && this.rawPose.position) {
  78251. this._deviceRoomPosition.copyFromFloats(this.rawPose.position[0], this.rawPose.position[1], -this.rawPose.position[2]);
  78252. if (this.getScene().useRightHandedSystem) {
  78253. this._deviceRoomPosition.z *= -1;
  78254. }
  78255. }
  78256. }
  78257. };
  78258. /**
  78259. * WebVR's attach control will start broadcasting frames to the device.
  78260. * Note that in certain browsers (chrome for example) this function must be called
  78261. * within a user-interaction callback. Example:
  78262. * <pre> scene.onPointerDown = function() { camera.attachControl(canvas); }</pre>
  78263. *
  78264. * @param element html element to attach the vrDevice to
  78265. * @param noPreventDefault prevent the default html element operation when attaching the vrDevice
  78266. */
  78267. WebVRFreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  78268. _super.prototype.attachControl.call(this, element, noPreventDefault);
  78269. this._attached = true;
  78270. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  78271. if (this._vrDevice) {
  78272. this.getEngine().enableVR();
  78273. }
  78274. };
  78275. /**
  78276. * Detaches the camera from the html element and disables VR
  78277. *
  78278. * @param element html element to detach from
  78279. */
  78280. WebVRFreeCamera.prototype.detachControl = function (element) {
  78281. this.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  78282. this.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  78283. _super.prototype.detachControl.call(this, element);
  78284. this._attached = false;
  78285. this.getEngine().disableVR();
  78286. };
  78287. /**
  78288. * @returns the name of this class
  78289. */
  78290. WebVRFreeCamera.prototype.getClassName = function () {
  78291. return "WebVRFreeCamera";
  78292. };
  78293. /**
  78294. * Calls resetPose on the vrDisplay
  78295. * See: https://developer.mozilla.org/en-US/docs/Web/API/VRDisplay/resetPose
  78296. */
  78297. WebVRFreeCamera.prototype.resetToCurrentRotation = function () {
  78298. //uses the vrDisplay's "resetPose()".
  78299. //pitch and roll won't be affected.
  78300. this._vrDevice.resetPose();
  78301. };
  78302. /**
  78303. * Updates the rig cameras (left and right eye)
  78304. */
  78305. WebVRFreeCamera.prototype._updateRigCameras = function () {
  78306. var camLeft = this._rigCameras[0];
  78307. var camRight = this._rigCameras[1];
  78308. camLeft.rotationQuaternion.copyFrom(this._deviceRoomRotationQuaternion);
  78309. camRight.rotationQuaternion.copyFrom(this._deviceRoomRotationQuaternion);
  78310. camLeft.position.copyFrom(this._deviceRoomPosition);
  78311. camRight.position.copyFrom(this._deviceRoomPosition);
  78312. };
  78313. /**
  78314. * Updates the cached values of the camera
  78315. * @param ignoreParentClass ignores updating the parent class's cache (default: false)
  78316. */
  78317. WebVRFreeCamera.prototype._updateCache = function (ignoreParentClass) {
  78318. var _this = this;
  78319. if (!this.rotationQuaternion.equals(this._cache.rotationQuaternion) || !this.position.equals(this._cache.position)) {
  78320. // Update to ensure devicePosition is up to date with most recent _deviceRoomPosition
  78321. if (!this.updateCacheCalled) {
  78322. // make sure it is only called once per loop. this.update() might cause an infinite loop.
  78323. this.updateCacheCalled = true;
  78324. this.update();
  78325. }
  78326. // Set working vector to the device position in room space rotated by the new rotation
  78327. this.rotationQuaternion.toRotationMatrix(this._workingMatrix);
  78328. BABYLON.Vector3.TransformCoordinatesToRef(this._deviceRoomPosition, this._workingMatrix, this._workingVector);
  78329. // Subtract this vector from the current device position in world to get the translation for the device world matrix
  78330. this.devicePosition.subtractToRef(this._workingVector, this._workingVector);
  78331. BABYLON.Matrix.ComposeToRef(this._oneVector, this.rotationQuaternion, this._workingVector, this._deviceToWorld);
  78332. // Add translation from anchor position
  78333. this._deviceToWorld.getTranslationToRef(this._workingVector);
  78334. this._workingVector.addInPlace(this.position);
  78335. this._workingVector.subtractInPlace(this._cache.position);
  78336. this._deviceToWorld.setTranslation(this._workingVector);
  78337. // Set an inverted matrix to be used when updating the camera
  78338. this._deviceToWorld.invertToRef(this._worldToDevice);
  78339. // Update the gamepad to ensure the mesh is updated on the same frame as camera
  78340. this.controllers.forEach(function (controller) {
  78341. controller._deviceToWorld = _this._deviceToWorld;
  78342. controller.update();
  78343. });
  78344. }
  78345. if (!ignoreParentClass) {
  78346. _super.prototype._updateCache.call(this);
  78347. }
  78348. this.updateCacheCalled = false;
  78349. };
  78350. /**
  78351. * Updates the current device position and rotation in the babylon world
  78352. */
  78353. WebVRFreeCamera.prototype.update = function () {
  78354. // Get current device position in babylon world
  78355. BABYLON.Vector3.TransformCoordinatesToRef(this._deviceRoomPosition, this._deviceToWorld, this.devicePosition);
  78356. // Get current device rotation in babylon world
  78357. BABYLON.Matrix.FromQuaternionToRef(this._deviceRoomRotationQuaternion, this._workingMatrix);
  78358. this._workingMatrix.multiplyToRef(this._deviceToWorld, this._workingMatrix);
  78359. BABYLON.Quaternion.FromRotationMatrixToRef(this._workingMatrix, this.deviceRotationQuaternion);
  78360. _super.prototype.update.call(this);
  78361. };
  78362. /**
  78363. * Gets the view matrix of this camera (Always set to identity as left and right eye cameras contain the actual view matrix)
  78364. * @returns an identity matrix
  78365. */
  78366. WebVRFreeCamera.prototype._getViewMatrix = function () {
  78367. return BABYLON.Matrix.Identity();
  78368. };
  78369. /**
  78370. * This function is called by the two RIG cameras.
  78371. * 'this' is the left or right camera (and NOT (!!!) the WebVRFreeCamera instance)
  78372. */
  78373. WebVRFreeCamera.prototype._getWebVRViewMatrix = function () {
  78374. var _this = this;
  78375. //WebVR 1.1
  78376. var viewArray = this._cameraRigParams["left"] ? this._cameraRigParams["frameData"].leftViewMatrix : this._cameraRigParams["frameData"].rightViewMatrix;
  78377. BABYLON.Matrix.FromArrayToRef(viewArray, 0, this._webvrViewMatrix);
  78378. if (!this.getScene().useRightHandedSystem) {
  78379. [2, 6, 8, 9, 14].forEach(function (num) {
  78380. _this._webvrViewMatrix.m[num] *= -1;
  78381. });
  78382. }
  78383. // update the camera rotation matrix
  78384. this._webvrViewMatrix.getRotationMatrixToRef(this._cameraRotationMatrix);
  78385. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  78386. // Computing target and final matrix
  78387. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  78388. var parentCamera = this._cameraRigParams["parentCamera"];
  78389. // should the view matrix be updated with scale and position offset?
  78390. if (parentCamera.deviceScaleFactor !== 1) {
  78391. this._webvrViewMatrix.invert();
  78392. // scale the position, if set
  78393. if (parentCamera.deviceScaleFactor) {
  78394. this._webvrViewMatrix.m[12] *= parentCamera.deviceScaleFactor;
  78395. this._webvrViewMatrix.m[13] *= parentCamera.deviceScaleFactor;
  78396. this._webvrViewMatrix.m[14] *= parentCamera.deviceScaleFactor;
  78397. }
  78398. this._webvrViewMatrix.invert();
  78399. }
  78400. parentCamera._worldToDevice.multiplyToRef(this._webvrViewMatrix, this._webvrViewMatrix);
  78401. return this._webvrViewMatrix;
  78402. };
  78403. WebVRFreeCamera.prototype._getWebVRProjectionMatrix = function () {
  78404. var _this = this;
  78405. var parentCamera = this.parent;
  78406. parentCamera._vrDevice.depthNear = parentCamera.minZ;
  78407. parentCamera._vrDevice.depthFar = parentCamera.maxZ;
  78408. var projectionArray = this._cameraRigParams["left"] ? this._cameraRigParams["frameData"].leftProjectionMatrix : this._cameraRigParams["frameData"].rightProjectionMatrix;
  78409. BABYLON.Matrix.FromArrayToRef(projectionArray, 0, this._projectionMatrix);
  78410. //babylon compatible matrix
  78411. if (!this.getScene().useRightHandedSystem) {
  78412. [8, 9, 10, 11].forEach(function (num) {
  78413. _this._projectionMatrix.m[num] *= -1;
  78414. });
  78415. }
  78416. return this._projectionMatrix;
  78417. };
  78418. /**
  78419. * Initializes the controllers and their meshes
  78420. */
  78421. WebVRFreeCamera.prototype.initControllers = function () {
  78422. var _this = this;
  78423. this.controllers = [];
  78424. var manager = this.getScene().gamepadManager;
  78425. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  78426. if (gamepad.type === BABYLON.Gamepad.POSE_ENABLED) {
  78427. var webVrController = gamepad;
  78428. if (webVrController.defaultModel) {
  78429. webVrController.defaultModel.setEnabled(false);
  78430. }
  78431. if (webVrController.hand === "right") {
  78432. _this._rightController = null;
  78433. }
  78434. if (webVrController.hand === "left") {
  78435. _this._rightController = null;
  78436. }
  78437. var controllerIndex = _this.controllers.indexOf(webVrController);
  78438. if (controllerIndex !== -1) {
  78439. _this.controllers.splice(controllerIndex, 1);
  78440. }
  78441. }
  78442. });
  78443. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  78444. if (gamepad.type === BABYLON.Gamepad.POSE_ENABLED) {
  78445. var webVrController_1 = gamepad;
  78446. webVrController_1._deviceToWorld = _this._deviceToWorld;
  78447. if (_this.webVROptions.controllerMeshes) {
  78448. if (webVrController_1.defaultModel) {
  78449. webVrController_1.defaultModel.setEnabled(true);
  78450. }
  78451. else {
  78452. // Load the meshes
  78453. webVrController_1.initControllerMesh(_this.getScene(), function (loadedMesh) {
  78454. _this.onControllerMeshLoadedObservable.notifyObservers(webVrController_1);
  78455. if (_this.webVROptions.defaultLightingOnControllers) {
  78456. if (!_this._lightOnControllers) {
  78457. _this._lightOnControllers = new BABYLON.HemisphericLight("vrControllersLight", new BABYLON.Vector3(0, 1, 0), _this.getScene());
  78458. }
  78459. var activateLightOnSubMeshes_1 = function (mesh, light) {
  78460. var children = mesh.getChildren();
  78461. if (children.length !== 0) {
  78462. children.forEach(function (mesh) {
  78463. light.includedOnlyMeshes.push(mesh);
  78464. activateLightOnSubMeshes_1(mesh, light);
  78465. });
  78466. }
  78467. };
  78468. _this._lightOnControllers.includedOnlyMeshes.push(loadedMesh);
  78469. activateLightOnSubMeshes_1(loadedMesh, _this._lightOnControllers);
  78470. }
  78471. });
  78472. }
  78473. }
  78474. webVrController_1.attachToPoseControlledCamera(_this);
  78475. // since this is async - sanity check. Is the controller already stored?
  78476. if (_this.controllers.indexOf(webVrController_1) === -1) {
  78477. //add to the controllers array
  78478. _this.controllers.push(webVrController_1);
  78479. // Forced to add some control code for Vive as it doesn't always fill properly the "hand" property
  78480. // Sometimes, both controllers are set correctly (left and right), sometimes none, sometimes only one of them...
  78481. // So we're overriding setting left & right manually to be sure
  78482. var firstViveWandDetected = false;
  78483. for (var i = 0; i < _this.controllers.length; i++) {
  78484. if (_this.controllers[i].controllerType === BABYLON.PoseEnabledControllerType.VIVE) {
  78485. if (!firstViveWandDetected) {
  78486. firstViveWandDetected = true;
  78487. _this.controllers[i].hand = "left";
  78488. }
  78489. else {
  78490. _this.controllers[i].hand = "right";
  78491. }
  78492. }
  78493. }
  78494. //did we find enough controllers? Great! let the developer know.
  78495. if (_this.controllers.length >= 2) {
  78496. _this.onControllersAttachedObservable.notifyObservers(_this.controllers);
  78497. }
  78498. }
  78499. }
  78500. });
  78501. };
  78502. return WebVRFreeCamera;
  78503. }(BABYLON.FreeCamera));
  78504. BABYLON.WebVRFreeCamera = WebVRFreeCamera;
  78505. })(BABYLON || (BABYLON = {}));
  78506. //# sourceMappingURL=babylon.webVRCamera.js.map
  78507. var BABYLON;
  78508. (function (BABYLON) {
  78509. // We're mainly based on the logic defined into the FreeCamera code
  78510. /**
  78511. * This is a camera specifically designed to react to device orientation events such as a modern mobile device
  78512. * being tilted forward or back and left or right.
  78513. */
  78514. var DeviceOrientationCamera = /** @class */ (function (_super) {
  78515. __extends(DeviceOrientationCamera, _super);
  78516. /**
  78517. * Creates a new device orientation camera. @see DeviceOrientationCamera
  78518. * @param name The name of the camera
  78519. * @param position The start position camera
  78520. * @param scene The scene the camera belongs to
  78521. */
  78522. function DeviceOrientationCamera(name, position, scene) {
  78523. var _this = _super.call(this, name, position, scene) || this;
  78524. _this._quaternionCache = new BABYLON.Quaternion();
  78525. _this.inputs.addDeviceOrientation();
  78526. return _this;
  78527. }
  78528. /**
  78529. * Gets the current instance class name ("DeviceOrientationCamera").
  78530. * This helps avoiding instanceof at run time.
  78531. * @returns the class name
  78532. */
  78533. DeviceOrientationCamera.prototype.getClassName = function () {
  78534. return "DeviceOrientationCamera";
  78535. };
  78536. /**
  78537. * Checks and applies the current values of the inputs to the camera. (Internal use only)
  78538. */
  78539. DeviceOrientationCamera.prototype._checkInputs = function () {
  78540. _super.prototype._checkInputs.call(this);
  78541. this._quaternionCache.copyFrom(this.rotationQuaternion);
  78542. if (this._initialQuaternion) {
  78543. this._initialQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  78544. }
  78545. };
  78546. /**
  78547. * Reset the camera to its default orientation on the specified axis only.
  78548. * @param axis The axis to reset
  78549. */
  78550. DeviceOrientationCamera.prototype.resetToCurrentRotation = function (axis) {
  78551. var _this = this;
  78552. if (axis === void 0) { axis = BABYLON.Axis.Y; }
  78553. //can only work if this camera has a rotation quaternion already.
  78554. if (!this.rotationQuaternion)
  78555. return;
  78556. if (!this._initialQuaternion) {
  78557. this._initialQuaternion = new BABYLON.Quaternion();
  78558. }
  78559. this._initialQuaternion.copyFrom(this._quaternionCache || this.rotationQuaternion);
  78560. ['x', 'y', 'z'].forEach(function (axisName) {
  78561. if (!axis[axisName]) {
  78562. _this._initialQuaternion[axisName] = 0;
  78563. }
  78564. else {
  78565. _this._initialQuaternion[axisName] *= -1;
  78566. }
  78567. });
  78568. this._initialQuaternion.normalize();
  78569. //force rotation update
  78570. this._initialQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  78571. };
  78572. return DeviceOrientationCamera;
  78573. }(BABYLON.FreeCamera));
  78574. BABYLON.DeviceOrientationCamera = DeviceOrientationCamera;
  78575. })(BABYLON || (BABYLON = {}));
  78576. //# sourceMappingURL=babylon.deviceOrientationCamera.js.map
  78577. var BABYLON;
  78578. (function (BABYLON) {
  78579. var VRDeviceOrientationFreeCamera = /** @class */ (function (_super) {
  78580. __extends(VRDeviceOrientationFreeCamera, _super);
  78581. function VRDeviceOrientationFreeCamera(name, position, scene, compensateDistortion, vrCameraMetrics) {
  78582. if (compensateDistortion === void 0) { compensateDistortion = true; }
  78583. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  78584. var _this = _super.call(this, name, position, scene) || this;
  78585. vrCameraMetrics.compensateDistortion = compensateDistortion;
  78586. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: vrCameraMetrics });
  78587. return _this;
  78588. }
  78589. VRDeviceOrientationFreeCamera.prototype.getClassName = function () {
  78590. return "VRDeviceOrientationFreeCamera";
  78591. };
  78592. return VRDeviceOrientationFreeCamera;
  78593. }(BABYLON.DeviceOrientationCamera));
  78594. BABYLON.VRDeviceOrientationFreeCamera = VRDeviceOrientationFreeCamera;
  78595. var VRDeviceOrientationGamepadCamera = /** @class */ (function (_super) {
  78596. __extends(VRDeviceOrientationGamepadCamera, _super);
  78597. function VRDeviceOrientationGamepadCamera(name, position, scene, compensateDistortion, vrCameraMetrics) {
  78598. if (compensateDistortion === void 0) { compensateDistortion = true; }
  78599. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  78600. var _this = _super.call(this, name, position, scene, compensateDistortion, vrCameraMetrics) || this;
  78601. _this.inputs.addGamepad();
  78602. return _this;
  78603. }
  78604. VRDeviceOrientationGamepadCamera.prototype.getClassName = function () {
  78605. return "VRDeviceOrientationGamepadCamera";
  78606. };
  78607. return VRDeviceOrientationGamepadCamera;
  78608. }(VRDeviceOrientationFreeCamera));
  78609. BABYLON.VRDeviceOrientationGamepadCamera = VRDeviceOrientationGamepadCamera;
  78610. var VRDeviceOrientationArcRotateCamera = /** @class */ (function (_super) {
  78611. __extends(VRDeviceOrientationArcRotateCamera, _super);
  78612. function VRDeviceOrientationArcRotateCamera(name, alpha, beta, radius, target, scene, compensateDistortion, vrCameraMetrics) {
  78613. if (compensateDistortion === void 0) { compensateDistortion = true; }
  78614. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  78615. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  78616. vrCameraMetrics.compensateDistortion = compensateDistortion;
  78617. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: vrCameraMetrics });
  78618. _this.inputs.addVRDeviceOrientation();
  78619. return _this;
  78620. }
  78621. VRDeviceOrientationArcRotateCamera.prototype.getClassName = function () {
  78622. return "VRDeviceOrientationArcRotateCamera";
  78623. };
  78624. return VRDeviceOrientationArcRotateCamera;
  78625. }(BABYLON.ArcRotateCamera));
  78626. BABYLON.VRDeviceOrientationArcRotateCamera = VRDeviceOrientationArcRotateCamera;
  78627. })(BABYLON || (BABYLON = {}));
  78628. //# sourceMappingURL=babylon.vrDeviceOrientationCamera.js.map
  78629. var BABYLON;
  78630. (function (BABYLON) {
  78631. var AnaglyphFreeCamera = /** @class */ (function (_super) {
  78632. __extends(AnaglyphFreeCamera, _super);
  78633. function AnaglyphFreeCamera(name, position, interaxialDistance, scene) {
  78634. var _this = _super.call(this, name, position, scene) || this;
  78635. _this.interaxialDistance = interaxialDistance;
  78636. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  78637. return _this;
  78638. }
  78639. AnaglyphFreeCamera.prototype.getClassName = function () {
  78640. return "AnaglyphFreeCamera";
  78641. };
  78642. return AnaglyphFreeCamera;
  78643. }(BABYLON.FreeCamera));
  78644. BABYLON.AnaglyphFreeCamera = AnaglyphFreeCamera;
  78645. var AnaglyphArcRotateCamera = /** @class */ (function (_super) {
  78646. __extends(AnaglyphArcRotateCamera, _super);
  78647. function AnaglyphArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, scene) {
  78648. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  78649. _this.interaxialDistance = interaxialDistance;
  78650. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  78651. return _this;
  78652. }
  78653. AnaglyphArcRotateCamera.prototype.getClassName = function () {
  78654. return "AnaglyphArcRotateCamera";
  78655. };
  78656. return AnaglyphArcRotateCamera;
  78657. }(BABYLON.ArcRotateCamera));
  78658. BABYLON.AnaglyphArcRotateCamera = AnaglyphArcRotateCamera;
  78659. var AnaglyphGamepadCamera = /** @class */ (function (_super) {
  78660. __extends(AnaglyphGamepadCamera, _super);
  78661. function AnaglyphGamepadCamera(name, position, interaxialDistance, scene) {
  78662. var _this = _super.call(this, name, position, scene) || this;
  78663. _this.interaxialDistance = interaxialDistance;
  78664. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  78665. return _this;
  78666. }
  78667. AnaglyphGamepadCamera.prototype.getClassName = function () {
  78668. return "AnaglyphGamepadCamera";
  78669. };
  78670. return AnaglyphGamepadCamera;
  78671. }(BABYLON.GamepadCamera));
  78672. BABYLON.AnaglyphGamepadCamera = AnaglyphGamepadCamera;
  78673. var AnaglyphUniversalCamera = /** @class */ (function (_super) {
  78674. __extends(AnaglyphUniversalCamera, _super);
  78675. function AnaglyphUniversalCamera(name, position, interaxialDistance, scene) {
  78676. var _this = _super.call(this, name, position, scene) || this;
  78677. _this.interaxialDistance = interaxialDistance;
  78678. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  78679. return _this;
  78680. }
  78681. AnaglyphUniversalCamera.prototype.getClassName = function () {
  78682. return "AnaglyphUniversalCamera";
  78683. };
  78684. return AnaglyphUniversalCamera;
  78685. }(BABYLON.UniversalCamera));
  78686. BABYLON.AnaglyphUniversalCamera = AnaglyphUniversalCamera;
  78687. var StereoscopicFreeCamera = /** @class */ (function (_super) {
  78688. __extends(StereoscopicFreeCamera, _super);
  78689. function StereoscopicFreeCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  78690. var _this = _super.call(this, name, position, scene) || this;
  78691. _this.interaxialDistance = interaxialDistance;
  78692. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  78693. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  78694. return _this;
  78695. }
  78696. StereoscopicFreeCamera.prototype.getClassName = function () {
  78697. return "StereoscopicFreeCamera";
  78698. };
  78699. return StereoscopicFreeCamera;
  78700. }(BABYLON.FreeCamera));
  78701. BABYLON.StereoscopicFreeCamera = StereoscopicFreeCamera;
  78702. var StereoscopicArcRotateCamera = /** @class */ (function (_super) {
  78703. __extends(StereoscopicArcRotateCamera, _super);
  78704. function StereoscopicArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, isStereoscopicSideBySide, scene) {
  78705. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  78706. _this.interaxialDistance = interaxialDistance;
  78707. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  78708. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  78709. return _this;
  78710. }
  78711. StereoscopicArcRotateCamera.prototype.getClassName = function () {
  78712. return "StereoscopicArcRotateCamera";
  78713. };
  78714. return StereoscopicArcRotateCamera;
  78715. }(BABYLON.ArcRotateCamera));
  78716. BABYLON.StereoscopicArcRotateCamera = StereoscopicArcRotateCamera;
  78717. var StereoscopicGamepadCamera = /** @class */ (function (_super) {
  78718. __extends(StereoscopicGamepadCamera, _super);
  78719. function StereoscopicGamepadCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  78720. var _this = _super.call(this, name, position, scene) || this;
  78721. _this.interaxialDistance = interaxialDistance;
  78722. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  78723. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  78724. return _this;
  78725. }
  78726. StereoscopicGamepadCamera.prototype.getClassName = function () {
  78727. return "StereoscopicGamepadCamera";
  78728. };
  78729. return StereoscopicGamepadCamera;
  78730. }(BABYLON.GamepadCamera));
  78731. BABYLON.StereoscopicGamepadCamera = StereoscopicGamepadCamera;
  78732. var StereoscopicUniversalCamera = /** @class */ (function (_super) {
  78733. __extends(StereoscopicUniversalCamera, _super);
  78734. function StereoscopicUniversalCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  78735. var _this = _super.call(this, name, position, scene) || this;
  78736. _this.interaxialDistance = interaxialDistance;
  78737. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  78738. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  78739. return _this;
  78740. }
  78741. StereoscopicUniversalCamera.prototype.getClassName = function () {
  78742. return "StereoscopicUniversalCamera";
  78743. };
  78744. return StereoscopicUniversalCamera;
  78745. }(BABYLON.UniversalCamera));
  78746. BABYLON.StereoscopicUniversalCamera = StereoscopicUniversalCamera;
  78747. })(BABYLON || (BABYLON = {}));
  78748. //# sourceMappingURL=babylon.stereoscopicCameras.js.map
  78749. var BABYLON;
  78750. (function (BABYLON) {
  78751. /**
  78752. * Helps to quickly add VR support to an existing scene.
  78753. * See http://doc.babylonjs.com/how_to/webvr_helper
  78754. */
  78755. var VRExperienceHelper = /** @class */ (function () {
  78756. /**
  78757. * Instantiates a VRExperienceHelper.
  78758. * Helps to quickly add VR support to an existing scene.
  78759. * @param scene The scene the VRExperienceHelper belongs to.
  78760. * @param webVROptions Options to modify the vr experience helper's behavior.
  78761. */
  78762. function VRExperienceHelper(scene, /** Options to modify the vr experience helper's behavior. */ webVROptions) {
  78763. if (webVROptions === void 0) { webVROptions = {}; }
  78764. var _this = this;
  78765. this.webVROptions = webVROptions;
  78766. // Can the system support WebVR, even if a headset isn't plugged in?
  78767. this._webVRsupported = false;
  78768. // If WebVR is supported, is a headset plugged in and are we ready to present?
  78769. this._webVRready = false;
  78770. // Are we waiting for the requestPresent callback to complete?
  78771. this._webVRrequesting = false;
  78772. // Are we presenting to the headset right now?
  78773. this._webVRpresenting = false;
  78774. // Are we presenting in the fullscreen fallback?
  78775. this._fullscreenVRpresenting = false;
  78776. /**
  78777. * Observable raised when entering VR.
  78778. */
  78779. this.onEnteringVRObservable = new BABYLON.Observable();
  78780. /**
  78781. * Observable raised when exiting VR.
  78782. */
  78783. this.onExitingVRObservable = new BABYLON.Observable();
  78784. /**
  78785. * Observable raised when controller mesh is loaded.
  78786. */
  78787. this.onControllerMeshLoadedObservable = new BABYLON.Observable();
  78788. this._useCustomVRButton = false;
  78789. this._teleportationRequested = false;
  78790. this._teleportationEnabledOnLeftController = false;
  78791. this._teleportationEnabledOnRightController = false;
  78792. this._interactionsEnabledOnLeftController = false;
  78793. this._interactionsEnabledOnRightController = false;
  78794. this._leftControllerReady = false;
  78795. this._rightControllerReady = false;
  78796. this._floorMeshesCollection = [];
  78797. this._teleportationAllowed = false;
  78798. this._rotationAllowed = true;
  78799. this._teleportationRequestInitiated = false;
  78800. this._teleportationBackRequestInitiated = false;
  78801. this.teleportBackwardsVector = new BABYLON.Vector3(0, -1, -1);
  78802. this._rotationRightAsked = false;
  78803. this._rotationLeftAsked = false;
  78804. this._isDefaultTeleportationTarget = true;
  78805. this._teleportationFillColor = "#444444";
  78806. this._teleportationBorderColor = "#FFFFFF";
  78807. this._rotationAngle = 0;
  78808. this._haloCenter = new BABYLON.Vector3(0, 0, 0);
  78809. this._padSensibilityUp = 0.65;
  78810. this._padSensibilityDown = 0.35;
  78811. /**
  78812. * Observable raised when a new mesh is selected based on meshSelectionPredicate
  78813. */
  78814. this.onNewMeshSelected = new BABYLON.Observable();
  78815. /**
  78816. * Observable raised when a new mesh is picked based on meshSelectionPredicate
  78817. */
  78818. this.onNewMeshPicked = new BABYLON.Observable();
  78819. /**
  78820. * Observable raised before camera teleportation
  78821. */
  78822. this.onBeforeCameraTeleport = new BABYLON.Observable();
  78823. /**
  78824. * Observable raised after camera teleportation
  78825. */
  78826. this.onAfterCameraTeleport = new BABYLON.Observable();
  78827. /**
  78828. * Observable raised when current selected mesh gets unselected
  78829. */
  78830. this.onSelectedMeshUnselected = new BABYLON.Observable();
  78831. /**
  78832. * Set teleportation enabled. If set to false camera teleportation will be disabled but camera rotation will be kept.
  78833. */
  78834. this.teleportationEnabled = true;
  78835. this._pointerDownOnMeshAsked = false;
  78836. this._isActionableMesh = false;
  78837. this._teleportationInitialized = false;
  78838. this._interactionsEnabled = false;
  78839. this._interactionsRequested = false;
  78840. this._displayGaze = true;
  78841. this._displayLaserPointer = true;
  78842. this._dpadPressed = true;
  78843. this._onResize = function () {
  78844. _this.moveButtonToBottomRight();
  78845. if (_this._fullscreenVRpresenting && _this._webVRready) {
  78846. _this.exitVR();
  78847. }
  78848. };
  78849. this._onFullscreenChange = function () {
  78850. if (document.fullscreen !== undefined) {
  78851. _this._fullscreenVRpresenting = document.fullscreen;
  78852. }
  78853. else if (document.mozFullScreen !== undefined) {
  78854. _this._fullscreenVRpresenting = document.mozFullScreen;
  78855. }
  78856. else if (document.webkitIsFullScreen !== undefined) {
  78857. _this._fullscreenVRpresenting = document.webkitIsFullScreen;
  78858. }
  78859. else if (document.msIsFullScreen !== undefined) {
  78860. _this._fullscreenVRpresenting = document.msIsFullScreen;
  78861. }
  78862. if (!_this._fullscreenVRpresenting && _this._canvas) {
  78863. _this.exitVR();
  78864. if (!_this._useCustomVRButton) {
  78865. _this._btnVR.style.top = _this._canvas.offsetTop + _this._canvas.offsetHeight - 70 + "px";
  78866. _this._btnVR.style.left = _this._canvas.offsetLeft + _this._canvas.offsetWidth - 100 + "px";
  78867. }
  78868. }
  78869. };
  78870. this.beforeRender = function () {
  78871. _this._castRayAndSelectObject();
  78872. };
  78873. this._onNewGamepadConnected = function (gamepad) {
  78874. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  78875. if (gamepad.leftStick) {
  78876. gamepad.onleftstickchanged(function (stickValues) {
  78877. if (_this._teleportationInitialized && _this.teleportationEnabled) {
  78878. // Listening to classic/xbox gamepad only if no VR controller is active
  78879. if ((!_this._leftLaserPointer && !_this._rightLaserPointer) ||
  78880. ((_this._leftLaserPointer && !_this._leftLaserPointer.isVisible) &&
  78881. (_this._rightLaserPointer && !_this._rightLaserPointer.isVisible))) {
  78882. _this._checkTeleportWithRay(stickValues);
  78883. _this._checkTeleportBackwards(stickValues);
  78884. }
  78885. }
  78886. });
  78887. }
  78888. if (gamepad.rightStick) {
  78889. gamepad.onrightstickchanged(function (stickValues) {
  78890. if (_this._teleportationInitialized) {
  78891. _this._checkRotate(stickValues);
  78892. }
  78893. });
  78894. }
  78895. if (gamepad.type === BABYLON.Gamepad.XBOX) {
  78896. gamepad.onbuttondown(function (buttonPressed) {
  78897. if (_this._interactionsEnabled && buttonPressed === BABYLON.Xbox360Button.A) {
  78898. _this._selectionPointerDown();
  78899. }
  78900. });
  78901. gamepad.onbuttonup(function (buttonPressed) {
  78902. if (_this._interactionsEnabled && buttonPressed === BABYLON.Xbox360Button.A) {
  78903. _this._selectionPointerUp();
  78904. }
  78905. });
  78906. }
  78907. }
  78908. else {
  78909. var webVRController = gamepad;
  78910. _this._tryEnableInteractionOnController(webVRController);
  78911. }
  78912. };
  78913. // 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
  78914. this._tryEnableInteractionOnController = function (webVRController) {
  78915. if (webVRController.hand === "left") {
  78916. _this._leftControllerReady = true;
  78917. if (_this._interactionsRequested && !_this._interactionsEnabledOnLeftController) {
  78918. _this._enableInteractionOnController(webVRController);
  78919. }
  78920. if (_this._teleportationRequested && !_this._teleportationEnabledOnLeftController) {
  78921. _this._enableTeleportationOnController(webVRController);
  78922. }
  78923. }
  78924. if (webVRController.hand === "right") {
  78925. _this._rightControllerReady = true;
  78926. if (_this._interactionsRequested && !_this._interactionsEnabledOnRightController) {
  78927. _this._enableInteractionOnController(webVRController);
  78928. }
  78929. if (_this._teleportationRequested && !_this._teleportationEnabledOnRightController) {
  78930. _this._enableTeleportationOnController(webVRController);
  78931. }
  78932. }
  78933. };
  78934. this._onNewGamepadDisconnected = function (gamepad) {
  78935. if (gamepad instanceof BABYLON.WebVRController) {
  78936. if (gamepad.hand === "left") {
  78937. _this._interactionsEnabledOnLeftController = false;
  78938. _this._teleportationEnabledOnLeftController = false;
  78939. _this._leftControllerReady = false;
  78940. if (_this._leftLaserPointer) {
  78941. _this._leftLaserPointer.dispose();
  78942. }
  78943. }
  78944. if (gamepad.hand === "right") {
  78945. _this._interactionsEnabledOnRightController = false;
  78946. _this._teleportationEnabledOnRightController = false;
  78947. _this._rightControllerReady = false;
  78948. if (_this._rightLaserPointer) {
  78949. _this._rightLaserPointer.dispose();
  78950. }
  78951. }
  78952. }
  78953. };
  78954. this._workingVector = BABYLON.Vector3.Zero();
  78955. this._workingQuaternion = BABYLON.Quaternion.Identity();
  78956. this._workingMatrix = BABYLON.Matrix.Identity();
  78957. this._scene = scene;
  78958. this._canvas = scene.getEngine().getRenderingCanvas();
  78959. // Parse options
  78960. if (webVROptions.createFallbackVRDeviceOrientationFreeCamera === undefined) {
  78961. webVROptions.createFallbackVRDeviceOrientationFreeCamera = true;
  78962. }
  78963. if (webVROptions.createDeviceOrientationCamera === undefined) {
  78964. webVROptions.createDeviceOrientationCamera = true;
  78965. }
  78966. if (webVROptions.defaultHeight === undefined) {
  78967. webVROptions.defaultHeight = 1.7;
  78968. }
  78969. if (webVROptions.useCustomVRButton) {
  78970. this._useCustomVRButton = true;
  78971. if (webVROptions.customVRButton) {
  78972. this._btnVR = webVROptions.customVRButton;
  78973. }
  78974. }
  78975. if (webVROptions.rayLength) {
  78976. this._rayLength = webVROptions.rayLength;
  78977. }
  78978. this._defaultHeight = webVROptions.defaultHeight;
  78979. // Set position
  78980. if (this._scene.activeCamera) {
  78981. this._position = this._scene.activeCamera.position.clone();
  78982. }
  78983. else {
  78984. this._position = new BABYLON.Vector3(0, this._defaultHeight, 0);
  78985. }
  78986. // Set non-vr camera
  78987. if (webVROptions.createDeviceOrientationCamera || !this._scene.activeCamera) {
  78988. this._deviceOrientationCamera = new BABYLON.DeviceOrientationCamera("deviceOrientationVRHelper", this._position.clone(), scene);
  78989. // Copy data from existing camera
  78990. if (this._scene.activeCamera) {
  78991. this._deviceOrientationCamera.minZ = this._scene.activeCamera.minZ;
  78992. this._deviceOrientationCamera.maxZ = this._scene.activeCamera.maxZ;
  78993. // Set rotation from previous camera
  78994. if (this._scene.activeCamera instanceof BABYLON.TargetCamera && this._scene.activeCamera.rotation) {
  78995. var targetCamera = this._scene.activeCamera;
  78996. if (targetCamera.rotationQuaternion) {
  78997. this._deviceOrientationCamera.rotationQuaternion.copyFrom(targetCamera.rotationQuaternion);
  78998. }
  78999. else {
  79000. this._deviceOrientationCamera.rotationQuaternion.copyFrom(BABYLON.Quaternion.RotationYawPitchRoll(targetCamera.rotation.y, targetCamera.rotation.x, targetCamera.rotation.z));
  79001. }
  79002. this._deviceOrientationCamera.rotation = targetCamera.rotation.clone();
  79003. }
  79004. }
  79005. this._scene.activeCamera = this._deviceOrientationCamera;
  79006. if (this._canvas) {
  79007. this._scene.activeCamera.attachControl(this._canvas);
  79008. }
  79009. }
  79010. else {
  79011. this._existingCamera = this._scene.activeCamera;
  79012. }
  79013. // Create VR cameras
  79014. if (webVROptions.createFallbackVRDeviceOrientationFreeCamera) {
  79015. this._vrDeviceOrientationCamera = new BABYLON.VRDeviceOrientationFreeCamera("VRDeviceOrientationVRHelper", this._position, this._scene);
  79016. }
  79017. this._webVRCamera = new BABYLON.WebVRFreeCamera("WebVRHelper", this._position, this._scene, webVROptions);
  79018. this._webVRCamera.useStandingMatrix();
  79019. // Create default button
  79020. if (!this._useCustomVRButton) {
  79021. this._btnVR = document.createElement("BUTTON");
  79022. this._btnVR.className = "babylonVRicon";
  79023. this._btnVR.id = "babylonVRiconbtn";
  79024. this._btnVR.title = "Click to switch to VR";
  79025. 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) }";
  79026. css += ".babylonVRicon.vrdisplaypresenting { display: none; }";
  79027. // TODO: Add user feedback so that they know what state the VRDisplay is in (disconnected, connected, entering-VR)
  79028. // css += ".babylonVRicon.vrdisplaysupported { }";
  79029. // css += ".babylonVRicon.vrdisplayready { }";
  79030. // css += ".babylonVRicon.vrdisplayrequesting { }";
  79031. var style = document.createElement('style');
  79032. style.appendChild(document.createTextNode(css));
  79033. document.getElementsByTagName('head')[0].appendChild(style);
  79034. this.moveButtonToBottomRight();
  79035. }
  79036. // VR button click event
  79037. if (this._btnVR) {
  79038. this._btnVR.addEventListener("click", function () {
  79039. if (!_this.isInVRMode) {
  79040. _this.enterVR();
  79041. }
  79042. else {
  79043. _this.exitVR();
  79044. }
  79045. });
  79046. }
  79047. // Window events
  79048. window.addEventListener("resize", this._onResize);
  79049. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  79050. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  79051. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  79052. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  79053. // Display vr button when headset is connected
  79054. if (webVROptions.createFallbackVRDeviceOrientationFreeCamera) {
  79055. this.displayVRButton();
  79056. }
  79057. else {
  79058. this._scene.getEngine().onVRDisplayChangedObservable.add(function (e) {
  79059. if (e.vrDisplay) {
  79060. _this.displayVRButton();
  79061. }
  79062. });
  79063. }
  79064. // Exiting VR mode using 'ESC' key on desktop
  79065. this._onKeyDown = function (event) {
  79066. if (event.keyCode === 27 && _this.isInVRMode) {
  79067. _this.exitVR();
  79068. }
  79069. };
  79070. document.addEventListener("keydown", this._onKeyDown);
  79071. // Exiting VR mode double tapping the touch screen
  79072. this._scene.onPrePointerObservable.add(function (pointerInfo, eventState) {
  79073. if (_this.isInVRMode) {
  79074. _this.exitVR();
  79075. if (_this._fullscreenVRpresenting) {
  79076. _this._scene.getEngine().switchFullscreen(true);
  79077. }
  79078. }
  79079. }, BABYLON.PointerEventTypes.POINTERDOUBLETAP, false);
  79080. // Listen for WebVR display changes
  79081. this._onVRDisplayChanged = function (eventArgs) { return _this.onVRDisplayChanged(eventArgs); };
  79082. this._onVrDisplayPresentChange = function () { return _this.onVrDisplayPresentChange(); };
  79083. this._onVRRequestPresentStart = function () {
  79084. _this._webVRrequesting = true;
  79085. _this.updateButtonVisibility();
  79086. };
  79087. this._onVRRequestPresentComplete = function (success) {
  79088. _this._webVRrequesting = false;
  79089. _this.updateButtonVisibility();
  79090. };
  79091. scene.getEngine().onVRDisplayChangedObservable.add(this._onVRDisplayChanged);
  79092. scene.getEngine().onVRRequestPresentStart.add(this._onVRRequestPresentStart);
  79093. scene.getEngine().onVRRequestPresentComplete.add(this._onVRRequestPresentComplete);
  79094. window.addEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  79095. scene.onDisposeObservable.add(function () {
  79096. _this.dispose();
  79097. });
  79098. // Gamepad connection events
  79099. this._webVRCamera.onControllerMeshLoadedObservable.add(function (webVRController) { return _this._onDefaultMeshLoaded(webVRController); });
  79100. this._scene.gamepadManager.onGamepadConnectedObservable.add(this._onNewGamepadConnected);
  79101. this._scene.gamepadManager.onGamepadDisconnectedObservable.add(this._onNewGamepadDisconnected);
  79102. this.updateButtonVisibility();
  79103. //create easing functions
  79104. this._circleEase = new BABYLON.CircleEase();
  79105. this._circleEase.setEasingMode(BABYLON.EasingFunction.EASINGMODE_EASEINOUT);
  79106. }
  79107. Object.defineProperty(VRExperienceHelper.prototype, "onEnteringVR", {
  79108. /** Return this.onEnteringVRObservable
  79109. * Note: This one is for backward compatibility. Please use onEnteringVRObservable directly
  79110. */
  79111. get: function () {
  79112. return this.onEnteringVRObservable;
  79113. },
  79114. enumerable: true,
  79115. configurable: true
  79116. });
  79117. Object.defineProperty(VRExperienceHelper.prototype, "onExitingVR", {
  79118. /** Return this.onExitingVRObservable
  79119. * Note: This one is for backward compatibility. Please use onExitingVRObservable directly
  79120. */
  79121. get: function () {
  79122. return this.onExitingVRObservable;
  79123. },
  79124. enumerable: true,
  79125. configurable: true
  79126. });
  79127. Object.defineProperty(VRExperienceHelper.prototype, "onControllerMeshLoaded", {
  79128. /** Return this.onControllerMeshLoadedObservable
  79129. * Note: This one is for backward compatibility. Please use onControllerMeshLoadedObservable directly
  79130. */
  79131. get: function () {
  79132. return this.onControllerMeshLoadedObservable;
  79133. },
  79134. enumerable: true,
  79135. configurable: true
  79136. });
  79137. Object.defineProperty(VRExperienceHelper.prototype, "teleportationTarget", {
  79138. /**
  79139. * The mesh used to display where the user is going to teleport.
  79140. */
  79141. get: function () {
  79142. return this._teleportationTarget;
  79143. },
  79144. /**
  79145. * Sets the mesh to be used to display where the user is going to teleport.
  79146. */
  79147. set: function (value) {
  79148. if (value) {
  79149. value.name = "teleportationTarget";
  79150. this._isDefaultTeleportationTarget = false;
  79151. this._teleportationTarget = value;
  79152. }
  79153. },
  79154. enumerable: true,
  79155. configurable: true
  79156. });
  79157. Object.defineProperty(VRExperienceHelper.prototype, "gazeTrackerMesh", {
  79158. /**
  79159. * The mesh used to display where the user is selecting,
  79160. * when set bakeCurrentTransformIntoVertices will be called on the mesh.
  79161. * See http://doc.babylonjs.com/resources/baking_transformations
  79162. */
  79163. get: function () {
  79164. return this._gazeTracker;
  79165. },
  79166. set: function (value) {
  79167. if (value) {
  79168. this._gazeTracker = value;
  79169. this._gazeTracker.bakeCurrentTransformIntoVertices();
  79170. this._gazeTracker.isPickable = false;
  79171. this._gazeTracker.isVisible = false;
  79172. }
  79173. },
  79174. enumerable: true,
  79175. configurable: true
  79176. });
  79177. Object.defineProperty(VRExperienceHelper.prototype, "displayGaze", {
  79178. /**
  79179. * If the ray of the gaze should be displayed.
  79180. */
  79181. get: function () {
  79182. return this._displayGaze;
  79183. },
  79184. /**
  79185. * Sets if the ray of the gaze should be displayed.
  79186. */
  79187. set: function (value) {
  79188. this._displayGaze = value;
  79189. if (!value) {
  79190. this._gazeTracker.isVisible = false;
  79191. }
  79192. },
  79193. enumerable: true,
  79194. configurable: true
  79195. });
  79196. Object.defineProperty(VRExperienceHelper.prototype, "displayLaserPointer", {
  79197. /**
  79198. * If the ray of the LaserPointer should be displayed.
  79199. */
  79200. get: function () {
  79201. return this._displayLaserPointer;
  79202. },
  79203. /**
  79204. * Sets if the ray of the LaserPointer should be displayed.
  79205. */
  79206. set: function (value) {
  79207. this._displayLaserPointer = value;
  79208. if (!value) {
  79209. if (this._rightLaserPointer) {
  79210. this._rightLaserPointer.isVisible = false;
  79211. }
  79212. if (this._leftLaserPointer) {
  79213. this._leftLaserPointer.isVisible = false;
  79214. }
  79215. }
  79216. else {
  79217. if (this._rightLaserPointer) {
  79218. this._rightLaserPointer.isVisible = true;
  79219. }
  79220. else if (this._leftLaserPointer) {
  79221. this._leftLaserPointer.isVisible = true;
  79222. }
  79223. }
  79224. },
  79225. enumerable: true,
  79226. configurable: true
  79227. });
  79228. Object.defineProperty(VRExperienceHelper.prototype, "deviceOrientationCamera", {
  79229. /**
  79230. * The deviceOrientationCamera used as the camera when not in VR.
  79231. */
  79232. get: function () {
  79233. return this._deviceOrientationCamera;
  79234. },
  79235. enumerable: true,
  79236. configurable: true
  79237. });
  79238. Object.defineProperty(VRExperienceHelper.prototype, "currentVRCamera", {
  79239. /**
  79240. * Based on the current WebVR support, returns the current VR camera used.
  79241. */
  79242. get: function () {
  79243. if (this._webVRready) {
  79244. return this._webVRCamera;
  79245. }
  79246. else {
  79247. return this._scene.activeCamera;
  79248. }
  79249. },
  79250. enumerable: true,
  79251. configurable: true
  79252. });
  79253. Object.defineProperty(VRExperienceHelper.prototype, "webVRCamera", {
  79254. /**
  79255. * The webVRCamera which is used when in VR.
  79256. */
  79257. get: function () {
  79258. return this._webVRCamera;
  79259. },
  79260. enumerable: true,
  79261. configurable: true
  79262. });
  79263. Object.defineProperty(VRExperienceHelper.prototype, "vrDeviceOrientationCamera", {
  79264. /**
  79265. * The deviceOrientationCamera that is used as a fallback when vr device is not connected.
  79266. */
  79267. get: function () {
  79268. return this._vrDeviceOrientationCamera;
  79269. },
  79270. enumerable: true,
  79271. configurable: true
  79272. });
  79273. // Raised when one of the controller has loaded successfully its associated default mesh
  79274. VRExperienceHelper.prototype._onDefaultMeshLoaded = function (webVRController) {
  79275. this._tryEnableInteractionOnController(webVRController);
  79276. try {
  79277. this.onControllerMeshLoadedObservable.notifyObservers(webVRController);
  79278. }
  79279. catch (err) {
  79280. BABYLON.Tools.Warn("Error in your custom logic onControllerMeshLoaded: " + err);
  79281. }
  79282. };
  79283. Object.defineProperty(VRExperienceHelper.prototype, "isInVRMode", {
  79284. /**
  79285. * Gets a value indicating if we are currently in VR mode.
  79286. */
  79287. get: function () {
  79288. return this._webVRpresenting || this._fullscreenVRpresenting;
  79289. },
  79290. enumerable: true,
  79291. configurable: true
  79292. });
  79293. VRExperienceHelper.prototype.onVrDisplayPresentChange = function () {
  79294. var vrDisplay = this._scene.getEngine().getVRDevice();
  79295. if (vrDisplay) {
  79296. var wasPresenting = this._webVRpresenting;
  79297. // A VR display is connected
  79298. this._webVRpresenting = vrDisplay.isPresenting;
  79299. if (wasPresenting && !this._webVRpresenting)
  79300. this.exitVR();
  79301. }
  79302. else {
  79303. BABYLON.Tools.Warn('Detected VRDisplayPresentChange on an unknown VRDisplay. Did you can enterVR on the vrExperienceHelper?');
  79304. }
  79305. this.updateButtonVisibility();
  79306. };
  79307. VRExperienceHelper.prototype.onVRDisplayChanged = function (eventArgs) {
  79308. this._webVRsupported = eventArgs.vrSupported;
  79309. this._webVRready = !!eventArgs.vrDisplay;
  79310. this._webVRpresenting = eventArgs.vrDisplay && eventArgs.vrDisplay.isPresenting;
  79311. this.updateButtonVisibility();
  79312. };
  79313. VRExperienceHelper.prototype.moveButtonToBottomRight = function () {
  79314. if (this._canvas && !this._useCustomVRButton) {
  79315. this._btnVR.style.top = this._canvas.offsetTop + this._canvas.offsetHeight - 70 + "px";
  79316. this._btnVR.style.left = this._canvas.offsetLeft + this._canvas.offsetWidth - 100 + "px";
  79317. }
  79318. };
  79319. VRExperienceHelper.prototype.displayVRButton = function () {
  79320. if (!this._useCustomVRButton && !this._btnVRDisplayed) {
  79321. document.body.appendChild(this._btnVR);
  79322. this._btnVRDisplayed = true;
  79323. }
  79324. };
  79325. VRExperienceHelper.prototype.updateButtonVisibility = function () {
  79326. if (!this._btnVR || this._useCustomVRButton) {
  79327. return;
  79328. }
  79329. this._btnVR.className = "babylonVRicon";
  79330. if (this.isInVRMode) {
  79331. this._btnVR.className += " vrdisplaypresenting";
  79332. }
  79333. else {
  79334. if (this._webVRready)
  79335. this._btnVR.className += " vrdisplayready";
  79336. if (this._webVRsupported)
  79337. this._btnVR.className += " vrdisplaysupported";
  79338. if (this._webVRrequesting)
  79339. this._btnVR.className += " vrdisplayrequesting";
  79340. }
  79341. };
  79342. /**
  79343. * Attempt to enter VR. If a headset is connected and ready, will request present on that.
  79344. * Otherwise, will use the fullscreen API.
  79345. */
  79346. VRExperienceHelper.prototype.enterVR = function () {
  79347. if (this.onEnteringVRObservable) {
  79348. try {
  79349. this.onEnteringVRObservable.notifyObservers(this);
  79350. }
  79351. catch (err) {
  79352. BABYLON.Tools.Warn("Error in your custom logic onEnteringVR: " + err);
  79353. }
  79354. }
  79355. if (this._scene.activeCamera) {
  79356. this._position = this._scene.activeCamera.position.clone();
  79357. // make sure that we return to the last active camera
  79358. this._existingCamera = this._scene.activeCamera;
  79359. }
  79360. if (this._webVRrequesting)
  79361. return;
  79362. // If WebVR is supported and a headset is connected
  79363. if (this._webVRready) {
  79364. if (!this._webVRpresenting) {
  79365. this._webVRCamera.position = this._position;
  79366. this._scene.activeCamera = this._webVRCamera;
  79367. }
  79368. }
  79369. else if (this._vrDeviceOrientationCamera) {
  79370. this._vrDeviceOrientationCamera.position = this._position;
  79371. this._scene.activeCamera = this._vrDeviceOrientationCamera;
  79372. this._scene.getEngine().switchFullscreen(true);
  79373. this.updateButtonVisibility();
  79374. }
  79375. if (this._scene.activeCamera && this._canvas) {
  79376. this._scene.activeCamera.attachControl(this._canvas);
  79377. }
  79378. if (this._interactionsEnabled) {
  79379. this._scene.registerBeforeRender(this.beforeRender);
  79380. }
  79381. };
  79382. /**
  79383. * Attempt to exit VR, or fullscreen.
  79384. */
  79385. VRExperienceHelper.prototype.exitVR = function () {
  79386. if (this.onExitingVRObservable) {
  79387. try {
  79388. this.onExitingVRObservable.notifyObservers(this);
  79389. }
  79390. catch (err) {
  79391. BABYLON.Tools.Warn("Error in your custom logic onExitingVR: " + err);
  79392. }
  79393. }
  79394. if (this._webVRpresenting) {
  79395. this._scene.getEngine().disableVR();
  79396. }
  79397. if (this._scene.activeCamera) {
  79398. this._position = this._scene.activeCamera.position.clone();
  79399. }
  79400. if (this._deviceOrientationCamera) {
  79401. this._deviceOrientationCamera.position = this._position;
  79402. this._scene.activeCamera = this._deviceOrientationCamera;
  79403. if (this._canvas) {
  79404. this._scene.activeCamera.attachControl(this._canvas);
  79405. }
  79406. }
  79407. else if (this._existingCamera) {
  79408. this._existingCamera.position = this._position;
  79409. this._scene.activeCamera = this._existingCamera;
  79410. }
  79411. this.updateButtonVisibility();
  79412. if (this._interactionsEnabled) {
  79413. this._scene.unregisterBeforeRender(this.beforeRender);
  79414. }
  79415. };
  79416. Object.defineProperty(VRExperienceHelper.prototype, "position", {
  79417. /**
  79418. * The position of the vr experience helper.
  79419. */
  79420. get: function () {
  79421. return this._position;
  79422. },
  79423. /**
  79424. * Sets the position of the vr experience helper.
  79425. */
  79426. set: function (value) {
  79427. this._position = value;
  79428. if (this._scene.activeCamera) {
  79429. this._scene.activeCamera.position = value;
  79430. }
  79431. },
  79432. enumerable: true,
  79433. configurable: true
  79434. });
  79435. /**
  79436. * Enables controllers and user interactions suck as selecting and object or clicking on an object.
  79437. */
  79438. VRExperienceHelper.prototype.enableInteractions = function () {
  79439. var _this = this;
  79440. if (!this._interactionsEnabled) {
  79441. this._interactionsRequested = true;
  79442. if (this._leftControllerReady && this._webVRCamera.leftController) {
  79443. this._enableInteractionOnController(this._webVRCamera.leftController);
  79444. }
  79445. if (this._rightControllerReady && this._webVRCamera.rightController) {
  79446. this._enableInteractionOnController(this._webVRCamera.rightController);
  79447. }
  79448. if (!this._gazeTracker) {
  79449. this._createGazeTracker();
  79450. }
  79451. this.raySelectionPredicate = function (mesh) {
  79452. return mesh.isVisible;
  79453. };
  79454. this.meshSelectionPredicate = function (mesh) {
  79455. return true;
  79456. };
  79457. this._raySelectionPredicate = function (mesh) {
  79458. if (_this._isTeleportationFloor(mesh) || (mesh != _this._gazeTracker
  79459. && mesh.name.indexOf("teleportationTarget") === -1
  79460. && mesh.name.indexOf("torusTeleportation") === -1
  79461. && mesh.name.indexOf("laserPointer") === -1)) {
  79462. return _this.raySelectionPredicate(mesh);
  79463. }
  79464. return false;
  79465. };
  79466. this._interactionsEnabled = true;
  79467. }
  79468. };
  79469. VRExperienceHelper.prototype._isTeleportationFloor = function (mesh) {
  79470. for (var i = 0; i < this._floorMeshesCollection.length; i++) {
  79471. if (this._floorMeshesCollection[i].id === mesh.id) {
  79472. return true;
  79473. }
  79474. }
  79475. if (this._floorMeshName && mesh.name === this._floorMeshName) {
  79476. return true;
  79477. }
  79478. return false;
  79479. };
  79480. /**
  79481. * Adds a floor mesh to be used for teleportation.
  79482. * @param floorMesh the mesh to be used for teleportation.
  79483. */
  79484. VRExperienceHelper.prototype.addFloorMesh = function (floorMesh) {
  79485. if (!this._floorMeshesCollection) {
  79486. return;
  79487. }
  79488. if (this._floorMeshesCollection.indexOf(floorMesh) > -1) {
  79489. return;
  79490. }
  79491. this._floorMeshesCollection.push(floorMesh);
  79492. };
  79493. /**
  79494. * Removes a floor mesh from being used for teleportation.
  79495. * @param floorMesh the mesh to be removed.
  79496. */
  79497. VRExperienceHelper.prototype.removeFloorMesh = function (floorMesh) {
  79498. if (!this._floorMeshesCollection) {
  79499. return;
  79500. }
  79501. var meshIndex = this._floorMeshesCollection.indexOf(floorMesh);
  79502. if (meshIndex !== -1) {
  79503. this._floorMeshesCollection.splice(meshIndex, 1);
  79504. }
  79505. };
  79506. /**
  79507. * Enables interactions and teleportation using the VR controllers and gaze.
  79508. * @param vrTeleportationOptions options to modify teleportation behavior.
  79509. */
  79510. VRExperienceHelper.prototype.enableTeleportation = function (vrTeleportationOptions) {
  79511. if (vrTeleportationOptions === void 0) { vrTeleportationOptions = {}; }
  79512. if (!this._teleportationInitialized) {
  79513. this._teleportationRequested = true;
  79514. this.enableInteractions();
  79515. if (vrTeleportationOptions.floorMeshName) {
  79516. this._floorMeshName = vrTeleportationOptions.floorMeshName;
  79517. }
  79518. if (vrTeleportationOptions.floorMeshes) {
  79519. this._floorMeshesCollection = vrTeleportationOptions.floorMeshes;
  79520. }
  79521. if (this._leftControllerReady && this._webVRCamera.leftController) {
  79522. this._enableTeleportationOnController(this._webVRCamera.leftController);
  79523. }
  79524. if (this._rightControllerReady && this._webVRCamera.rightController) {
  79525. this._enableTeleportationOnController(this._webVRCamera.rightController);
  79526. }
  79527. // Creates an image processing post process for the vignette not relying
  79528. // on the main scene configuration for image processing to reduce setup and spaces
  79529. // (gamma/linear) conflicts.
  79530. var imageProcessingConfiguration = new BABYLON.ImageProcessingConfiguration();
  79531. imageProcessingConfiguration.vignetteColor = new BABYLON.Color4(0, 0, 0, 0);
  79532. imageProcessingConfiguration.vignetteEnabled = true;
  79533. this._postProcessMove = new BABYLON.ImageProcessingPostProcess("postProcessMove", 1.0, this._webVRCamera, undefined, undefined, undefined, undefined, imageProcessingConfiguration);
  79534. this._webVRCamera.detachPostProcess(this._postProcessMove);
  79535. this._passProcessMove = new BABYLON.PassPostProcess("pass", 1.0, this._webVRCamera);
  79536. this._teleportationInitialized = true;
  79537. if (this._isDefaultTeleportationTarget) {
  79538. this._createTeleportationCircles();
  79539. }
  79540. }
  79541. };
  79542. VRExperienceHelper.prototype._enableInteractionOnController = function (webVRController) {
  79543. var _this = this;
  79544. var controllerMesh = webVRController.mesh;
  79545. if (controllerMesh) {
  79546. var makeNotPick = function (root) {
  79547. root.name += " laserPointer";
  79548. root.getChildMeshes().forEach(function (c) {
  79549. makeNotPick(c);
  79550. });
  79551. };
  79552. makeNotPick(controllerMesh);
  79553. var childMeshes = controllerMesh.getChildMeshes();
  79554. for (var i = 0; i < childMeshes.length; i++) {
  79555. if (childMeshes[i].name && childMeshes[i].name.indexOf("POINTING_POSE") >= 0) {
  79556. controllerMesh = childMeshes[i];
  79557. break;
  79558. }
  79559. }
  79560. var laserPointer = BABYLON.Mesh.CreateCylinder("laserPointer", 1, 0.004, 0.0002, 20, 1, this._scene, false);
  79561. var laserPointerMaterial = new BABYLON.StandardMaterial("laserPointerMat", this._scene);
  79562. laserPointerMaterial.emissiveColor = new BABYLON.Color3(0.7, 0.7, 0.7);
  79563. laserPointerMaterial.alpha = 0.6;
  79564. laserPointer.material = laserPointerMaterial;
  79565. laserPointer.rotation.x = Math.PI / 2;
  79566. laserPointer.parent = controllerMesh;
  79567. laserPointer.position.z = -0.5;
  79568. laserPointer.isVisible = false;
  79569. if (webVRController.hand === "left") {
  79570. this._leftLaserPointer = laserPointer;
  79571. this._interactionsEnabledOnLeftController = true;
  79572. if (!this._rightLaserPointer) {
  79573. this._leftLaserPointer.isVisible = true;
  79574. }
  79575. }
  79576. else {
  79577. this._rightLaserPointer = laserPointer;
  79578. this._interactionsEnabledOnRightController = true;
  79579. if (!this._leftLaserPointer) {
  79580. this._rightLaserPointer.isVisible = true;
  79581. }
  79582. }
  79583. webVRController.onMainButtonStateChangedObservable.add(function (stateObject) {
  79584. // Enabling / disabling laserPointer
  79585. if (_this._displayLaserPointer && stateObject.value === 1) {
  79586. laserPointer.isVisible = !laserPointer.isVisible;
  79587. // Laser pointer can only be active on left or right, not both at the same time
  79588. if (webVRController.hand === "left" && _this._rightLaserPointer) {
  79589. _this._rightLaserPointer.isVisible = false;
  79590. }
  79591. else if (_this._leftLaserPointer) {
  79592. _this._leftLaserPointer.isVisible = false;
  79593. }
  79594. }
  79595. });
  79596. webVRController.onTriggerStateChangedObservable.add(function (stateObject) {
  79597. if (!_this._pointerDownOnMeshAsked) {
  79598. if (stateObject.value > _this._padSensibilityUp) {
  79599. _this._selectionPointerDown();
  79600. }
  79601. }
  79602. else if (stateObject.value < _this._padSensibilityDown) {
  79603. _this._selectionPointerUp();
  79604. }
  79605. });
  79606. }
  79607. };
  79608. VRExperienceHelper.prototype._checkTeleportWithRay = function (stateObject, webVRController) {
  79609. if (webVRController === void 0) { webVRController = null; }
  79610. if (!this._teleportationRequestInitiated) {
  79611. if (stateObject.y < -this._padSensibilityUp && this._dpadPressed) {
  79612. if (webVRController) {
  79613. // If laser pointer wasn't enabled yet
  79614. if (this._displayLaserPointer && webVRController.hand === "left" && this._leftLaserPointer) {
  79615. this._leftLaserPointer.isVisible = true;
  79616. if (this._rightLaserPointer) {
  79617. this._rightLaserPointer.isVisible = false;
  79618. }
  79619. }
  79620. else if (this._displayLaserPointer && this._rightLaserPointer) {
  79621. this._rightLaserPointer.isVisible = true;
  79622. if (this._leftLaserPointer) {
  79623. this._leftLaserPointer.isVisible = false;
  79624. }
  79625. }
  79626. }
  79627. this._teleportationRequestInitiated = true;
  79628. }
  79629. }
  79630. else {
  79631. // Listening to the proper controller values changes to confirm teleportation
  79632. if (webVRController == null
  79633. || (webVRController.hand === "left" && this._leftLaserPointer && this._leftLaserPointer.isVisible)
  79634. || (webVRController.hand === "right" && this._rightLaserPointer && this._rightLaserPointer.isVisible)) {
  79635. if (Math.sqrt(stateObject.y * stateObject.y + stateObject.x * stateObject.x) < this._padSensibilityDown) {
  79636. if (this._teleportationAllowed) {
  79637. this._teleportationAllowed = false;
  79638. this._teleportCamera();
  79639. }
  79640. this._teleportationRequestInitiated = false;
  79641. }
  79642. }
  79643. }
  79644. };
  79645. VRExperienceHelper.prototype._selectionPointerDown = function () {
  79646. this._pointerDownOnMeshAsked = true;
  79647. if (this._currentMeshSelected && this._currentHit) {
  79648. this._scene.simulatePointerDown(this._currentHit);
  79649. }
  79650. };
  79651. VRExperienceHelper.prototype._selectionPointerUp = function () {
  79652. if (this._currentMeshSelected && this._currentHit) {
  79653. this._scene.simulatePointerUp(this._currentHit);
  79654. }
  79655. this._pointerDownOnMeshAsked = false;
  79656. };
  79657. VRExperienceHelper.prototype._checkRotate = function (stateObject) {
  79658. // Only rotate when user is not currently selecting a teleportation location
  79659. if (this._teleportationRequestInitiated) {
  79660. return;
  79661. }
  79662. if (!this._rotationLeftAsked) {
  79663. if (stateObject.x < -this._padSensibilityUp && this._dpadPressed) {
  79664. this._rotationLeftAsked = true;
  79665. if (this._rotationAllowed) {
  79666. this._rotateCamera(false);
  79667. }
  79668. }
  79669. }
  79670. else {
  79671. if (stateObject.x > -this._padSensibilityDown) {
  79672. this._rotationLeftAsked = false;
  79673. }
  79674. }
  79675. if (!this._rotationRightAsked) {
  79676. if (stateObject.x > this._padSensibilityUp && this._dpadPressed) {
  79677. this._rotationRightAsked = true;
  79678. if (this._rotationAllowed) {
  79679. this._rotateCamera(true);
  79680. }
  79681. }
  79682. }
  79683. else {
  79684. if (stateObject.x < this._padSensibilityDown) {
  79685. this._rotationRightAsked = false;
  79686. }
  79687. }
  79688. };
  79689. VRExperienceHelper.prototype._checkTeleportBackwards = function (stateObject) {
  79690. // Only teleport backwards when user is not currently selecting a teleportation location
  79691. if (this._teleportationRequestInitiated) {
  79692. return;
  79693. }
  79694. // Teleport backwards
  79695. if (stateObject.y > this._padSensibilityUp && this._dpadPressed) {
  79696. if (!this._teleportationBackRequestInitiated) {
  79697. if (!this.currentVRCamera) {
  79698. return;
  79699. }
  79700. // Get rotation and position of the current camera
  79701. var rotation = BABYLON.Quaternion.FromRotationMatrix(this.currentVRCamera.getWorldMatrix().getRotationMatrix());
  79702. var position = this.currentVRCamera.position;
  79703. // If the camera has device position, use that instead
  79704. if (this.currentVRCamera.devicePosition && this.currentVRCamera.deviceRotationQuaternion) {
  79705. rotation = this.currentVRCamera.deviceRotationQuaternion;
  79706. position = this.currentVRCamera.devicePosition;
  79707. }
  79708. // Get matrix with only the y rotation of the device rotation
  79709. rotation.toEulerAnglesToRef(this._workingVector);
  79710. this._workingVector.z = 0;
  79711. this._workingVector.x = 0;
  79712. BABYLON.Quaternion.RotationYawPitchRollToRef(this._workingVector.y, this._workingVector.x, this._workingVector.z, this._workingQuaternion);
  79713. this._workingQuaternion.toRotationMatrix(this._workingMatrix);
  79714. // Rotate backwards ray by device rotation to cast at the ground behind the user
  79715. BABYLON.Vector3.TransformCoordinatesToRef(this.teleportBackwardsVector, this._workingMatrix, this._workingVector);
  79716. // Teleport if ray hit the ground and is not to far away eg. backwards off a cliff
  79717. var ray = new BABYLON.Ray(position, this._workingVector);
  79718. var hit = this._scene.pickWithRay(ray, this._raySelectionPredicate);
  79719. if (hit && hit.pickedPoint && hit.pickedMesh && this._isTeleportationFloor(hit.pickedMesh) && hit.distance < 5) {
  79720. this._teleportCamera(hit.pickedPoint);
  79721. }
  79722. this._teleportationBackRequestInitiated = true;
  79723. }
  79724. }
  79725. else {
  79726. this._teleportationBackRequestInitiated = false;
  79727. }
  79728. };
  79729. VRExperienceHelper.prototype._enableTeleportationOnController = function (webVRController) {
  79730. var _this = this;
  79731. var controllerMesh = webVRController.mesh;
  79732. if (controllerMesh) {
  79733. if (webVRController.hand === "left") {
  79734. if (!this._interactionsEnabledOnLeftController) {
  79735. this._enableInteractionOnController(webVRController);
  79736. }
  79737. this._teleportationEnabledOnLeftController = true;
  79738. }
  79739. else {
  79740. if (!this._interactionsEnabledOnRightController) {
  79741. this._enableInteractionOnController(webVRController);
  79742. }
  79743. this._teleportationEnabledOnRightController = true;
  79744. }
  79745. if (webVRController.controllerType === BABYLON.PoseEnabledControllerType.VIVE) {
  79746. this._dpadPressed = false;
  79747. webVRController.onPadStateChangedObservable.add(function (stateObject) {
  79748. _this._dpadPressed = stateObject.pressed;
  79749. if (!_this._dpadPressed) {
  79750. _this._rotationLeftAsked = false;
  79751. _this._rotationRightAsked = false;
  79752. _this._teleportationBackRequestInitiated = false;
  79753. }
  79754. });
  79755. }
  79756. webVRController.onPadValuesChangedObservable.add(function (stateObject) {
  79757. if (_this.teleportationEnabled) {
  79758. _this._checkTeleportBackwards(stateObject);
  79759. _this._checkTeleportWithRay(stateObject, webVRController);
  79760. }
  79761. _this._checkRotate(stateObject);
  79762. });
  79763. }
  79764. };
  79765. // Gaze support used to point to teleport or to interact with an object
  79766. VRExperienceHelper.prototype._createGazeTracker = function () {
  79767. this._gazeTracker = BABYLON.Mesh.CreateTorus("gazeTracker", 0.0035, 0.0025, 20, this._scene, false);
  79768. this._gazeTracker.bakeCurrentTransformIntoVertices();
  79769. this._gazeTracker.isPickable = false;
  79770. this._gazeTracker.isVisible = false;
  79771. var targetMat = new BABYLON.StandardMaterial("targetMat", this._scene);
  79772. targetMat.specularColor = BABYLON.Color3.Black();
  79773. targetMat.emissiveColor = new BABYLON.Color3(0.7, 0.7, 0.7);
  79774. targetMat.backFaceCulling = false;
  79775. this._gazeTracker.material = targetMat;
  79776. };
  79777. VRExperienceHelper.prototype._createTeleportationCircles = function () {
  79778. this._teleportationTarget = BABYLON.Mesh.CreateGround("teleportationTarget", 2, 2, 2, this._scene);
  79779. this._teleportationTarget.isPickable = false;
  79780. var length = 512;
  79781. var dynamicTexture = new BABYLON.DynamicTexture("DynamicTexture", length, this._scene, true);
  79782. dynamicTexture.hasAlpha = true;
  79783. var context = dynamicTexture.getContext();
  79784. var centerX = length / 2;
  79785. var centerY = length / 2;
  79786. var radius = 200;
  79787. context.beginPath();
  79788. context.arc(centerX, centerY, radius, 0, 2 * Math.PI, false);
  79789. context.fillStyle = this._teleportationFillColor;
  79790. context.fill();
  79791. context.lineWidth = 10;
  79792. context.strokeStyle = this._teleportationBorderColor;
  79793. context.stroke();
  79794. context.closePath();
  79795. dynamicTexture.update();
  79796. var teleportationCircleMaterial = new BABYLON.StandardMaterial("TextPlaneMaterial", this._scene);
  79797. teleportationCircleMaterial.diffuseTexture = dynamicTexture;
  79798. this._teleportationTarget.material = teleportationCircleMaterial;
  79799. var torus = BABYLON.Mesh.CreateTorus("torusTeleportation", 0.75, 0.1, 25, this._scene, false);
  79800. torus.isPickable = false;
  79801. torus.parent = this._teleportationTarget;
  79802. var animationInnerCircle = new BABYLON.Animation("animationInnerCircle", "position.y", 30, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  79803. var keys = [];
  79804. keys.push({
  79805. frame: 0,
  79806. value: 0
  79807. });
  79808. keys.push({
  79809. frame: 30,
  79810. value: 0.4
  79811. });
  79812. keys.push({
  79813. frame: 60,
  79814. value: 0
  79815. });
  79816. animationInnerCircle.setKeys(keys);
  79817. var easingFunction = new BABYLON.SineEase();
  79818. easingFunction.setEasingMode(BABYLON.EasingFunction.EASINGMODE_EASEINOUT);
  79819. animationInnerCircle.setEasingFunction(easingFunction);
  79820. torus.animations = [];
  79821. torus.animations.push(animationInnerCircle);
  79822. this._scene.beginAnimation(torus, 0, 60, true);
  79823. this._hideTeleportationTarget();
  79824. };
  79825. VRExperienceHelper.prototype._displayTeleportationTarget = function () {
  79826. if (this._teleportationInitialized) {
  79827. this._teleportationTarget.isVisible = true;
  79828. if (this._isDefaultTeleportationTarget) {
  79829. this._teleportationTarget.getChildren()[0].isVisible = true;
  79830. }
  79831. }
  79832. };
  79833. VRExperienceHelper.prototype._hideTeleportationTarget = function () {
  79834. if (this._teleportationInitialized) {
  79835. this._teleportationTarget.isVisible = false;
  79836. if (this._isDefaultTeleportationTarget) {
  79837. this._teleportationTarget.getChildren()[0].isVisible = false;
  79838. }
  79839. }
  79840. };
  79841. VRExperienceHelper.prototype._rotateCamera = function (right) {
  79842. var _this = this;
  79843. if (!(this.currentVRCamera instanceof BABYLON.FreeCamera)) {
  79844. return;
  79845. }
  79846. if (right) {
  79847. this._rotationAngle++;
  79848. }
  79849. else {
  79850. this._rotationAngle--;
  79851. }
  79852. this.currentVRCamera.animations = [];
  79853. var target = BABYLON.Quaternion.FromRotationMatrix(BABYLON.Matrix.RotationY(Math.PI / 4 * this._rotationAngle));
  79854. var animationRotation = new BABYLON.Animation("animationRotation", "rotationQuaternion", 90, BABYLON.Animation.ANIMATIONTYPE_QUATERNION, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  79855. var animationRotationKeys = [];
  79856. animationRotationKeys.push({
  79857. frame: 0,
  79858. value: this.currentVRCamera.rotationQuaternion
  79859. });
  79860. animationRotationKeys.push({
  79861. frame: 6,
  79862. value: target
  79863. });
  79864. animationRotation.setKeys(animationRotationKeys);
  79865. animationRotation.setEasingFunction(this._circleEase);
  79866. this.currentVRCamera.animations.push(animationRotation);
  79867. this._postProcessMove.animations = [];
  79868. var animationPP = new BABYLON.Animation("animationPP", "vignetteWeight", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  79869. var vignetteWeightKeys = [];
  79870. vignetteWeightKeys.push({
  79871. frame: 0,
  79872. value: 0
  79873. });
  79874. vignetteWeightKeys.push({
  79875. frame: 3,
  79876. value: 4
  79877. });
  79878. vignetteWeightKeys.push({
  79879. frame: 6,
  79880. value: 0
  79881. });
  79882. animationPP.setKeys(vignetteWeightKeys);
  79883. animationPP.setEasingFunction(this._circleEase);
  79884. this._postProcessMove.animations.push(animationPP);
  79885. var animationPP2 = new BABYLON.Animation("animationPP2", "vignetteStretch", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  79886. var vignetteStretchKeys = [];
  79887. vignetteStretchKeys.push({
  79888. frame: 0,
  79889. value: 0
  79890. });
  79891. vignetteStretchKeys.push({
  79892. frame: 3,
  79893. value: 10
  79894. });
  79895. vignetteStretchKeys.push({
  79896. frame: 6,
  79897. value: 0
  79898. });
  79899. animationPP2.setKeys(vignetteStretchKeys);
  79900. animationPP2.setEasingFunction(this._circleEase);
  79901. this._postProcessMove.animations.push(animationPP2);
  79902. this._postProcessMove.imageProcessingConfiguration.vignetteWeight = 0;
  79903. this._postProcessMove.imageProcessingConfiguration.vignetteStretch = 0;
  79904. this._webVRCamera.attachPostProcess(this._postProcessMove);
  79905. this._scene.beginAnimation(this._postProcessMove, 0, 6, false, 1, function () {
  79906. _this._webVRCamera.detachPostProcess(_this._postProcessMove);
  79907. });
  79908. this._scene.beginAnimation(this.currentVRCamera, 0, 6, false, 1);
  79909. };
  79910. VRExperienceHelper.prototype._moveTeleportationSelectorTo = function (hit) {
  79911. if (hit.pickedPoint) {
  79912. this._teleportationAllowed = true;
  79913. if (this._teleportationRequestInitiated) {
  79914. this._displayTeleportationTarget();
  79915. }
  79916. else {
  79917. this._hideTeleportationTarget();
  79918. }
  79919. this._haloCenter.copyFrom(hit.pickedPoint);
  79920. this._teleportationTarget.position.copyFrom(hit.pickedPoint);
  79921. var pickNormal = hit.getNormal(true, false);
  79922. if (pickNormal) {
  79923. var axis1 = BABYLON.Vector3.Cross(BABYLON.Axis.Y, pickNormal);
  79924. var axis2 = BABYLON.Vector3.Cross(pickNormal, axis1);
  79925. BABYLON.Vector3.RotationFromAxisToRef(axis2, pickNormal, axis1, this._teleportationTarget.rotation);
  79926. }
  79927. this._teleportationTarget.position.y += 0.1;
  79928. }
  79929. };
  79930. VRExperienceHelper.prototype._teleportCamera = function (location) {
  79931. var _this = this;
  79932. if (location === void 0) { location = null; }
  79933. if (!(this.currentVRCamera instanceof BABYLON.FreeCamera)) {
  79934. return;
  79935. }
  79936. if (!location) {
  79937. location = this._haloCenter;
  79938. }
  79939. // Teleport the hmd to where the user is looking by moving the anchor to where they are looking minus the
  79940. // offset of the headset from the anchor.
  79941. if (this.webVRCamera.leftCamera) {
  79942. this._workingVector.copyFrom(this.webVRCamera.leftCamera.globalPosition);
  79943. this._workingVector.subtractInPlace(this.webVRCamera.position);
  79944. location.subtractToRef(this._workingVector, this._workingVector);
  79945. }
  79946. else {
  79947. this._workingVector.copyFrom(location);
  79948. }
  79949. // Add height to account for user's height offset
  79950. if (this.isInVRMode) {
  79951. this._workingVector.y += this.webVRCamera.deviceDistanceToRoomGround();
  79952. }
  79953. else {
  79954. this._workingVector.y += this._defaultHeight;
  79955. }
  79956. this.onBeforeCameraTeleport.notifyObservers(this._workingVector);
  79957. // Create animation from the camera's position to the new location
  79958. this.currentVRCamera.animations = [];
  79959. var animationCameraTeleportation = new BABYLON.Animation("animationCameraTeleportation", "position", 90, BABYLON.Animation.ANIMATIONTYPE_VECTOR3, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  79960. var animationCameraTeleportationKeys = [{
  79961. frame: 0,
  79962. value: this.currentVRCamera.position
  79963. },
  79964. {
  79965. frame: 11,
  79966. value: this._workingVector
  79967. }
  79968. ];
  79969. animationCameraTeleportation.setKeys(animationCameraTeleportationKeys);
  79970. animationCameraTeleportation.setEasingFunction(this._circleEase);
  79971. this.currentVRCamera.animations.push(animationCameraTeleportation);
  79972. this._postProcessMove.animations = [];
  79973. var animationPP = new BABYLON.Animation("animationPP", "vignetteWeight", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  79974. var vignetteWeightKeys = [];
  79975. vignetteWeightKeys.push({
  79976. frame: 0,
  79977. value: 0
  79978. });
  79979. vignetteWeightKeys.push({
  79980. frame: 5,
  79981. value: 8
  79982. });
  79983. vignetteWeightKeys.push({
  79984. frame: 11,
  79985. value: 0
  79986. });
  79987. animationPP.setKeys(vignetteWeightKeys);
  79988. this._postProcessMove.animations.push(animationPP);
  79989. var animationPP2 = new BABYLON.Animation("animationPP2", "vignetteStretch", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  79990. var vignetteStretchKeys = [];
  79991. vignetteStretchKeys.push({
  79992. frame: 0,
  79993. value: 0
  79994. });
  79995. vignetteStretchKeys.push({
  79996. frame: 5,
  79997. value: 10
  79998. });
  79999. vignetteStretchKeys.push({
  80000. frame: 11,
  80001. value: 0
  80002. });
  80003. animationPP2.setKeys(vignetteStretchKeys);
  80004. this._postProcessMove.animations.push(animationPP2);
  80005. this._postProcessMove.imageProcessingConfiguration.vignetteWeight = 0;
  80006. this._postProcessMove.imageProcessingConfiguration.vignetteStretch = 0;
  80007. this._webVRCamera.attachPostProcess(this._postProcessMove);
  80008. this._scene.beginAnimation(this._postProcessMove, 0, 11, false, 1, function () {
  80009. _this._webVRCamera.detachPostProcess(_this._postProcessMove);
  80010. });
  80011. this._scene.beginAnimation(this.currentVRCamera, 0, 11, false, 1, function () {
  80012. _this.onAfterCameraTeleport.notifyObservers(_this._workingVector);
  80013. });
  80014. };
  80015. VRExperienceHelper.prototype._castRayAndSelectObject = function () {
  80016. if (!(this.currentVRCamera instanceof BABYLON.FreeCamera)) {
  80017. return;
  80018. }
  80019. var ray;
  80020. if (this._leftLaserPointer && this._leftLaserPointer.isVisible && this.currentVRCamera.leftController) {
  80021. ray = this.currentVRCamera.leftController.getForwardRay(this._rayLength);
  80022. }
  80023. else if (this._rightLaserPointer && this._rightLaserPointer.isVisible && this.currentVRCamera.rightController) {
  80024. ray = this.currentVRCamera.rightController.getForwardRay(this._rayLength);
  80025. }
  80026. else {
  80027. ray = this.currentVRCamera.getForwardRay(this._rayLength);
  80028. }
  80029. var hit = this._scene.pickWithRay(ray, this._raySelectionPredicate);
  80030. // Moving the gazeTracker on the mesh face targetted
  80031. if (hit && hit.pickedPoint) {
  80032. if (this._displayGaze) {
  80033. var multiplier = 1;
  80034. this._gazeTracker.isVisible = true;
  80035. if (this._isActionableMesh) {
  80036. multiplier = 3;
  80037. }
  80038. this._gazeTracker.scaling.x = hit.distance * multiplier;
  80039. this._gazeTracker.scaling.y = hit.distance * multiplier;
  80040. this._gazeTracker.scaling.z = hit.distance * multiplier;
  80041. var pickNormal = hit.getNormal();
  80042. // To avoid z-fighting
  80043. var deltaFighting = 0.002;
  80044. if (pickNormal) {
  80045. var axis1 = BABYLON.Vector3.Cross(BABYLON.Axis.Y, pickNormal);
  80046. var axis2 = BABYLON.Vector3.Cross(pickNormal, axis1);
  80047. BABYLON.Vector3.RotationFromAxisToRef(axis2, pickNormal, axis1, this._gazeTracker.rotation);
  80048. }
  80049. this._gazeTracker.position.copyFrom(hit.pickedPoint);
  80050. if (this._gazeTracker.position.x < 0) {
  80051. this._gazeTracker.position.x += deltaFighting;
  80052. }
  80053. else {
  80054. this._gazeTracker.position.x -= deltaFighting;
  80055. }
  80056. if (this._gazeTracker.position.y < 0) {
  80057. this._gazeTracker.position.y += deltaFighting;
  80058. }
  80059. else {
  80060. this._gazeTracker.position.y -= deltaFighting;
  80061. }
  80062. if (this._gazeTracker.position.z < 0) {
  80063. this._gazeTracker.position.z += deltaFighting;
  80064. }
  80065. else {
  80066. this._gazeTracker.position.z -= deltaFighting;
  80067. }
  80068. }
  80069. // Changing the size of the laser pointer based on the distance from the targetted point
  80070. if (this._rightLaserPointer && this._rightLaserPointer.isVisible) {
  80071. this._rightLaserPointer.scaling.y = hit.distance;
  80072. this._rightLaserPointer.position.z = -hit.distance / 2;
  80073. }
  80074. if (this._leftLaserPointer && this._leftLaserPointer.isVisible) {
  80075. this._leftLaserPointer.scaling.y = hit.distance;
  80076. this._leftLaserPointer.position.z = -hit.distance / 2;
  80077. }
  80078. }
  80079. else {
  80080. this._gazeTracker.isVisible = false;
  80081. }
  80082. if (hit && hit.pickedMesh) {
  80083. this._currentHit = hit;
  80084. if (this._pointerDownOnMeshAsked) {
  80085. this._scene.simulatePointerMove(this._currentHit);
  80086. }
  80087. // The object selected is the floor, we're in a teleportation scenario
  80088. if (this._teleportationInitialized && this._isTeleportationFloor(hit.pickedMesh) && hit.pickedPoint) {
  80089. // Moving the teleportation area to this targetted point
  80090. //Raise onSelectedMeshUnselected observable if ray collided floor mesh/meshes and a non floor mesh was previously selected
  80091. if (this._currentMeshSelected && !this._isTeleportationFloor(this._currentMeshSelected)) {
  80092. this._notifySelectedMeshUnselected();
  80093. }
  80094. this._currentMeshSelected = null;
  80095. this._moveTeleportationSelectorTo(hit);
  80096. return;
  80097. }
  80098. // If not, we're in a selection scenario
  80099. this._hideTeleportationTarget();
  80100. this._teleportationAllowed = false;
  80101. if (hit.pickedMesh !== this._currentMeshSelected) {
  80102. if (this.meshSelectionPredicate(hit.pickedMesh)) {
  80103. this.onNewMeshPicked.notifyObservers(hit);
  80104. this._currentMeshSelected = hit.pickedMesh;
  80105. if (hit.pickedMesh.isPickable && hit.pickedMesh.actionManager) {
  80106. this.changeGazeColor(new BABYLON.Color3(0, 0, 1));
  80107. this.changeLaserColor(new BABYLON.Color3(0.2, 0.2, 1));
  80108. this._isActionableMesh = true;
  80109. }
  80110. else {
  80111. this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  80112. this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  80113. this._isActionableMesh = false;
  80114. }
  80115. try {
  80116. this.onNewMeshSelected.notifyObservers(this._currentMeshSelected);
  80117. }
  80118. catch (err) {
  80119. BABYLON.Tools.Warn("Error in your custom logic onNewMeshSelected: " + err);
  80120. }
  80121. }
  80122. else {
  80123. this._notifySelectedMeshUnselected();
  80124. this._currentMeshSelected = null;
  80125. this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  80126. this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  80127. }
  80128. }
  80129. }
  80130. else {
  80131. this._currentHit = null;
  80132. this._notifySelectedMeshUnselected();
  80133. this._currentMeshSelected = null;
  80134. this._teleportationAllowed = false;
  80135. this._hideTeleportationTarget();
  80136. this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  80137. this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  80138. }
  80139. };
  80140. VRExperienceHelper.prototype._notifySelectedMeshUnselected = function () {
  80141. if (this._currentMeshSelected) {
  80142. this.onSelectedMeshUnselected.notifyObservers(this._currentMeshSelected);
  80143. }
  80144. };
  80145. /**
  80146. * Sets the color of the laser ray from the vr controllers.
  80147. * @param color new color for the ray.
  80148. */
  80149. VRExperienceHelper.prototype.changeLaserColor = function (color) {
  80150. if (this._leftLaserPointer && this._leftLaserPointer.material) {
  80151. this._leftLaserPointer.material.emissiveColor = color;
  80152. }
  80153. if (this._rightLaserPointer && this._rightLaserPointer.material) {
  80154. this._rightLaserPointer.material.emissiveColor = color;
  80155. }
  80156. };
  80157. /**
  80158. * Sets the color of the ray from the vr headsets gaze.
  80159. * @param color new color for the ray.
  80160. */
  80161. VRExperienceHelper.prototype.changeGazeColor = function (color) {
  80162. if (this._gazeTracker.material) {
  80163. this._gazeTracker.material.emissiveColor = color;
  80164. }
  80165. };
  80166. /**
  80167. * Exits VR and disposes of the vr experience helper
  80168. */
  80169. VRExperienceHelper.prototype.dispose = function () {
  80170. if (this.isInVRMode) {
  80171. this.exitVR();
  80172. }
  80173. if (this._passProcessMove) {
  80174. this._passProcessMove.dispose();
  80175. }
  80176. if (this._postProcessMove) {
  80177. this._postProcessMove.dispose();
  80178. }
  80179. if (this._webVRCamera) {
  80180. this._webVRCamera.dispose();
  80181. }
  80182. if (this._vrDeviceOrientationCamera) {
  80183. this._vrDeviceOrientationCamera.dispose();
  80184. }
  80185. if (!this._useCustomVRButton && this._btnVR.parentNode) {
  80186. document.body.removeChild(this._btnVR);
  80187. }
  80188. if (this._deviceOrientationCamera && (this._scene.activeCamera != this._deviceOrientationCamera)) {
  80189. this._deviceOrientationCamera.dispose();
  80190. }
  80191. if (this._gazeTracker) {
  80192. this._gazeTracker.dispose();
  80193. }
  80194. if (this._teleportationTarget) {
  80195. this._teleportationTarget.dispose();
  80196. }
  80197. this._floorMeshesCollection = [];
  80198. document.removeEventListener("keydown", this._onKeyDown);
  80199. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  80200. window.removeEventListener("resize", this._onResize);
  80201. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  80202. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  80203. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  80204. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  80205. this._scene.getEngine().onVRDisplayChangedObservable.removeCallback(this._onVRDisplayChanged);
  80206. this._scene.getEngine().onVRRequestPresentStart.removeCallback(this._onVRRequestPresentStart);
  80207. this._scene.getEngine().onVRRequestPresentComplete.removeCallback(this._onVRRequestPresentComplete);
  80208. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  80209. this._scene.gamepadManager.onGamepadConnectedObservable.removeCallback(this._onNewGamepadConnected);
  80210. this._scene.gamepadManager.onGamepadDisconnectedObservable.removeCallback(this._onNewGamepadDisconnected);
  80211. this._scene.unregisterBeforeRender(this.beforeRender);
  80212. };
  80213. /**
  80214. * Gets the name of the VRExperienceHelper class
  80215. * @returns "VRExperienceHelper"
  80216. */
  80217. VRExperienceHelper.prototype.getClassName = function () {
  80218. return "VRExperienceHelper";
  80219. };
  80220. return VRExperienceHelper;
  80221. }());
  80222. BABYLON.VRExperienceHelper = VRExperienceHelper;
  80223. })(BABYLON || (BABYLON = {}));
  80224. //# sourceMappingURL=babylon.vrExperienceHelper.js.map
  80225. // Mainly based on these 2 articles :
  80226. // 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
  80227. // & on Seb Lee-Delisle original work: http://seb.ly/2011/04/multi-touch-game-controller-in-javascripthtml5-for-ipad/
  80228. var BABYLON;
  80229. (function (BABYLON) {
  80230. var JoystickAxis;
  80231. (function (JoystickAxis) {
  80232. JoystickAxis[JoystickAxis["X"] = 0] = "X";
  80233. JoystickAxis[JoystickAxis["Y"] = 1] = "Y";
  80234. JoystickAxis[JoystickAxis["Z"] = 2] = "Z";
  80235. })(JoystickAxis = BABYLON.JoystickAxis || (BABYLON.JoystickAxis = {}));
  80236. var VirtualJoystick = /** @class */ (function () {
  80237. function VirtualJoystick(leftJoystick) {
  80238. var _this = this;
  80239. if (leftJoystick) {
  80240. this._leftJoystick = true;
  80241. }
  80242. else {
  80243. this._leftJoystick = false;
  80244. }
  80245. VirtualJoystick._globalJoystickIndex++;
  80246. // By default left & right arrow keys are moving the X
  80247. // and up & down keys are moving the Y
  80248. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  80249. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  80250. this.reverseLeftRight = false;
  80251. this.reverseUpDown = false;
  80252. // collections of pointers
  80253. this._touches = new BABYLON.StringDictionary();
  80254. this.deltaPosition = BABYLON.Vector3.Zero();
  80255. this._joystickSensibility = 25;
  80256. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  80257. this._onResize = function (evt) {
  80258. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  80259. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  80260. if (VirtualJoystick.vjCanvas) {
  80261. VirtualJoystick.vjCanvas.width = VirtualJoystick.vjCanvasWidth;
  80262. VirtualJoystick.vjCanvas.height = VirtualJoystick.vjCanvasHeight;
  80263. }
  80264. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvasWidth / 2;
  80265. };
  80266. // injecting a canvas element on top of the canvas 3D game
  80267. if (!VirtualJoystick.vjCanvas) {
  80268. window.addEventListener("resize", this._onResize, false);
  80269. VirtualJoystick.vjCanvas = document.createElement("canvas");
  80270. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  80271. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  80272. VirtualJoystick.vjCanvas.width = window.innerWidth;
  80273. VirtualJoystick.vjCanvas.height = window.innerHeight;
  80274. VirtualJoystick.vjCanvas.style.width = "100%";
  80275. VirtualJoystick.vjCanvas.style.height = "100%";
  80276. VirtualJoystick.vjCanvas.style.position = "absolute";
  80277. VirtualJoystick.vjCanvas.style.backgroundColor = "transparent";
  80278. VirtualJoystick.vjCanvas.style.top = "0px";
  80279. VirtualJoystick.vjCanvas.style.left = "0px";
  80280. VirtualJoystick.vjCanvas.style.zIndex = "5";
  80281. VirtualJoystick.vjCanvas.style.msTouchAction = "none";
  80282. // Support for jQuery PEP polyfill
  80283. VirtualJoystick.vjCanvas.setAttribute("touch-action", "none");
  80284. var context = VirtualJoystick.vjCanvas.getContext('2d');
  80285. if (!context) {
  80286. throw new Error("Unable to create canvas for virtual joystick");
  80287. }
  80288. VirtualJoystick.vjCanvasContext = context;
  80289. VirtualJoystick.vjCanvasContext.strokeStyle = "#ffffff";
  80290. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  80291. document.body.appendChild(VirtualJoystick.vjCanvas);
  80292. }
  80293. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvas.width / 2;
  80294. this.pressed = false;
  80295. // default joystick color
  80296. this._joystickColor = "cyan";
  80297. this._joystickPointerID = -1;
  80298. // current joystick position
  80299. this._joystickPointerPos = new BABYLON.Vector2(0, 0);
  80300. this._joystickPreviousPointerPos = new BABYLON.Vector2(0, 0);
  80301. // origin joystick position
  80302. this._joystickPointerStartPos = new BABYLON.Vector2(0, 0);
  80303. this._deltaJoystickVector = new BABYLON.Vector2(0, 0);
  80304. this._onPointerDownHandlerRef = function (evt) {
  80305. _this._onPointerDown(evt);
  80306. };
  80307. this._onPointerMoveHandlerRef = function (evt) {
  80308. _this._onPointerMove(evt);
  80309. };
  80310. this._onPointerUpHandlerRef = function (evt) {
  80311. _this._onPointerUp(evt);
  80312. };
  80313. VirtualJoystick.vjCanvas.addEventListener('pointerdown', this._onPointerDownHandlerRef, false);
  80314. VirtualJoystick.vjCanvas.addEventListener('pointermove', this._onPointerMoveHandlerRef, false);
  80315. VirtualJoystick.vjCanvas.addEventListener('pointerup', this._onPointerUpHandlerRef, false);
  80316. VirtualJoystick.vjCanvas.addEventListener('pointerout', this._onPointerUpHandlerRef, false);
  80317. VirtualJoystick.vjCanvas.addEventListener("contextmenu", function (evt) {
  80318. evt.preventDefault(); // Disables system menu
  80319. }, false);
  80320. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  80321. }
  80322. VirtualJoystick.prototype.setJoystickSensibility = function (newJoystickSensibility) {
  80323. this._joystickSensibility = newJoystickSensibility;
  80324. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  80325. };
  80326. VirtualJoystick.prototype._onPointerDown = function (e) {
  80327. var positionOnScreenCondition;
  80328. e.preventDefault();
  80329. if (this._leftJoystick === true) {
  80330. positionOnScreenCondition = (e.clientX < VirtualJoystick.halfWidth);
  80331. }
  80332. else {
  80333. positionOnScreenCondition = (e.clientX > VirtualJoystick.halfWidth);
  80334. }
  80335. if (positionOnScreenCondition && this._joystickPointerID < 0) {
  80336. // First contact will be dedicated to the virtual joystick
  80337. this._joystickPointerID = e.pointerId;
  80338. this._joystickPointerStartPos.x = e.clientX;
  80339. this._joystickPointerStartPos.y = e.clientY;
  80340. this._joystickPointerPos = this._joystickPointerStartPos.clone();
  80341. this._joystickPreviousPointerPos = this._joystickPointerStartPos.clone();
  80342. this._deltaJoystickVector.x = 0;
  80343. this._deltaJoystickVector.y = 0;
  80344. this.pressed = true;
  80345. this._touches.add(e.pointerId.toString(), e);
  80346. }
  80347. else {
  80348. // You can only trigger the action buttons with a joystick declared
  80349. if (VirtualJoystick._globalJoystickIndex < 2 && this._action) {
  80350. this._action();
  80351. this._touches.add(e.pointerId.toString(), { x: e.clientX, y: e.clientY, prevX: e.clientX, prevY: e.clientY });
  80352. }
  80353. }
  80354. };
  80355. VirtualJoystick.prototype._onPointerMove = function (e) {
  80356. // If the current pointer is the one associated to the joystick (first touch contact)
  80357. if (this._joystickPointerID == e.pointerId) {
  80358. this._joystickPointerPos.x = e.clientX;
  80359. this._joystickPointerPos.y = e.clientY;
  80360. this._deltaJoystickVector = this._joystickPointerPos.clone();
  80361. this._deltaJoystickVector = this._deltaJoystickVector.subtract(this._joystickPointerStartPos);
  80362. var directionLeftRight = this.reverseLeftRight ? -1 : 1;
  80363. var deltaJoystickX = directionLeftRight * this._deltaJoystickVector.x / this._inversedSensibility;
  80364. switch (this._axisTargetedByLeftAndRight) {
  80365. case JoystickAxis.X:
  80366. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickX));
  80367. break;
  80368. case JoystickAxis.Y:
  80369. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickX));
  80370. break;
  80371. case JoystickAxis.Z:
  80372. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickX));
  80373. break;
  80374. }
  80375. var directionUpDown = this.reverseUpDown ? 1 : -1;
  80376. var deltaJoystickY = directionUpDown * this._deltaJoystickVector.y / this._inversedSensibility;
  80377. switch (this._axisTargetedByUpAndDown) {
  80378. case JoystickAxis.X:
  80379. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickY));
  80380. break;
  80381. case JoystickAxis.Y:
  80382. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickY));
  80383. break;
  80384. case JoystickAxis.Z:
  80385. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickY));
  80386. break;
  80387. }
  80388. }
  80389. else {
  80390. var data = this._touches.get(e.pointerId.toString());
  80391. if (data) {
  80392. data.x = e.clientX;
  80393. data.y = e.clientY;
  80394. }
  80395. }
  80396. };
  80397. VirtualJoystick.prototype._onPointerUp = function (e) {
  80398. if (this._joystickPointerID == e.pointerId) {
  80399. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPointerStartPos.x - 64, this._joystickPointerStartPos.y - 64, 128, 128);
  80400. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPreviousPointerPos.x - 42, this._joystickPreviousPointerPos.y - 42, 84, 84);
  80401. this._joystickPointerID = -1;
  80402. this.pressed = false;
  80403. }
  80404. else {
  80405. var touch = this._touches.get(e.pointerId.toString());
  80406. if (touch) {
  80407. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 44, touch.prevY - 44, 88, 88);
  80408. }
  80409. }
  80410. this._deltaJoystickVector.x = 0;
  80411. this._deltaJoystickVector.y = 0;
  80412. this._touches.remove(e.pointerId.toString());
  80413. };
  80414. /**
  80415. * Change the color of the virtual joystick
  80416. * @param newColor a string that must be a CSS color value (like "red") or the hexa value (like "#FF0000")
  80417. */
  80418. VirtualJoystick.prototype.setJoystickColor = function (newColor) {
  80419. this._joystickColor = newColor;
  80420. };
  80421. VirtualJoystick.prototype.setActionOnTouch = function (action) {
  80422. this._action = action;
  80423. };
  80424. // Define which axis you'd like to control for left & right
  80425. VirtualJoystick.prototype.setAxisForLeftRight = function (axis) {
  80426. switch (axis) {
  80427. case JoystickAxis.X:
  80428. case JoystickAxis.Y:
  80429. case JoystickAxis.Z:
  80430. this._axisTargetedByLeftAndRight = axis;
  80431. break;
  80432. default:
  80433. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  80434. break;
  80435. }
  80436. };
  80437. // Define which axis you'd like to control for up & down
  80438. VirtualJoystick.prototype.setAxisForUpDown = function (axis) {
  80439. switch (axis) {
  80440. case JoystickAxis.X:
  80441. case JoystickAxis.Y:
  80442. case JoystickAxis.Z:
  80443. this._axisTargetedByUpAndDown = axis;
  80444. break;
  80445. default:
  80446. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  80447. break;
  80448. }
  80449. };
  80450. VirtualJoystick.prototype._drawVirtualJoystick = function () {
  80451. var _this = this;
  80452. if (this.pressed) {
  80453. this._touches.forEach(function (key, touch) {
  80454. if (touch.pointerId === _this._joystickPointerID) {
  80455. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPointerStartPos.x - 64, _this._joystickPointerStartPos.y - 64, 128, 128);
  80456. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPreviousPointerPos.x - 42, _this._joystickPreviousPointerPos.y - 42, 84, 84);
  80457. VirtualJoystick.vjCanvasContext.beginPath();
  80458. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  80459. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  80460. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 40, 0, Math.PI * 2, true);
  80461. VirtualJoystick.vjCanvasContext.stroke();
  80462. VirtualJoystick.vjCanvasContext.closePath();
  80463. VirtualJoystick.vjCanvasContext.beginPath();
  80464. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  80465. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  80466. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 60, 0, Math.PI * 2, true);
  80467. VirtualJoystick.vjCanvasContext.stroke();
  80468. VirtualJoystick.vjCanvasContext.closePath();
  80469. VirtualJoystick.vjCanvasContext.beginPath();
  80470. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  80471. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerPos.x, _this._joystickPointerPos.y, 40, 0, Math.PI * 2, true);
  80472. VirtualJoystick.vjCanvasContext.stroke();
  80473. VirtualJoystick.vjCanvasContext.closePath();
  80474. _this._joystickPreviousPointerPos = _this._joystickPointerPos.clone();
  80475. }
  80476. else {
  80477. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 44, touch.prevY - 44, 88, 88);
  80478. VirtualJoystick.vjCanvasContext.beginPath();
  80479. VirtualJoystick.vjCanvasContext.fillStyle = "white";
  80480. VirtualJoystick.vjCanvasContext.beginPath();
  80481. VirtualJoystick.vjCanvasContext.strokeStyle = "red";
  80482. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  80483. VirtualJoystick.vjCanvasContext.arc(touch.x, touch.y, 40, 0, Math.PI * 2, true);
  80484. VirtualJoystick.vjCanvasContext.stroke();
  80485. VirtualJoystick.vjCanvasContext.closePath();
  80486. touch.prevX = touch.x;
  80487. touch.prevY = touch.y;
  80488. }
  80489. ;
  80490. });
  80491. }
  80492. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  80493. };
  80494. VirtualJoystick.prototype.releaseCanvas = function () {
  80495. if (VirtualJoystick.vjCanvas) {
  80496. VirtualJoystick.vjCanvas.removeEventListener('pointerdown', this._onPointerDownHandlerRef);
  80497. VirtualJoystick.vjCanvas.removeEventListener('pointermove', this._onPointerMoveHandlerRef);
  80498. VirtualJoystick.vjCanvas.removeEventListener('pointerup', this._onPointerUpHandlerRef);
  80499. VirtualJoystick.vjCanvas.removeEventListener('pointerout', this._onPointerUpHandlerRef);
  80500. window.removeEventListener("resize", this._onResize);
  80501. document.body.removeChild(VirtualJoystick.vjCanvas);
  80502. VirtualJoystick.vjCanvas = null;
  80503. }
  80504. };
  80505. // Used to draw the virtual joystick inside a 2D canvas on top of the WebGL rendering canvas
  80506. VirtualJoystick._globalJoystickIndex = 0;
  80507. return VirtualJoystick;
  80508. }());
  80509. BABYLON.VirtualJoystick = VirtualJoystick;
  80510. })(BABYLON || (BABYLON = {}));
  80511. //# sourceMappingURL=babylon.virtualJoystick.js.map
  80512. var BABYLON;
  80513. (function (BABYLON) {
  80514. // We're mainly based on the logic defined into the FreeCamera code
  80515. var VirtualJoysticksCamera = /** @class */ (function (_super) {
  80516. __extends(VirtualJoysticksCamera, _super);
  80517. function VirtualJoysticksCamera(name, position, scene) {
  80518. var _this = _super.call(this, name, position, scene) || this;
  80519. _this.inputs.addVirtualJoystick();
  80520. return _this;
  80521. }
  80522. VirtualJoysticksCamera.prototype.getClassName = function () {
  80523. return "VirtualJoysticksCamera";
  80524. };
  80525. return VirtualJoysticksCamera;
  80526. }(BABYLON.FreeCamera));
  80527. BABYLON.VirtualJoysticksCamera = VirtualJoysticksCamera;
  80528. })(BABYLON || (BABYLON = {}));
  80529. //# sourceMappingURL=babylon.virtualJoysticksCamera.js.map
  80530. var BABYLON;
  80531. (function (BABYLON) {
  80532. var FreeCameraVirtualJoystickInput = /** @class */ (function () {
  80533. function FreeCameraVirtualJoystickInput() {
  80534. }
  80535. FreeCameraVirtualJoystickInput.prototype.getLeftJoystick = function () {
  80536. return this._leftjoystick;
  80537. };
  80538. FreeCameraVirtualJoystickInput.prototype.getRightJoystick = function () {
  80539. return this._rightjoystick;
  80540. };
  80541. FreeCameraVirtualJoystickInput.prototype.checkInputs = function () {
  80542. if (this._leftjoystick) {
  80543. var camera = this.camera;
  80544. var speed = camera._computeLocalCameraSpeed() * 50;
  80545. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(camera.rotation.y, camera.rotation.x, 0);
  80546. var deltaTransform = BABYLON.Vector3.TransformCoordinates(new BABYLON.Vector3(this._leftjoystick.deltaPosition.x * speed, this._leftjoystick.deltaPosition.y * speed, this._leftjoystick.deltaPosition.z * speed), cameraTransform);
  80547. camera.cameraDirection = camera.cameraDirection.add(deltaTransform);
  80548. camera.cameraRotation = camera.cameraRotation.addVector3(this._rightjoystick.deltaPosition);
  80549. if (!this._leftjoystick.pressed) {
  80550. this._leftjoystick.deltaPosition = this._leftjoystick.deltaPosition.scale(0.9);
  80551. }
  80552. if (!this._rightjoystick.pressed) {
  80553. this._rightjoystick.deltaPosition = this._rightjoystick.deltaPosition.scale(0.9);
  80554. }
  80555. }
  80556. };
  80557. FreeCameraVirtualJoystickInput.prototype.attachControl = function (element, noPreventDefault) {
  80558. this._leftjoystick = new BABYLON.VirtualJoystick(true);
  80559. this._leftjoystick.setAxisForUpDown(BABYLON.JoystickAxis.Z);
  80560. this._leftjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.X);
  80561. this._leftjoystick.setJoystickSensibility(0.15);
  80562. this._rightjoystick = new BABYLON.VirtualJoystick(false);
  80563. this._rightjoystick.setAxisForUpDown(BABYLON.JoystickAxis.X);
  80564. this._rightjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.Y);
  80565. this._rightjoystick.reverseUpDown = true;
  80566. this._rightjoystick.setJoystickSensibility(0.05);
  80567. this._rightjoystick.setJoystickColor("yellow");
  80568. };
  80569. FreeCameraVirtualJoystickInput.prototype.detachControl = function (element) {
  80570. this._leftjoystick.releaseCanvas();
  80571. this._rightjoystick.releaseCanvas();
  80572. };
  80573. FreeCameraVirtualJoystickInput.prototype.getClassName = function () {
  80574. return "FreeCameraVirtualJoystickInput";
  80575. };
  80576. FreeCameraVirtualJoystickInput.prototype.getSimpleName = function () {
  80577. return "virtualJoystick";
  80578. };
  80579. return FreeCameraVirtualJoystickInput;
  80580. }());
  80581. BABYLON.FreeCameraVirtualJoystickInput = FreeCameraVirtualJoystickInput;
  80582. BABYLON.CameraInputTypes["FreeCameraVirtualJoystickInput"] = FreeCameraVirtualJoystickInput;
  80583. })(BABYLON || (BABYLON = {}));
  80584. //# sourceMappingURL=babylon.freeCameraVirtualJoystickInput.js.map
  80585. var BABYLON;
  80586. (function (BABYLON) {
  80587. var SimplificationSettings = /** @class */ (function () {
  80588. function SimplificationSettings(quality, distance, optimizeMesh) {
  80589. this.quality = quality;
  80590. this.distance = distance;
  80591. this.optimizeMesh = optimizeMesh;
  80592. }
  80593. return SimplificationSettings;
  80594. }());
  80595. BABYLON.SimplificationSettings = SimplificationSettings;
  80596. var SimplificationQueue = /** @class */ (function () {
  80597. function SimplificationQueue() {
  80598. this.running = false;
  80599. this._simplificationArray = [];
  80600. }
  80601. SimplificationQueue.prototype.addTask = function (task) {
  80602. this._simplificationArray.push(task);
  80603. };
  80604. SimplificationQueue.prototype.executeNext = function () {
  80605. var task = this._simplificationArray.pop();
  80606. if (task) {
  80607. this.running = true;
  80608. this.runSimplification(task);
  80609. }
  80610. else {
  80611. this.running = false;
  80612. }
  80613. };
  80614. SimplificationQueue.prototype.runSimplification = function (task) {
  80615. var _this = this;
  80616. if (task.parallelProcessing) {
  80617. //parallel simplifier
  80618. task.settings.forEach(function (setting) {
  80619. var simplifier = _this.getSimplifier(task);
  80620. simplifier.simplify(setting, function (newMesh) {
  80621. task.mesh.addLODLevel(setting.distance, newMesh);
  80622. newMesh.isVisible = true;
  80623. //check if it is the last
  80624. if (setting.quality === task.settings[task.settings.length - 1].quality && task.successCallback) {
  80625. //all done, run the success callback.
  80626. task.successCallback();
  80627. }
  80628. _this.executeNext();
  80629. });
  80630. });
  80631. }
  80632. else {
  80633. //single simplifier.
  80634. var simplifier = this.getSimplifier(task);
  80635. var runDecimation = function (setting, callback) {
  80636. simplifier.simplify(setting, function (newMesh) {
  80637. task.mesh.addLODLevel(setting.distance, newMesh);
  80638. newMesh.isVisible = true;
  80639. //run the next quality level
  80640. callback();
  80641. });
  80642. };
  80643. BABYLON.AsyncLoop.Run(task.settings.length, function (loop) {
  80644. runDecimation(task.settings[loop.index], function () {
  80645. loop.executeNext();
  80646. });
  80647. }, function () {
  80648. //execution ended, run the success callback.
  80649. if (task.successCallback) {
  80650. task.successCallback();
  80651. }
  80652. _this.executeNext();
  80653. });
  80654. }
  80655. };
  80656. SimplificationQueue.prototype.getSimplifier = function (task) {
  80657. switch (task.simplificationType) {
  80658. case SimplificationType.QUADRATIC:
  80659. default:
  80660. return new QuadraticErrorSimplification(task.mesh);
  80661. }
  80662. };
  80663. return SimplificationQueue;
  80664. }());
  80665. BABYLON.SimplificationQueue = SimplificationQueue;
  80666. /**
  80667. * The implemented types of simplification.
  80668. * At the moment only Quadratic Error Decimation is implemented.
  80669. */
  80670. var SimplificationType;
  80671. (function (SimplificationType) {
  80672. SimplificationType[SimplificationType["QUADRATIC"] = 0] = "QUADRATIC";
  80673. })(SimplificationType = BABYLON.SimplificationType || (BABYLON.SimplificationType = {}));
  80674. var DecimationTriangle = /** @class */ (function () {
  80675. function DecimationTriangle(vertices) {
  80676. this.vertices = vertices;
  80677. this.error = new Array(4);
  80678. this.deleted = false;
  80679. this.isDirty = false;
  80680. this.deletePending = false;
  80681. this.borderFactor = 0;
  80682. }
  80683. return DecimationTriangle;
  80684. }());
  80685. BABYLON.DecimationTriangle = DecimationTriangle;
  80686. var DecimationVertex = /** @class */ (function () {
  80687. function DecimationVertex(position, id) {
  80688. this.position = position;
  80689. this.id = id;
  80690. this.isBorder = true;
  80691. this.q = new QuadraticMatrix();
  80692. this.triangleCount = 0;
  80693. this.triangleStart = 0;
  80694. this.originalOffsets = [];
  80695. }
  80696. DecimationVertex.prototype.updatePosition = function (newPosition) {
  80697. this.position.copyFrom(newPosition);
  80698. };
  80699. return DecimationVertex;
  80700. }());
  80701. BABYLON.DecimationVertex = DecimationVertex;
  80702. var QuadraticMatrix = /** @class */ (function () {
  80703. function QuadraticMatrix(data) {
  80704. this.data = new Array(10);
  80705. for (var i = 0; i < 10; ++i) {
  80706. if (data && data[i]) {
  80707. this.data[i] = data[i];
  80708. }
  80709. else {
  80710. this.data[i] = 0;
  80711. }
  80712. }
  80713. }
  80714. QuadraticMatrix.prototype.det = function (a11, a12, a13, a21, a22, a23, a31, a32, a33) {
  80715. var det = this.data[a11] * this.data[a22] * this.data[a33] + this.data[a13] * this.data[a21] * this.data[a32] +
  80716. this.data[a12] * this.data[a23] * this.data[a31] - this.data[a13] * this.data[a22] * this.data[a31] -
  80717. this.data[a11] * this.data[a23] * this.data[a32] - this.data[a12] * this.data[a21] * this.data[a33];
  80718. return det;
  80719. };
  80720. QuadraticMatrix.prototype.addInPlace = function (matrix) {
  80721. for (var i = 0; i < 10; ++i) {
  80722. this.data[i] += matrix.data[i];
  80723. }
  80724. };
  80725. QuadraticMatrix.prototype.addArrayInPlace = function (data) {
  80726. for (var i = 0; i < 10; ++i) {
  80727. this.data[i] += data[i];
  80728. }
  80729. };
  80730. QuadraticMatrix.prototype.add = function (matrix) {
  80731. var m = new QuadraticMatrix();
  80732. for (var i = 0; i < 10; ++i) {
  80733. m.data[i] = this.data[i] + matrix.data[i];
  80734. }
  80735. return m;
  80736. };
  80737. QuadraticMatrix.FromData = function (a, b, c, d) {
  80738. return new QuadraticMatrix(QuadraticMatrix.DataFromNumbers(a, b, c, d));
  80739. };
  80740. //returning an array to avoid garbage collection
  80741. QuadraticMatrix.DataFromNumbers = function (a, b, c, d) {
  80742. return [a * a, a * b, a * c, a * d, b * b, b * c, b * d, c * c, c * d, d * d];
  80743. };
  80744. return QuadraticMatrix;
  80745. }());
  80746. BABYLON.QuadraticMatrix = QuadraticMatrix;
  80747. var Reference = /** @class */ (function () {
  80748. function Reference(vertexId, triangleId) {
  80749. this.vertexId = vertexId;
  80750. this.triangleId = triangleId;
  80751. }
  80752. return Reference;
  80753. }());
  80754. BABYLON.Reference = Reference;
  80755. /**
  80756. * An implementation of the Quadratic Error simplification algorithm.
  80757. * Original paper : http://www1.cs.columbia.edu/~cs4162/html05s/garland97.pdf
  80758. * Ported mostly from QSlim and http://voxels.blogspot.de/2014/05/quadric-mesh-simplification-with-source.html to babylon JS
  80759. * @author RaananW
  80760. */
  80761. var QuadraticErrorSimplification = /** @class */ (function () {
  80762. function QuadraticErrorSimplification(_mesh) {
  80763. this._mesh = _mesh;
  80764. this.syncIterations = 5000;
  80765. this.aggressiveness = 7;
  80766. this.decimationIterations = 100;
  80767. this.boundingBoxEpsilon = BABYLON.Epsilon;
  80768. }
  80769. QuadraticErrorSimplification.prototype.simplify = function (settings, successCallback) {
  80770. var _this = this;
  80771. this.initDecimatedMesh();
  80772. //iterating through the submeshes array, one after the other.
  80773. BABYLON.AsyncLoop.Run(this._mesh.subMeshes.length, function (loop) {
  80774. _this.initWithMesh(loop.index, function () {
  80775. _this.runDecimation(settings, loop.index, function () {
  80776. loop.executeNext();
  80777. });
  80778. }, settings.optimizeMesh);
  80779. }, function () {
  80780. setTimeout(function () {
  80781. successCallback(_this._reconstructedMesh);
  80782. }, 0);
  80783. });
  80784. };
  80785. QuadraticErrorSimplification.prototype.runDecimation = function (settings, submeshIndex, successCallback) {
  80786. var _this = this;
  80787. var targetCount = ~~(this.triangles.length * settings.quality);
  80788. var deletedTriangles = 0;
  80789. var triangleCount = this.triangles.length;
  80790. var iterationFunction = function (iteration, callback) {
  80791. setTimeout(function () {
  80792. if (iteration % 5 === 0) {
  80793. _this.updateMesh(iteration === 0);
  80794. }
  80795. for (var i = 0; i < _this.triangles.length; ++i) {
  80796. _this.triangles[i].isDirty = false;
  80797. }
  80798. var threshold = 0.000000001 * Math.pow((iteration + 3), _this.aggressiveness);
  80799. var trianglesIterator = function (i) {
  80800. var tIdx = ~~(((_this.triangles.length / 2) + i) % _this.triangles.length);
  80801. var t = _this.triangles[tIdx];
  80802. if (!t)
  80803. return;
  80804. if (t.error[3] > threshold || t.deleted || t.isDirty) {
  80805. return;
  80806. }
  80807. for (var j = 0; j < 3; ++j) {
  80808. if (t.error[j] < threshold) {
  80809. var deleted0 = [];
  80810. var deleted1 = [];
  80811. var v0 = t.vertices[j];
  80812. var v1 = t.vertices[(j + 1) % 3];
  80813. if (v0.isBorder || v1.isBorder)
  80814. continue;
  80815. var p = BABYLON.Vector3.Zero();
  80816. var n = BABYLON.Vector3.Zero();
  80817. var uv = BABYLON.Vector2.Zero();
  80818. var color = new BABYLON.Color4(0, 0, 0, 1);
  80819. _this.calculateError(v0, v1, p, n, uv, color);
  80820. var delTr = new Array();
  80821. if (_this.isFlipped(v0, v1, p, deleted0, t.borderFactor, delTr))
  80822. continue;
  80823. if (_this.isFlipped(v1, v0, p, deleted1, t.borderFactor, delTr))
  80824. continue;
  80825. if (deleted0.indexOf(true) < 0 || deleted1.indexOf(true) < 0)
  80826. continue;
  80827. var uniqueArray = new Array();
  80828. delTr.forEach(function (deletedT) {
  80829. if (uniqueArray.indexOf(deletedT) === -1) {
  80830. deletedT.deletePending = true;
  80831. uniqueArray.push(deletedT);
  80832. }
  80833. });
  80834. if (uniqueArray.length % 2 !== 0) {
  80835. continue;
  80836. }
  80837. v0.q = v1.q.add(v0.q);
  80838. v0.updatePosition(p);
  80839. var tStart = _this.references.length;
  80840. deletedTriangles = _this.updateTriangles(v0, v0, deleted0, deletedTriangles);
  80841. deletedTriangles = _this.updateTriangles(v0, v1, deleted1, deletedTriangles);
  80842. var tCount = _this.references.length - tStart;
  80843. if (tCount <= v0.triangleCount) {
  80844. if (tCount) {
  80845. for (var c = 0; c < tCount; c++) {
  80846. _this.references[v0.triangleStart + c] = _this.references[tStart + c];
  80847. }
  80848. }
  80849. }
  80850. else {
  80851. v0.triangleStart = tStart;
  80852. }
  80853. v0.triangleCount = tCount;
  80854. break;
  80855. }
  80856. }
  80857. };
  80858. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, trianglesIterator, callback, function () { return (triangleCount - deletedTriangles <= targetCount); });
  80859. }, 0);
  80860. };
  80861. BABYLON.AsyncLoop.Run(this.decimationIterations, function (loop) {
  80862. if (triangleCount - deletedTriangles <= targetCount)
  80863. loop.breakLoop();
  80864. else {
  80865. iterationFunction(loop.index, function () {
  80866. loop.executeNext();
  80867. });
  80868. }
  80869. }, function () {
  80870. setTimeout(function () {
  80871. //reconstruct this part of the mesh
  80872. _this.reconstructMesh(submeshIndex);
  80873. successCallback();
  80874. }, 0);
  80875. });
  80876. };
  80877. QuadraticErrorSimplification.prototype.initWithMesh = function (submeshIndex, callback, optimizeMesh) {
  80878. var _this = this;
  80879. this.vertices = [];
  80880. this.triangles = [];
  80881. var positionData = this._mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  80882. var indices = this._mesh.getIndices();
  80883. var submesh = this._mesh.subMeshes[submeshIndex];
  80884. var findInVertices = function (positionToSearch) {
  80885. if (optimizeMesh) {
  80886. for (var ii = 0; ii < _this.vertices.length; ++ii) {
  80887. if (_this.vertices[ii].position.equals(positionToSearch)) {
  80888. return _this.vertices[ii];
  80889. }
  80890. }
  80891. }
  80892. return null;
  80893. };
  80894. var vertexReferences = [];
  80895. var vertexInit = function (i) {
  80896. if (!positionData) {
  80897. return;
  80898. }
  80899. var offset = i + submesh.verticesStart;
  80900. var position = BABYLON.Vector3.FromArray(positionData, offset * 3);
  80901. var vertex = findInVertices(position) || new DecimationVertex(position, _this.vertices.length);
  80902. vertex.originalOffsets.push(offset);
  80903. if (vertex.id === _this.vertices.length) {
  80904. _this.vertices.push(vertex);
  80905. }
  80906. vertexReferences.push(vertex.id);
  80907. };
  80908. //var totalVertices = mesh.getTotalVertices();
  80909. var totalVertices = submesh.verticesCount;
  80910. BABYLON.AsyncLoop.SyncAsyncForLoop(totalVertices, (this.syncIterations / 4) >> 0, vertexInit, function () {
  80911. var indicesInit = function (i) {
  80912. if (!indices) {
  80913. return;
  80914. }
  80915. var offset = (submesh.indexStart / 3) + i;
  80916. var pos = (offset * 3);
  80917. var i0 = indices[pos + 0];
  80918. var i1 = indices[pos + 1];
  80919. var i2 = indices[pos + 2];
  80920. var v0 = _this.vertices[vertexReferences[i0 - submesh.verticesStart]];
  80921. var v1 = _this.vertices[vertexReferences[i1 - submesh.verticesStart]];
  80922. var v2 = _this.vertices[vertexReferences[i2 - submesh.verticesStart]];
  80923. var triangle = new DecimationTriangle([v0, v1, v2]);
  80924. triangle.originalOffset = pos;
  80925. _this.triangles.push(triangle);
  80926. };
  80927. BABYLON.AsyncLoop.SyncAsyncForLoop(submesh.indexCount / 3, _this.syncIterations, indicesInit, function () {
  80928. _this.init(callback);
  80929. });
  80930. });
  80931. };
  80932. QuadraticErrorSimplification.prototype.init = function (callback) {
  80933. var _this = this;
  80934. var triangleInit1 = function (i) {
  80935. var t = _this.triangles[i];
  80936. t.normal = BABYLON.Vector3.Cross(t.vertices[1].position.subtract(t.vertices[0].position), t.vertices[2].position.subtract(t.vertices[0].position)).normalize();
  80937. for (var j = 0; j < 3; j++) {
  80938. 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))));
  80939. }
  80940. };
  80941. BABYLON.AsyncLoop.SyncAsyncForLoop(this.triangles.length, this.syncIterations, triangleInit1, function () {
  80942. var triangleInit2 = function (i) {
  80943. var t = _this.triangles[i];
  80944. for (var j = 0; j < 3; ++j) {
  80945. t.error[j] = _this.calculateError(t.vertices[j], t.vertices[(j + 1) % 3]);
  80946. }
  80947. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  80948. };
  80949. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, triangleInit2, function () {
  80950. callback();
  80951. });
  80952. });
  80953. };
  80954. QuadraticErrorSimplification.prototype.reconstructMesh = function (submeshIndex) {
  80955. var newTriangles = [];
  80956. var i;
  80957. for (i = 0; i < this.vertices.length; ++i) {
  80958. this.vertices[i].triangleCount = 0;
  80959. }
  80960. var t;
  80961. var j;
  80962. for (i = 0; i < this.triangles.length; ++i) {
  80963. if (!this.triangles[i].deleted) {
  80964. t = this.triangles[i];
  80965. for (j = 0; j < 3; ++j) {
  80966. t.vertices[j].triangleCount = 1;
  80967. }
  80968. newTriangles.push(t);
  80969. }
  80970. }
  80971. var newPositionData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []);
  80972. var newNormalData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []);
  80973. var newUVsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind) || []);
  80974. var newColorsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.ColorKind) || []);
  80975. var normalData = this._mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  80976. var uvs = this._mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  80977. var colorsData = this._mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  80978. var vertexCount = 0;
  80979. for (i = 0; i < this.vertices.length; ++i) {
  80980. var vertex = this.vertices[i];
  80981. vertex.id = vertexCount;
  80982. if (vertex.triangleCount) {
  80983. vertex.originalOffsets.forEach(function (originalOffset) {
  80984. if (!normalData) {
  80985. return;
  80986. }
  80987. newPositionData.push(vertex.position.x);
  80988. newPositionData.push(vertex.position.y);
  80989. newPositionData.push(vertex.position.z);
  80990. newNormalData.push(normalData[originalOffset * 3]);
  80991. newNormalData.push(normalData[(originalOffset * 3) + 1]);
  80992. newNormalData.push(normalData[(originalOffset * 3) + 2]);
  80993. if (uvs && uvs.length) {
  80994. newUVsData.push(uvs[(originalOffset * 2)]);
  80995. newUVsData.push(uvs[(originalOffset * 2) + 1]);
  80996. }
  80997. else if (colorsData && colorsData.length) {
  80998. newColorsData.push(colorsData[(originalOffset * 4)]);
  80999. newColorsData.push(colorsData[(originalOffset * 4) + 1]);
  81000. newColorsData.push(colorsData[(originalOffset * 4) + 2]);
  81001. newColorsData.push(colorsData[(originalOffset * 4) + 3]);
  81002. }
  81003. ++vertexCount;
  81004. });
  81005. }
  81006. }
  81007. var startingIndex = this._reconstructedMesh.getTotalIndices();
  81008. var startingVertex = this._reconstructedMesh.getTotalVertices();
  81009. var submeshesArray = this._reconstructedMesh.subMeshes;
  81010. this._reconstructedMesh.subMeshes = [];
  81011. var newIndicesArray = this._reconstructedMesh.getIndices(); //[];
  81012. var originalIndices = this._mesh.getIndices();
  81013. for (i = 0; i < newTriangles.length; ++i) {
  81014. t = newTriangles[i]; //now get the new referencing point for each vertex
  81015. [0, 1, 2].forEach(function (idx) {
  81016. var id = originalIndices[t.originalOffset + idx];
  81017. var offset = t.vertices[idx].originalOffsets.indexOf(id);
  81018. if (offset < 0)
  81019. offset = 0;
  81020. newIndicesArray.push(t.vertices[idx].id + offset + startingVertex);
  81021. });
  81022. }
  81023. //overwriting the old vertex buffers and indices.
  81024. this._reconstructedMesh.setIndices(newIndicesArray);
  81025. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, newPositionData);
  81026. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, newNormalData);
  81027. if (newUVsData.length > 0)
  81028. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.UVKind, newUVsData);
  81029. if (newColorsData.length > 0)
  81030. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, newColorsData);
  81031. //create submesh
  81032. var originalSubmesh = this._mesh.subMeshes[submeshIndex];
  81033. if (submeshIndex > 0) {
  81034. this._reconstructedMesh.subMeshes = [];
  81035. submeshesArray.forEach(function (submesh) {
  81036. BABYLON.SubMesh.AddToMesh(submesh.materialIndex, submesh.verticesStart, submesh.verticesCount, /* 0, newPositionData.length/3, */ submesh.indexStart, submesh.indexCount, submesh.getMesh());
  81037. });
  81038. BABYLON.SubMesh.AddToMesh(originalSubmesh.materialIndex, startingVertex, vertexCount, /* 0, newPositionData.length / 3, */ startingIndex, newTriangles.length * 3, this._reconstructedMesh);
  81039. }
  81040. };
  81041. QuadraticErrorSimplification.prototype.initDecimatedMesh = function () {
  81042. this._reconstructedMesh = new BABYLON.Mesh(this._mesh.name + "Decimated", this._mesh.getScene());
  81043. this._reconstructedMesh.material = this._mesh.material;
  81044. this._reconstructedMesh.parent = this._mesh.parent;
  81045. this._reconstructedMesh.isVisible = false;
  81046. this._reconstructedMesh.renderingGroupId = this._mesh.renderingGroupId;
  81047. };
  81048. QuadraticErrorSimplification.prototype.isFlipped = function (vertex1, vertex2, point, deletedArray, borderFactor, delTr) {
  81049. for (var i = 0; i < vertex1.triangleCount; ++i) {
  81050. var t = this.triangles[this.references[vertex1.triangleStart + i].triangleId];
  81051. if (t.deleted)
  81052. continue;
  81053. var s = this.references[vertex1.triangleStart + i].vertexId;
  81054. var v1 = t.vertices[(s + 1) % 3];
  81055. var v2 = t.vertices[(s + 2) % 3];
  81056. if ((v1 === vertex2 || v2 === vertex2)) {
  81057. deletedArray[i] = true;
  81058. delTr.push(t);
  81059. continue;
  81060. }
  81061. var d1 = v1.position.subtract(point);
  81062. d1 = d1.normalize();
  81063. var d2 = v2.position.subtract(point);
  81064. d2 = d2.normalize();
  81065. if (Math.abs(BABYLON.Vector3.Dot(d1, d2)) > 0.999)
  81066. return true;
  81067. var normal = BABYLON.Vector3.Cross(d1, d2).normalize();
  81068. deletedArray[i] = false;
  81069. if (BABYLON.Vector3.Dot(normal, t.normal) < 0.2)
  81070. return true;
  81071. }
  81072. return false;
  81073. };
  81074. QuadraticErrorSimplification.prototype.updateTriangles = function (origVertex, vertex, deletedArray, deletedTriangles) {
  81075. var newDeleted = deletedTriangles;
  81076. for (var i = 0; i < vertex.triangleCount; ++i) {
  81077. var ref = this.references[vertex.triangleStart + i];
  81078. var t = this.triangles[ref.triangleId];
  81079. if (t.deleted)
  81080. continue;
  81081. if (deletedArray[i] && t.deletePending) {
  81082. t.deleted = true;
  81083. newDeleted++;
  81084. continue;
  81085. }
  81086. t.vertices[ref.vertexId] = origVertex;
  81087. t.isDirty = true;
  81088. t.error[0] = this.calculateError(t.vertices[0], t.vertices[1]) + (t.borderFactor / 2);
  81089. t.error[1] = this.calculateError(t.vertices[1], t.vertices[2]) + (t.borderFactor / 2);
  81090. t.error[2] = this.calculateError(t.vertices[2], t.vertices[0]) + (t.borderFactor / 2);
  81091. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  81092. this.references.push(ref);
  81093. }
  81094. return newDeleted;
  81095. };
  81096. QuadraticErrorSimplification.prototype.identifyBorder = function () {
  81097. for (var i = 0; i < this.vertices.length; ++i) {
  81098. var vCount = [];
  81099. var vId = [];
  81100. var v = this.vertices[i];
  81101. var j;
  81102. for (j = 0; j < v.triangleCount; ++j) {
  81103. var triangle = this.triangles[this.references[v.triangleStart + j].triangleId];
  81104. for (var ii = 0; ii < 3; ii++) {
  81105. var ofs = 0;
  81106. var vv = triangle.vertices[ii];
  81107. while (ofs < vCount.length) {
  81108. if (vId[ofs] === vv.id)
  81109. break;
  81110. ++ofs;
  81111. }
  81112. if (ofs === vCount.length) {
  81113. vCount.push(1);
  81114. vId.push(vv.id);
  81115. }
  81116. else {
  81117. vCount[ofs]++;
  81118. }
  81119. }
  81120. }
  81121. for (j = 0; j < vCount.length; ++j) {
  81122. if (vCount[j] === 1) {
  81123. this.vertices[vId[j]].isBorder = true;
  81124. }
  81125. else {
  81126. this.vertices[vId[j]].isBorder = false;
  81127. }
  81128. }
  81129. }
  81130. };
  81131. QuadraticErrorSimplification.prototype.updateMesh = function (identifyBorders) {
  81132. if (identifyBorders === void 0) { identifyBorders = false; }
  81133. var i;
  81134. if (!identifyBorders) {
  81135. var newTrianglesVector = [];
  81136. for (i = 0; i < this.triangles.length; ++i) {
  81137. if (!this.triangles[i].deleted) {
  81138. newTrianglesVector.push(this.triangles[i]);
  81139. }
  81140. }
  81141. this.triangles = newTrianglesVector;
  81142. }
  81143. for (i = 0; i < this.vertices.length; ++i) {
  81144. this.vertices[i].triangleCount = 0;
  81145. this.vertices[i].triangleStart = 0;
  81146. }
  81147. var t;
  81148. var j;
  81149. var v;
  81150. for (i = 0; i < this.triangles.length; ++i) {
  81151. t = this.triangles[i];
  81152. for (j = 0; j < 3; ++j) {
  81153. v = t.vertices[j];
  81154. v.triangleCount++;
  81155. }
  81156. }
  81157. var tStart = 0;
  81158. for (i = 0; i < this.vertices.length; ++i) {
  81159. this.vertices[i].triangleStart = tStart;
  81160. tStart += this.vertices[i].triangleCount;
  81161. this.vertices[i].triangleCount = 0;
  81162. }
  81163. var newReferences = new Array(this.triangles.length * 3);
  81164. for (i = 0; i < this.triangles.length; ++i) {
  81165. t = this.triangles[i];
  81166. for (j = 0; j < 3; ++j) {
  81167. v = t.vertices[j];
  81168. newReferences[v.triangleStart + v.triangleCount] = new Reference(j, i);
  81169. v.triangleCount++;
  81170. }
  81171. }
  81172. this.references = newReferences;
  81173. if (identifyBorders) {
  81174. this.identifyBorder();
  81175. }
  81176. };
  81177. QuadraticErrorSimplification.prototype.vertexError = function (q, point) {
  81178. var x = point.x;
  81179. var y = point.y;
  81180. var z = point.z;
  81181. 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
  81182. + 2 * q.data[5] * y * z + 2 * q.data[6] * y + q.data[7] * z * z + 2 * q.data[8] * z + q.data[9];
  81183. };
  81184. QuadraticErrorSimplification.prototype.calculateError = function (vertex1, vertex2, pointResult, normalResult, uvResult, colorResult) {
  81185. var q = vertex1.q.add(vertex2.q);
  81186. var border = vertex1.isBorder && vertex2.isBorder;
  81187. var error = 0;
  81188. var qDet = q.det(0, 1, 2, 1, 4, 5, 2, 5, 7);
  81189. if (qDet !== 0 && !border) {
  81190. if (!pointResult) {
  81191. pointResult = BABYLON.Vector3.Zero();
  81192. }
  81193. pointResult.x = -1 / qDet * (q.det(1, 2, 3, 4, 5, 6, 5, 7, 8));
  81194. pointResult.y = 1 / qDet * (q.det(0, 2, 3, 1, 5, 6, 2, 7, 8));
  81195. pointResult.z = -1 / qDet * (q.det(0, 1, 3, 1, 4, 6, 2, 5, 8));
  81196. error = this.vertexError(q, pointResult);
  81197. }
  81198. else {
  81199. var p3 = (vertex1.position.add(vertex2.position)).divide(new BABYLON.Vector3(2, 2, 2));
  81200. //var norm3 = (vertex1.normal.add(vertex2.normal)).divide(new Vector3(2, 2, 2)).normalize();
  81201. var error1 = this.vertexError(q, vertex1.position);
  81202. var error2 = this.vertexError(q, vertex2.position);
  81203. var error3 = this.vertexError(q, p3);
  81204. error = Math.min(error1, error2, error3);
  81205. if (error === error1) {
  81206. if (pointResult) {
  81207. pointResult.copyFrom(vertex1.position);
  81208. }
  81209. }
  81210. else if (error === error2) {
  81211. if (pointResult) {
  81212. pointResult.copyFrom(vertex2.position);
  81213. }
  81214. }
  81215. else {
  81216. if (pointResult) {
  81217. pointResult.copyFrom(p3);
  81218. }
  81219. }
  81220. }
  81221. return error;
  81222. };
  81223. return QuadraticErrorSimplification;
  81224. }());
  81225. BABYLON.QuadraticErrorSimplification = QuadraticErrorSimplification;
  81226. })(BABYLON || (BABYLON = {}));
  81227. //# sourceMappingURL=babylon.meshSimplification.js.map
  81228. var BABYLON;
  81229. (function (BABYLON) {
  81230. var MeshLODLevel = /** @class */ (function () {
  81231. function MeshLODLevel(distance, mesh) {
  81232. this.distance = distance;
  81233. this.mesh = mesh;
  81234. }
  81235. return MeshLODLevel;
  81236. }());
  81237. BABYLON.MeshLODLevel = MeshLODLevel;
  81238. })(BABYLON || (BABYLON = {}));
  81239. //# sourceMappingURL=babylon.meshLODLevel.js.map
  81240. var BABYLON;
  81241. (function (BABYLON) {
  81242. /**
  81243. * Defines the root class used to create scene optimization to use with SceneOptimizer
  81244. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  81245. */
  81246. var SceneOptimization = /** @class */ (function () {
  81247. /**
  81248. * Creates the SceneOptimization object
  81249. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  81250. * @param desc defines the description associated with the optimization
  81251. */
  81252. function SceneOptimization(
  81253. /**
  81254. * Defines the priority of this optimization (0 by default which means first in the list)
  81255. */
  81256. priority) {
  81257. if (priority === void 0) { priority = 0; }
  81258. this.priority = priority;
  81259. }
  81260. /**
  81261. * Gets a string describing the action executed by the current optimization
  81262. * @returns description string
  81263. */
  81264. SceneOptimization.prototype.getDescription = function () {
  81265. return "";
  81266. };
  81267. /**
  81268. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  81269. * @param scene defines the current scene where to apply this optimization
  81270. * @param optimizer defines the current optimizer
  81271. * @returns true if everything that can be done was applied
  81272. */
  81273. SceneOptimization.prototype.apply = function (scene, optimizer) {
  81274. return true;
  81275. };
  81276. ;
  81277. return SceneOptimization;
  81278. }());
  81279. BABYLON.SceneOptimization = SceneOptimization;
  81280. /**
  81281. * Defines an optimization used to reduce the size of render target textures
  81282. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  81283. */
  81284. var TextureOptimization = /** @class */ (function (_super) {
  81285. __extends(TextureOptimization, _super);
  81286. /**
  81287. * Creates the TextureOptimization object
  81288. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  81289. * @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
  81290. * @param step defines the factor (0.5 by default) used to scale down textures bigger than maximum sized allowed.
  81291. */
  81292. function TextureOptimization(
  81293. /**
  81294. * Defines the priority of this optimization (0 by default which means first in the list)
  81295. */
  81296. priority,
  81297. /**
  81298. * 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
  81299. */
  81300. maximumSize,
  81301. /**
  81302. * Defines the factor (0.5 by default) used to scale down textures bigger than maximum sized allowed.
  81303. */
  81304. step) {
  81305. if (priority === void 0) { priority = 0; }
  81306. if (maximumSize === void 0) { maximumSize = 1024; }
  81307. if (step === void 0) { step = 0.5; }
  81308. var _this = _super.call(this, priority) || this;
  81309. _this.priority = priority;
  81310. _this.maximumSize = maximumSize;
  81311. _this.step = step;
  81312. return _this;
  81313. }
  81314. /**
  81315. * Gets a string describing the action executed by the current optimization
  81316. * @returns description string
  81317. */
  81318. TextureOptimization.prototype.getDescription = function () {
  81319. return "Reducing render target texture size to " + this.maximumSize;
  81320. };
  81321. /**
  81322. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  81323. * @param scene defines the current scene where to apply this optimization
  81324. * @param optimizer defines the current optimizer
  81325. * @returns true if everything that can be done was applied
  81326. */
  81327. TextureOptimization.prototype.apply = function (scene, optimizer) {
  81328. var allDone = true;
  81329. for (var index = 0; index < scene.textures.length; index++) {
  81330. var texture = scene.textures[index];
  81331. if (!texture.canRescale || texture.getContext) {
  81332. continue;
  81333. }
  81334. var currentSize = texture.getSize();
  81335. var maxDimension = Math.max(currentSize.width, currentSize.height);
  81336. if (maxDimension > this.maximumSize) {
  81337. texture.scale(this.step);
  81338. allDone = false;
  81339. }
  81340. }
  81341. return allDone;
  81342. };
  81343. return TextureOptimization;
  81344. }(SceneOptimization));
  81345. BABYLON.TextureOptimization = TextureOptimization;
  81346. /**
  81347. * Defines an optimization used to increase or decrease the rendering resolution
  81348. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  81349. */
  81350. var HardwareScalingOptimization = /** @class */ (function (_super) {
  81351. __extends(HardwareScalingOptimization, _super);
  81352. /**
  81353. * Creates the HardwareScalingOptimization object
  81354. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  81355. * @param maximumScale defines the maximum scale to use (2 by default)
  81356. * @param step defines the step to use between two passes (0.5 by default)
  81357. */
  81358. function HardwareScalingOptimization(
  81359. /**
  81360. * Defines the priority of this optimization (0 by default which means first in the list)
  81361. */
  81362. priority,
  81363. /**
  81364. * Defines the maximum scale to use (2 by default)
  81365. */
  81366. maximumScale,
  81367. /**
  81368. * Defines the step to use between two passes (0.5 by default)
  81369. */
  81370. step) {
  81371. if (priority === void 0) { priority = 0; }
  81372. if (maximumScale === void 0) { maximumScale = 2; }
  81373. if (step === void 0) { step = 0.25; }
  81374. var _this = _super.call(this, priority) || this;
  81375. _this.priority = priority;
  81376. _this.maximumScale = maximumScale;
  81377. _this.step = step;
  81378. _this._currentScale = -1;
  81379. _this._directionOffset = 1;
  81380. return _this;
  81381. }
  81382. /**
  81383. * Gets a string describing the action executed by the current optimization
  81384. * @return description string
  81385. */
  81386. HardwareScalingOptimization.prototype.getDescription = function () {
  81387. return "Setting hardware scaling level to " + this._currentScale;
  81388. };
  81389. /**
  81390. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  81391. * @param scene defines the current scene where to apply this optimization
  81392. * @param optimizer defines the current optimizer
  81393. * @returns true if everything that can be done was applied
  81394. */
  81395. HardwareScalingOptimization.prototype.apply = function (scene, optimizer) {
  81396. if (this._currentScale === -1) {
  81397. this._currentScale = scene.getEngine().getHardwareScalingLevel();
  81398. if (this._currentScale > this.maximumScale) {
  81399. this._directionOffset = -1;
  81400. }
  81401. }
  81402. this._currentScale += this._directionOffset * this.step;
  81403. scene.getEngine().setHardwareScalingLevel(this._currentScale);
  81404. return this._directionOffset === 1 ? this._currentScale >= this.maximumScale : this._currentScale <= this.maximumScale;
  81405. };
  81406. ;
  81407. return HardwareScalingOptimization;
  81408. }(SceneOptimization));
  81409. BABYLON.HardwareScalingOptimization = HardwareScalingOptimization;
  81410. /**
  81411. * Defines an optimization used to remove shadows
  81412. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  81413. */
  81414. var ShadowsOptimization = /** @class */ (function (_super) {
  81415. __extends(ShadowsOptimization, _super);
  81416. function ShadowsOptimization() {
  81417. return _super !== null && _super.apply(this, arguments) || this;
  81418. }
  81419. /**
  81420. * Gets a string describing the action executed by the current optimization
  81421. * @return description string
  81422. */
  81423. ShadowsOptimization.prototype.getDescription = function () {
  81424. return "Turning shadows on/off";
  81425. };
  81426. /**
  81427. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  81428. * @param scene defines the current scene where to apply this optimization
  81429. * @param optimizer defines the current optimizer
  81430. * @returns true if everything that can be done was applied
  81431. */
  81432. ShadowsOptimization.prototype.apply = function (scene, optimizer) {
  81433. scene.shadowsEnabled = optimizer.isInImprovementMode;
  81434. return true;
  81435. };
  81436. ;
  81437. return ShadowsOptimization;
  81438. }(SceneOptimization));
  81439. BABYLON.ShadowsOptimization = ShadowsOptimization;
  81440. /**
  81441. * Defines an optimization used to turn post-processes off
  81442. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  81443. */
  81444. var PostProcessesOptimization = /** @class */ (function (_super) {
  81445. __extends(PostProcessesOptimization, _super);
  81446. function PostProcessesOptimization() {
  81447. return _super !== null && _super.apply(this, arguments) || this;
  81448. }
  81449. /**
  81450. * Gets a string describing the action executed by the current optimization
  81451. * @return description string
  81452. */
  81453. PostProcessesOptimization.prototype.getDescription = function () {
  81454. return "Turning post-processes on/off";
  81455. };
  81456. /**
  81457. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  81458. * @param scene defines the current scene where to apply this optimization
  81459. * @param optimizer defines the current optimizer
  81460. * @returns true if everything that can be done was applied
  81461. */
  81462. PostProcessesOptimization.prototype.apply = function (scene, optimizer) {
  81463. scene.postProcessesEnabled = optimizer.isInImprovementMode;
  81464. return true;
  81465. };
  81466. ;
  81467. return PostProcessesOptimization;
  81468. }(SceneOptimization));
  81469. BABYLON.PostProcessesOptimization = PostProcessesOptimization;
  81470. /**
  81471. * Defines an optimization used to turn lens flares off
  81472. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  81473. */
  81474. var LensFlaresOptimization = /** @class */ (function (_super) {
  81475. __extends(LensFlaresOptimization, _super);
  81476. function LensFlaresOptimization() {
  81477. return _super !== null && _super.apply(this, arguments) || this;
  81478. }
  81479. /**
  81480. * Gets a string describing the action executed by the current optimization
  81481. * @return description string
  81482. */
  81483. LensFlaresOptimization.prototype.getDescription = function () {
  81484. return "Turning lens flares on/off";
  81485. };
  81486. /**
  81487. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  81488. * @param scene defines the current scene where to apply this optimization
  81489. * @param optimizer defines the current optimizer
  81490. * @returns true if everything that can be done was applied
  81491. */
  81492. LensFlaresOptimization.prototype.apply = function (scene, optimizer) {
  81493. scene.lensFlaresEnabled = optimizer.isInImprovementMode;
  81494. return true;
  81495. };
  81496. ;
  81497. return LensFlaresOptimization;
  81498. }(SceneOptimization));
  81499. BABYLON.LensFlaresOptimization = LensFlaresOptimization;
  81500. /**
  81501. * Defines an optimization based on user defined callback.
  81502. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  81503. */
  81504. var CustomOptimization = /** @class */ (function (_super) {
  81505. __extends(CustomOptimization, _super);
  81506. function CustomOptimization() {
  81507. return _super !== null && _super.apply(this, arguments) || this;
  81508. }
  81509. /**
  81510. * Gets a string describing the action executed by the current optimization
  81511. * @returns description string
  81512. */
  81513. CustomOptimization.prototype.getDescription = function () {
  81514. if (this.onGetDescription) {
  81515. return this.onGetDescription();
  81516. }
  81517. return "Running user defined callback";
  81518. };
  81519. /**
  81520. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  81521. * @param scene defines the current scene where to apply this optimization
  81522. * @param optimizer defines the current optimizer
  81523. * @returns true if everything that can be done was applied
  81524. */
  81525. CustomOptimization.prototype.apply = function (scene, optimizer) {
  81526. if (this.onApply) {
  81527. return this.onApply(scene, optimizer);
  81528. }
  81529. return true;
  81530. };
  81531. ;
  81532. return CustomOptimization;
  81533. }(SceneOptimization));
  81534. BABYLON.CustomOptimization = CustomOptimization;
  81535. /**
  81536. * Defines an optimization used to turn particles off
  81537. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  81538. */
  81539. var ParticlesOptimization = /** @class */ (function (_super) {
  81540. __extends(ParticlesOptimization, _super);
  81541. function ParticlesOptimization() {
  81542. return _super !== null && _super.apply(this, arguments) || this;
  81543. }
  81544. /**
  81545. * Gets a string describing the action executed by the current optimization
  81546. * @return description string
  81547. */
  81548. ParticlesOptimization.prototype.getDescription = function () {
  81549. return "Turning particles on/off";
  81550. };
  81551. /**
  81552. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  81553. * @param scene defines the current scene where to apply this optimization
  81554. * @param optimizer defines the current optimizer
  81555. * @returns true if everything that can be done was applied
  81556. */
  81557. ParticlesOptimization.prototype.apply = function (scene, optimizer) {
  81558. scene.particlesEnabled = optimizer.isInImprovementMode;
  81559. return true;
  81560. };
  81561. ;
  81562. return ParticlesOptimization;
  81563. }(SceneOptimization));
  81564. BABYLON.ParticlesOptimization = ParticlesOptimization;
  81565. /**
  81566. * Defines an optimization used to turn render targets off
  81567. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  81568. */
  81569. var RenderTargetsOptimization = /** @class */ (function (_super) {
  81570. __extends(RenderTargetsOptimization, _super);
  81571. function RenderTargetsOptimization() {
  81572. return _super !== null && _super.apply(this, arguments) || this;
  81573. }
  81574. /**
  81575. * Gets a string describing the action executed by the current optimization
  81576. * @return description string
  81577. */
  81578. RenderTargetsOptimization.prototype.getDescription = function () {
  81579. return "Turning render targets off";
  81580. };
  81581. /**
  81582. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  81583. * @param scene defines the current scene where to apply this optimization
  81584. * @param optimizer defines the current optimizer
  81585. * @returns true if everything that can be done was applied
  81586. */
  81587. RenderTargetsOptimization.prototype.apply = function (scene, optimizer) {
  81588. scene.renderTargetsEnabled = optimizer.isInImprovementMode;
  81589. return true;
  81590. };
  81591. ;
  81592. return RenderTargetsOptimization;
  81593. }(SceneOptimization));
  81594. BABYLON.RenderTargetsOptimization = RenderTargetsOptimization;
  81595. /**
  81596. * Defines an optimization used to merge meshes with compatible materials
  81597. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  81598. */
  81599. var MergeMeshesOptimization = /** @class */ (function (_super) {
  81600. __extends(MergeMeshesOptimization, _super);
  81601. function MergeMeshesOptimization() {
  81602. var _this = _super !== null && _super.apply(this, arguments) || this;
  81603. _this._canBeMerged = function (abstractMesh) {
  81604. if (!(abstractMesh instanceof BABYLON.Mesh)) {
  81605. return false;
  81606. }
  81607. var mesh = abstractMesh;
  81608. if (!mesh.isVisible || !mesh.isEnabled()) {
  81609. return false;
  81610. }
  81611. if (mesh.instances.length > 0) {
  81612. return false;
  81613. }
  81614. if (mesh.skeleton || mesh.hasLODLevels) {
  81615. return false;
  81616. }
  81617. if (mesh.parent) {
  81618. return false;
  81619. }
  81620. return true;
  81621. };
  81622. return _this;
  81623. }
  81624. Object.defineProperty(MergeMeshesOptimization, "UpdateSelectionTree", {
  81625. /**
  81626. * Gets or sets a boolean which defines if optimization octree has to be updated
  81627. */
  81628. get: function () {
  81629. return MergeMeshesOptimization._UpdateSelectionTree;
  81630. },
  81631. /**
  81632. * Gets or sets a boolean which defines if optimization octree has to be updated
  81633. */
  81634. set: function (value) {
  81635. MergeMeshesOptimization._UpdateSelectionTree = value;
  81636. },
  81637. enumerable: true,
  81638. configurable: true
  81639. });
  81640. /**
  81641. * Gets a string describing the action executed by the current optimization
  81642. * @return description string
  81643. */
  81644. MergeMeshesOptimization.prototype.getDescription = function () {
  81645. return "Merging similar meshes together";
  81646. };
  81647. /**
  81648. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  81649. * @param scene defines the current scene where to apply this optimization
  81650. * @param optimizer defines the current optimizer
  81651. * @param updateSelectionTree defines that the selection octree has to be updated (false by default)
  81652. * @returns true if everything that can be done was applied
  81653. */
  81654. MergeMeshesOptimization.prototype.apply = function (scene, optimizer, updateSelectionTree) {
  81655. var globalPool = scene.meshes.slice(0);
  81656. var globalLength = globalPool.length;
  81657. for (var index = 0; index < globalLength; index++) {
  81658. var currentPool = new Array();
  81659. var current = globalPool[index];
  81660. // Checks
  81661. if (!this._canBeMerged(current)) {
  81662. continue;
  81663. }
  81664. currentPool.push(current);
  81665. // Find compatible meshes
  81666. for (var subIndex = index + 1; subIndex < globalLength; subIndex++) {
  81667. var otherMesh = globalPool[subIndex];
  81668. if (!this._canBeMerged(otherMesh)) {
  81669. continue;
  81670. }
  81671. if (otherMesh.material !== current.material) {
  81672. continue;
  81673. }
  81674. if (otherMesh.checkCollisions !== current.checkCollisions) {
  81675. continue;
  81676. }
  81677. currentPool.push(otherMesh);
  81678. globalLength--;
  81679. globalPool.splice(subIndex, 1);
  81680. subIndex--;
  81681. }
  81682. if (currentPool.length < 2) {
  81683. continue;
  81684. }
  81685. // Merge meshes
  81686. BABYLON.Mesh.MergeMeshes(currentPool);
  81687. }
  81688. if (updateSelectionTree != undefined) {
  81689. if (updateSelectionTree) {
  81690. scene.createOrUpdateSelectionOctree();
  81691. }
  81692. }
  81693. else if (MergeMeshesOptimization.UpdateSelectionTree) {
  81694. scene.createOrUpdateSelectionOctree();
  81695. }
  81696. return true;
  81697. };
  81698. ;
  81699. MergeMeshesOptimization._UpdateSelectionTree = false;
  81700. return MergeMeshesOptimization;
  81701. }(SceneOptimization));
  81702. BABYLON.MergeMeshesOptimization = MergeMeshesOptimization;
  81703. /**
  81704. * Defines a list of options used by SceneOptimizer
  81705. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  81706. */
  81707. var SceneOptimizerOptions = /** @class */ (function () {
  81708. /**
  81709. * Creates a new list of options used by SceneOptimizer
  81710. * @param targetFrameRate defines the target frame rate to reach (60 by default)
  81711. * @param trackerDuration defines the interval between two checkes (2000ms by default)
  81712. */
  81713. function SceneOptimizerOptions(
  81714. /**
  81715. * Defines the target frame rate to reach (60 by default)
  81716. */
  81717. targetFrameRate,
  81718. /**
  81719. * Defines the interval between two checkes (2000ms by default)
  81720. */
  81721. trackerDuration) {
  81722. if (targetFrameRate === void 0) { targetFrameRate = 60; }
  81723. if (trackerDuration === void 0) { trackerDuration = 2000; }
  81724. this.targetFrameRate = targetFrameRate;
  81725. this.trackerDuration = trackerDuration;
  81726. /**
  81727. * Gets the list of optimizations to apply
  81728. */
  81729. this.optimizations = new Array();
  81730. }
  81731. /**
  81732. * Add a new optimization
  81733. * @param optimization defines the SceneOptimization to add to the list of active optimizations
  81734. * @returns the current SceneOptimizerOptions
  81735. */
  81736. SceneOptimizerOptions.prototype.addOptimization = function (optimization) {
  81737. this.optimizations.push(optimization);
  81738. return this;
  81739. };
  81740. /**
  81741. * Add a new custom optimization
  81742. * @param onApply defines the callback called to apply the custom optimization (true if everything that can be done was applied)
  81743. * @param onGetDescription defines the callback called to get the description attached with the optimization.
  81744. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  81745. * @returns the current SceneOptimizerOptions
  81746. */
  81747. SceneOptimizerOptions.prototype.addCustomOptimization = function (onApply, onGetDescription, priority) {
  81748. if (priority === void 0) { priority = 0; }
  81749. var optimization = new CustomOptimization(priority);
  81750. optimization.onApply = onApply;
  81751. optimization.onGetDescription = onGetDescription;
  81752. this.optimizations.push(optimization);
  81753. return this;
  81754. };
  81755. /**
  81756. * Creates a list of pre-defined optimizations aimed to reduce the visual impact on the scene
  81757. * @param targetFrameRate defines the target frame rate (60 by default)
  81758. * @returns a SceneOptimizerOptions object
  81759. */
  81760. SceneOptimizerOptions.LowDegradationAllowed = function (targetFrameRate) {
  81761. var result = new SceneOptimizerOptions(targetFrameRate);
  81762. var priority = 0;
  81763. result.addOptimization(new MergeMeshesOptimization(priority));
  81764. result.addOptimization(new ShadowsOptimization(priority));
  81765. result.addOptimization(new LensFlaresOptimization(priority));
  81766. // Next priority
  81767. priority++;
  81768. result.addOptimization(new PostProcessesOptimization(priority));
  81769. result.addOptimization(new ParticlesOptimization(priority));
  81770. // Next priority
  81771. priority++;
  81772. result.addOptimization(new TextureOptimization(priority, 1024));
  81773. return result;
  81774. };
  81775. /**
  81776. * Creates a list of pre-defined optimizations aimed to have a moderate impact on the scene visual
  81777. * @param targetFrameRate defines the target frame rate (60 by default)
  81778. * @returns a SceneOptimizerOptions object
  81779. */
  81780. SceneOptimizerOptions.ModerateDegradationAllowed = function (targetFrameRate) {
  81781. var result = new SceneOptimizerOptions(targetFrameRate);
  81782. var priority = 0;
  81783. result.addOptimization(new MergeMeshesOptimization(priority));
  81784. result.addOptimization(new ShadowsOptimization(priority));
  81785. result.addOptimization(new LensFlaresOptimization(priority));
  81786. // Next priority
  81787. priority++;
  81788. result.addOptimization(new PostProcessesOptimization(priority));
  81789. result.addOptimization(new ParticlesOptimization(priority));
  81790. // Next priority
  81791. priority++;
  81792. result.addOptimization(new TextureOptimization(priority, 512));
  81793. // Next priority
  81794. priority++;
  81795. result.addOptimization(new RenderTargetsOptimization(priority));
  81796. // Next priority
  81797. priority++;
  81798. result.addOptimization(new HardwareScalingOptimization(priority, 2));
  81799. return result;
  81800. };
  81801. /**
  81802. * Creates a list of pre-defined optimizations aimed to have a big impact on the scene visual
  81803. * @param targetFrameRate defines the target frame rate (60 by default)
  81804. * @returns a SceneOptimizerOptions object
  81805. */
  81806. SceneOptimizerOptions.HighDegradationAllowed = function (targetFrameRate) {
  81807. var result = new SceneOptimizerOptions(targetFrameRate);
  81808. var priority = 0;
  81809. result.addOptimization(new MergeMeshesOptimization(priority));
  81810. result.addOptimization(new ShadowsOptimization(priority));
  81811. result.addOptimization(new LensFlaresOptimization(priority));
  81812. // Next priority
  81813. priority++;
  81814. result.addOptimization(new PostProcessesOptimization(priority));
  81815. result.addOptimization(new ParticlesOptimization(priority));
  81816. // Next priority
  81817. priority++;
  81818. result.addOptimization(new TextureOptimization(priority, 256));
  81819. // Next priority
  81820. priority++;
  81821. result.addOptimization(new RenderTargetsOptimization(priority));
  81822. // Next priority
  81823. priority++;
  81824. result.addOptimization(new HardwareScalingOptimization(priority, 4));
  81825. return result;
  81826. };
  81827. return SceneOptimizerOptions;
  81828. }());
  81829. BABYLON.SceneOptimizerOptions = SceneOptimizerOptions;
  81830. /**
  81831. * Class used to run optimizations in order to reach a target frame rate
  81832. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  81833. */
  81834. var SceneOptimizer = /** @class */ (function () {
  81835. /**
  81836. * Creates a new SceneOptimizer
  81837. * @param scene defines the scene to work on
  81838. * @param options defines the options to use with the SceneOptimizer
  81839. * @param autoGeneratePriorities defines if priorities must be generated and not read from SceneOptimization property (true by default)
  81840. * @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)
  81841. */
  81842. function SceneOptimizer(scene, options, autoGeneratePriorities, improvementMode) {
  81843. if (autoGeneratePriorities === void 0) { autoGeneratePriorities = true; }
  81844. if (improvementMode === void 0) { improvementMode = false; }
  81845. var _this = this;
  81846. this._isRunning = false;
  81847. this._currentPriorityLevel = 0;
  81848. this._targetFrameRate = 60;
  81849. this._trackerDuration = 2000;
  81850. this._currentFrameRate = 0;
  81851. this._improvementMode = false;
  81852. /**
  81853. * Defines an observable called when the optimizer reaches the target frame rate
  81854. */
  81855. this.onSuccessObservable = new BABYLON.Observable();
  81856. /**
  81857. * Defines an observable called when the optimizer enables an optimization
  81858. */
  81859. this.onNewOptimizationAppliedObservable = new BABYLON.Observable();
  81860. /**
  81861. * Defines an observable called when the optimizer is not able to reach the target frame rate
  81862. */
  81863. this.onFailureObservable = new BABYLON.Observable();
  81864. if (!options) {
  81865. this._options = new SceneOptimizerOptions();
  81866. }
  81867. else {
  81868. this._options = options;
  81869. }
  81870. if (this._options.targetFrameRate) {
  81871. this._targetFrameRate = this._options.targetFrameRate;
  81872. }
  81873. if (this._options.trackerDuration) {
  81874. this._trackerDuration = this._options.trackerDuration;
  81875. }
  81876. if (autoGeneratePriorities) {
  81877. var priority = 0;
  81878. for (var _i = 0, _a = this._options.optimizations; _i < _a.length; _i++) {
  81879. var optim = _a[_i];
  81880. optim.priority = priority++;
  81881. }
  81882. }
  81883. this._improvementMode = improvementMode;
  81884. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  81885. this._sceneDisposeObserver = this._scene.onDisposeObservable.add(function () {
  81886. _this._sceneDisposeObserver = null;
  81887. _this.dispose();
  81888. });
  81889. }
  81890. Object.defineProperty(SceneOptimizer.prototype, "isInImprovementMode", {
  81891. /**
  81892. * Gets a boolean indicating if the optimizer is in improvement mode
  81893. */
  81894. get: function () {
  81895. return this._improvementMode;
  81896. },
  81897. enumerable: true,
  81898. configurable: true
  81899. });
  81900. Object.defineProperty(SceneOptimizer.prototype, "currentPriorityLevel", {
  81901. /**
  81902. * Gets the current priority level (0 at start)
  81903. */
  81904. get: function () {
  81905. return this._currentPriorityLevel;
  81906. },
  81907. enumerable: true,
  81908. configurable: true
  81909. });
  81910. Object.defineProperty(SceneOptimizer.prototype, "currentFrameRate", {
  81911. /**
  81912. * Gets the current frame rate checked by the SceneOptimizer
  81913. */
  81914. get: function () {
  81915. return this._currentFrameRate;
  81916. },
  81917. enumerable: true,
  81918. configurable: true
  81919. });
  81920. Object.defineProperty(SceneOptimizer.prototype, "targetFrameRate", {
  81921. /**
  81922. * Gets or sets the current target frame rate (60 by default)
  81923. */
  81924. get: function () {
  81925. return this._targetFrameRate;
  81926. },
  81927. /**
  81928. * Gets or sets the current target frame rate (60 by default)
  81929. */
  81930. set: function (value) {
  81931. this._targetFrameRate = value;
  81932. },
  81933. enumerable: true,
  81934. configurable: true
  81935. });
  81936. Object.defineProperty(SceneOptimizer.prototype, "trackerDuration", {
  81937. /**
  81938. * Gets or sets the current interval between two checks (every 2000ms by default)
  81939. */
  81940. get: function () {
  81941. return this._trackerDuration;
  81942. },
  81943. /**
  81944. * Gets or sets the current interval between two checks (every 2000ms by default)
  81945. */
  81946. set: function (value) {
  81947. this._trackerDuration = value;
  81948. },
  81949. enumerable: true,
  81950. configurable: true
  81951. });
  81952. Object.defineProperty(SceneOptimizer.prototype, "optimizations", {
  81953. /**
  81954. * Gets the list of active optimizations
  81955. */
  81956. get: function () {
  81957. return this._options.optimizations;
  81958. },
  81959. enumerable: true,
  81960. configurable: true
  81961. });
  81962. /**
  81963. * Stops the current optimizer
  81964. */
  81965. SceneOptimizer.prototype.stop = function () {
  81966. this._isRunning = false;
  81967. };
  81968. /**
  81969. * Reset the optimizer to initial step (current priority level = 0)
  81970. */
  81971. SceneOptimizer.prototype.reset = function () {
  81972. this._currentPriorityLevel = 0;
  81973. };
  81974. /**
  81975. * Start the optimizer. By default it will try to reach a specific framerate
  81976. * but if the optimizer is set with improvementMode === true then it will run all optimiatiation while frame rate is above the target frame rate
  81977. */
  81978. SceneOptimizer.prototype.start = function () {
  81979. var _this = this;
  81980. if (this._isRunning) {
  81981. return;
  81982. }
  81983. this._isRunning = true;
  81984. // Let's wait for the scene to be ready before running our check
  81985. this._scene.executeWhenReady(function () {
  81986. setTimeout(function () {
  81987. _this._checkCurrentState();
  81988. }, _this._trackerDuration);
  81989. });
  81990. };
  81991. SceneOptimizer.prototype._checkCurrentState = function () {
  81992. var _this = this;
  81993. if (!this._isRunning) {
  81994. return;
  81995. }
  81996. var scene = this._scene;
  81997. var options = this._options;
  81998. this._currentFrameRate = Math.round(scene.getEngine().getFps());
  81999. if (this._improvementMode && this._currentFrameRate <= this._targetFrameRate ||
  82000. !this._improvementMode && this._currentFrameRate >= this._targetFrameRate) {
  82001. this._isRunning = false;
  82002. this.onSuccessObservable.notifyObservers(this);
  82003. return;
  82004. }
  82005. // Apply current level of optimizations
  82006. var allDone = true;
  82007. var noOptimizationApplied = true;
  82008. for (var index = 0; index < options.optimizations.length; index++) {
  82009. var optimization = options.optimizations[index];
  82010. if (optimization.priority === this._currentPriorityLevel) {
  82011. noOptimizationApplied = false;
  82012. allDone = allDone && optimization.apply(scene, this);
  82013. this.onNewOptimizationAppliedObservable.notifyObservers(optimization);
  82014. }
  82015. }
  82016. // If no optimization was applied, this is a failure :(
  82017. if (noOptimizationApplied) {
  82018. this._isRunning = false;
  82019. this.onFailureObservable.notifyObservers(this);
  82020. return;
  82021. }
  82022. // If all optimizations were done, move to next level
  82023. if (allDone) {
  82024. this._currentPriorityLevel++;
  82025. }
  82026. // Let's the system running for a specific amount of time before checking FPS
  82027. scene.executeWhenReady(function () {
  82028. setTimeout(function () {
  82029. _this._checkCurrentState();
  82030. }, _this._trackerDuration);
  82031. });
  82032. };
  82033. /**
  82034. * Release all resources
  82035. */
  82036. SceneOptimizer.prototype.dispose = function () {
  82037. this.stop();
  82038. this.onSuccessObservable.clear();
  82039. this.onFailureObservable.clear();
  82040. this.onNewOptimizationAppliedObservable.clear();
  82041. if (this._sceneDisposeObserver) {
  82042. this._scene.onDisposeObservable.remove(this._sceneDisposeObserver);
  82043. }
  82044. };
  82045. /**
  82046. * Helper function to create a SceneOptimizer with one single line of code
  82047. * @param scene defines the scene to work on
  82048. * @param options defines the options to use with the SceneOptimizer
  82049. * @param onSuccess defines a callback to call on success
  82050. * @param onFailure defines a callback to call on failure
  82051. * @returns the new SceneOptimizer object
  82052. */
  82053. SceneOptimizer.OptimizeAsync = function (scene, options, onSuccess, onFailure) {
  82054. var optimizer = new SceneOptimizer(scene, options || SceneOptimizerOptions.ModerateDegradationAllowed(), false);
  82055. if (onSuccess) {
  82056. optimizer.onSuccessObservable.add(function () {
  82057. onSuccess();
  82058. });
  82059. }
  82060. if (onFailure) {
  82061. optimizer.onFailureObservable.add(function () {
  82062. onFailure();
  82063. });
  82064. }
  82065. optimizer.start();
  82066. return optimizer;
  82067. };
  82068. return SceneOptimizer;
  82069. }());
  82070. BABYLON.SceneOptimizer = SceneOptimizer;
  82071. })(BABYLON || (BABYLON = {}));
  82072. //# sourceMappingURL=babylon.sceneOptimizer.js.map
  82073. var BABYLON;
  82074. (function (BABYLON) {
  82075. var OutlineRenderer = /** @class */ (function () {
  82076. function OutlineRenderer(scene) {
  82077. this.zOffset = 1;
  82078. this._scene = scene;
  82079. }
  82080. OutlineRenderer.prototype.render = function (subMesh, batch, useOverlay) {
  82081. var _this = this;
  82082. if (useOverlay === void 0) { useOverlay = false; }
  82083. var scene = this._scene;
  82084. var engine = this._scene.getEngine();
  82085. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  82086. if (!this.isReady(subMesh, hardwareInstancedRendering)) {
  82087. return;
  82088. }
  82089. var mesh = subMesh.getRenderingMesh();
  82090. var material = subMesh.getMaterial();
  82091. if (!material || !scene.activeCamera) {
  82092. return;
  82093. }
  82094. engine.enableEffect(this._effect);
  82095. // Logarithmic depth
  82096. if (material.useLogarithmicDepth) {
  82097. this._effect.setFloat("logarithmicDepthConstant", 2.0 / (Math.log(scene.activeCamera.maxZ + 1.0) / Math.LN2));
  82098. }
  82099. this._effect.setFloat("offset", useOverlay ? 0 : mesh.outlineWidth);
  82100. this._effect.setColor4("color", useOverlay ? mesh.overlayColor : mesh.outlineColor, useOverlay ? mesh.overlayAlpha : material.alpha);
  82101. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  82102. // Bones
  82103. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  82104. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  82105. }
  82106. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  82107. // Alpha test
  82108. if (material && material.needAlphaTesting()) {
  82109. var alphaTexture = material.getAlphaTestTexture();
  82110. if (alphaTexture) {
  82111. this._effect.setTexture("diffuseSampler", alphaTexture);
  82112. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  82113. }
  82114. }
  82115. engine.setZOffset(-this.zOffset);
  82116. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { _this._effect.setMatrix("world", world); });
  82117. engine.setZOffset(0);
  82118. };
  82119. OutlineRenderer.prototype.isReady = function (subMesh, useInstances) {
  82120. var defines = [];
  82121. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  82122. var mesh = subMesh.getMesh();
  82123. var material = subMesh.getMaterial();
  82124. if (material) {
  82125. // Alpha test
  82126. if (material.needAlphaTesting()) {
  82127. defines.push("#define ALPHATEST");
  82128. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  82129. attribs.push(BABYLON.VertexBuffer.UVKind);
  82130. defines.push("#define UV1");
  82131. }
  82132. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  82133. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  82134. defines.push("#define UV2");
  82135. }
  82136. }
  82137. //Logarithmic depth
  82138. if (material.useLogarithmicDepth) {
  82139. defines.push("#define LOGARITHMICDEPTH");
  82140. }
  82141. }
  82142. // Bones
  82143. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  82144. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  82145. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  82146. if (mesh.numBoneInfluencers > 4) {
  82147. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  82148. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  82149. }
  82150. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  82151. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  82152. }
  82153. else {
  82154. defines.push("#define NUM_BONE_INFLUENCERS 0");
  82155. }
  82156. // Instances
  82157. if (useInstances) {
  82158. defines.push("#define INSTANCES");
  82159. attribs.push("world0");
  82160. attribs.push("world1");
  82161. attribs.push("world2");
  82162. attribs.push("world3");
  82163. }
  82164. // Get correct effect
  82165. var join = defines.join("\n");
  82166. if (this._cachedDefines !== join) {
  82167. this._cachedDefines = join;
  82168. this._effect = this._scene.getEngine().createEffect("outline", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "offset", "color", "logarithmicDepthConstant"], ["diffuseSampler"], join);
  82169. }
  82170. return this._effect.isReady();
  82171. };
  82172. return OutlineRenderer;
  82173. }());
  82174. BABYLON.OutlineRenderer = OutlineRenderer;
  82175. })(BABYLON || (BABYLON = {}));
  82176. //# sourceMappingURL=babylon.outlineRenderer.js.map
  82177. var BABYLON;
  82178. (function (BABYLON) {
  82179. var FaceAdjacencies = /** @class */ (function () {
  82180. function FaceAdjacencies() {
  82181. this.edges = new Array();
  82182. this.edgesConnectedCount = 0;
  82183. }
  82184. return FaceAdjacencies;
  82185. }());
  82186. var EdgesRenderer = /** @class */ (function () {
  82187. // Beware when you use this class with complex objects as the adjacencies computation can be really long
  82188. function EdgesRenderer(source, epsilon, checkVerticesInsteadOfIndices) {
  82189. if (epsilon === void 0) { epsilon = 0.95; }
  82190. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  82191. this.edgesWidthScalerForOrthographic = 1000.0;
  82192. this.edgesWidthScalerForPerspective = 50.0;
  82193. this._linesPositions = new Array();
  82194. this._linesNormals = new Array();
  82195. this._linesIndices = new Array();
  82196. this._buffers = {};
  82197. this._checkVerticesInsteadOfIndices = false;
  82198. this._source = source;
  82199. this._checkVerticesInsteadOfIndices = checkVerticesInsteadOfIndices;
  82200. this._epsilon = epsilon;
  82201. this._prepareRessources();
  82202. this._generateEdgesLines();
  82203. }
  82204. EdgesRenderer.prototype._prepareRessources = function () {
  82205. if (this._lineShader) {
  82206. return;
  82207. }
  82208. this._lineShader = new BABYLON.ShaderMaterial("lineShader", this._source.getScene(), "line", {
  82209. attributes: ["position", "normal"],
  82210. uniforms: ["worldViewProjection", "color", "width", "aspectRatio"]
  82211. });
  82212. this._lineShader.disableDepthWrite = true;
  82213. this._lineShader.backFaceCulling = false;
  82214. };
  82215. EdgesRenderer.prototype._rebuild = function () {
  82216. var buffer = this._buffers[BABYLON.VertexBuffer.PositionKind];
  82217. if (buffer) {
  82218. buffer._rebuild();
  82219. }
  82220. buffer = this._buffers[BABYLON.VertexBuffer.NormalKind];
  82221. if (buffer) {
  82222. buffer._rebuild();
  82223. }
  82224. var scene = this._source.getScene();
  82225. var engine = scene.getEngine();
  82226. this._ib = engine.createIndexBuffer(this._linesIndices);
  82227. };
  82228. EdgesRenderer.prototype.dispose = function () {
  82229. var buffer = this._buffers[BABYLON.VertexBuffer.PositionKind];
  82230. if (buffer) {
  82231. buffer.dispose();
  82232. this._buffers[BABYLON.VertexBuffer.PositionKind] = null;
  82233. }
  82234. buffer = this._buffers[BABYLON.VertexBuffer.NormalKind];
  82235. if (buffer) {
  82236. buffer.dispose();
  82237. this._buffers[BABYLON.VertexBuffer.NormalKind] = null;
  82238. }
  82239. this._source.getScene().getEngine()._releaseBuffer(this._ib);
  82240. this._lineShader.dispose();
  82241. };
  82242. EdgesRenderer.prototype._processEdgeForAdjacencies = function (pa, pb, p0, p1, p2) {
  82243. if (pa === p0 && pb === p1 || pa === p1 && pb === p0) {
  82244. return 0;
  82245. }
  82246. if (pa === p1 && pb === p2 || pa === p2 && pb === p1) {
  82247. return 1;
  82248. }
  82249. if (pa === p2 && pb === p0 || pa === p0 && pb === p2) {
  82250. return 2;
  82251. }
  82252. return -1;
  82253. };
  82254. EdgesRenderer.prototype._processEdgeForAdjacenciesWithVertices = function (pa, pb, p0, p1, p2) {
  82255. if (pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p1) || pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p0)) {
  82256. return 0;
  82257. }
  82258. if (pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p2) || pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p1)) {
  82259. return 1;
  82260. }
  82261. if (pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p0) || pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p2)) {
  82262. return 2;
  82263. }
  82264. return -1;
  82265. };
  82266. EdgesRenderer.prototype._checkEdge = function (faceIndex, edge, faceNormals, p0, p1) {
  82267. var needToCreateLine;
  82268. if (edge === undefined) {
  82269. needToCreateLine = true;
  82270. }
  82271. else {
  82272. var dotProduct = BABYLON.Vector3.Dot(faceNormals[faceIndex], faceNormals[edge]);
  82273. needToCreateLine = dotProduct < this._epsilon;
  82274. }
  82275. if (needToCreateLine) {
  82276. var offset = this._linesPositions.length / 3;
  82277. var normal = p0.subtract(p1);
  82278. normal.normalize();
  82279. // Positions
  82280. this._linesPositions.push(p0.x);
  82281. this._linesPositions.push(p0.y);
  82282. this._linesPositions.push(p0.z);
  82283. this._linesPositions.push(p0.x);
  82284. this._linesPositions.push(p0.y);
  82285. this._linesPositions.push(p0.z);
  82286. this._linesPositions.push(p1.x);
  82287. this._linesPositions.push(p1.y);
  82288. this._linesPositions.push(p1.z);
  82289. this._linesPositions.push(p1.x);
  82290. this._linesPositions.push(p1.y);
  82291. this._linesPositions.push(p1.z);
  82292. // Normals
  82293. this._linesNormals.push(p1.x);
  82294. this._linesNormals.push(p1.y);
  82295. this._linesNormals.push(p1.z);
  82296. this._linesNormals.push(-1);
  82297. this._linesNormals.push(p1.x);
  82298. this._linesNormals.push(p1.y);
  82299. this._linesNormals.push(p1.z);
  82300. this._linesNormals.push(1);
  82301. this._linesNormals.push(p0.x);
  82302. this._linesNormals.push(p0.y);
  82303. this._linesNormals.push(p0.z);
  82304. this._linesNormals.push(-1);
  82305. this._linesNormals.push(p0.x);
  82306. this._linesNormals.push(p0.y);
  82307. this._linesNormals.push(p0.z);
  82308. this._linesNormals.push(1);
  82309. // Indices
  82310. this._linesIndices.push(offset);
  82311. this._linesIndices.push(offset + 1);
  82312. this._linesIndices.push(offset + 2);
  82313. this._linesIndices.push(offset);
  82314. this._linesIndices.push(offset + 2);
  82315. this._linesIndices.push(offset + 3);
  82316. }
  82317. };
  82318. EdgesRenderer.prototype._generateEdgesLines = function () {
  82319. var positions = this._source.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  82320. var indices = this._source.getIndices();
  82321. if (!indices || !positions) {
  82322. return;
  82323. }
  82324. // First let's find adjacencies
  82325. var adjacencies = new Array();
  82326. var faceNormals = new Array();
  82327. var index;
  82328. var faceAdjacencies;
  82329. // Prepare faces
  82330. for (index = 0; index < indices.length; index += 3) {
  82331. faceAdjacencies = new FaceAdjacencies();
  82332. var p0Index = indices[index];
  82333. var p1Index = indices[index + 1];
  82334. var p2Index = indices[index + 2];
  82335. faceAdjacencies.p0 = new BABYLON.Vector3(positions[p0Index * 3], positions[p0Index * 3 + 1], positions[p0Index * 3 + 2]);
  82336. faceAdjacencies.p1 = new BABYLON.Vector3(positions[p1Index * 3], positions[p1Index * 3 + 1], positions[p1Index * 3 + 2]);
  82337. faceAdjacencies.p2 = new BABYLON.Vector3(positions[p2Index * 3], positions[p2Index * 3 + 1], positions[p2Index * 3 + 2]);
  82338. var faceNormal = BABYLON.Vector3.Cross(faceAdjacencies.p1.subtract(faceAdjacencies.p0), faceAdjacencies.p2.subtract(faceAdjacencies.p1));
  82339. faceNormal.normalize();
  82340. faceNormals.push(faceNormal);
  82341. adjacencies.push(faceAdjacencies);
  82342. }
  82343. // Scan
  82344. for (index = 0; index < adjacencies.length; index++) {
  82345. faceAdjacencies = adjacencies[index];
  82346. for (var otherIndex = index + 1; otherIndex < adjacencies.length; otherIndex++) {
  82347. var otherFaceAdjacencies = adjacencies[otherIndex];
  82348. if (faceAdjacencies.edgesConnectedCount === 3) {
  82349. break;
  82350. }
  82351. if (otherFaceAdjacencies.edgesConnectedCount === 3) {
  82352. continue;
  82353. }
  82354. var otherP0 = indices[otherIndex * 3];
  82355. var otherP1 = indices[otherIndex * 3 + 1];
  82356. var otherP2 = indices[otherIndex * 3 + 2];
  82357. for (var edgeIndex = 0; edgeIndex < 3; edgeIndex++) {
  82358. var otherEdgeIndex = 0;
  82359. if (faceAdjacencies.edges[edgeIndex] !== undefined) {
  82360. continue;
  82361. }
  82362. switch (edgeIndex) {
  82363. case 0:
  82364. if (this._checkVerticesInsteadOfIndices) {
  82365. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p0, faceAdjacencies.p1, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  82366. }
  82367. else {
  82368. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3], indices[index * 3 + 1], otherP0, otherP1, otherP2);
  82369. }
  82370. break;
  82371. case 1:
  82372. if (this._checkVerticesInsteadOfIndices) {
  82373. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p1, faceAdjacencies.p2, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  82374. }
  82375. else {
  82376. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 1], indices[index * 3 + 2], otherP0, otherP1, otherP2);
  82377. }
  82378. break;
  82379. case 2:
  82380. if (this._checkVerticesInsteadOfIndices) {
  82381. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p2, faceAdjacencies.p0, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  82382. }
  82383. else {
  82384. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 2], indices[index * 3], otherP0, otherP1, otherP2);
  82385. }
  82386. break;
  82387. }
  82388. if (otherEdgeIndex === -1) {
  82389. continue;
  82390. }
  82391. faceAdjacencies.edges[edgeIndex] = otherIndex;
  82392. otherFaceAdjacencies.edges[otherEdgeIndex] = index;
  82393. faceAdjacencies.edgesConnectedCount++;
  82394. otherFaceAdjacencies.edgesConnectedCount++;
  82395. if (faceAdjacencies.edgesConnectedCount === 3) {
  82396. break;
  82397. }
  82398. }
  82399. }
  82400. }
  82401. // Create lines
  82402. for (index = 0; index < adjacencies.length; index++) {
  82403. // 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
  82404. var current = adjacencies[index];
  82405. this._checkEdge(index, current.edges[0], faceNormals, current.p0, current.p1);
  82406. this._checkEdge(index, current.edges[1], faceNormals, current.p1, current.p2);
  82407. this._checkEdge(index, current.edges[2], faceNormals, current.p2, current.p0);
  82408. }
  82409. // Merge into a single mesh
  82410. var engine = this._source.getScene().getEngine();
  82411. this._buffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, this._linesPositions, BABYLON.VertexBuffer.PositionKind, false);
  82412. this._buffers[BABYLON.VertexBuffer.NormalKind] = new BABYLON.VertexBuffer(engine, this._linesNormals, BABYLON.VertexBuffer.NormalKind, false, false, 4);
  82413. this._ib = engine.createIndexBuffer(this._linesIndices);
  82414. this._indicesCount = this._linesIndices.length;
  82415. };
  82416. EdgesRenderer.prototype.render = function () {
  82417. var scene = this._source.getScene();
  82418. if (!this._lineShader.isReady() || !scene.activeCamera) {
  82419. return;
  82420. }
  82421. var engine = scene.getEngine();
  82422. this._lineShader._preBind();
  82423. // VBOs
  82424. engine.bindBuffers(this._buffers, this._ib, this._lineShader.getEffect());
  82425. scene.resetCachedMaterial();
  82426. this._lineShader.setColor4("color", this._source.edgesColor);
  82427. if (scene.activeCamera.mode === BABYLON.Camera.ORTHOGRAPHIC_CAMERA) {
  82428. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForOrthographic);
  82429. }
  82430. else {
  82431. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForPerspective);
  82432. }
  82433. this._lineShader.setFloat("aspectRatio", engine.getAspectRatio(scene.activeCamera));
  82434. this._lineShader.bind(this._source.getWorldMatrix());
  82435. // Draw order
  82436. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, this._indicesCount);
  82437. this._lineShader.unbind();
  82438. engine.setDepthWrite(true);
  82439. };
  82440. return EdgesRenderer;
  82441. }());
  82442. BABYLON.EdgesRenderer = EdgesRenderer;
  82443. })(BABYLON || (BABYLON = {}));
  82444. //# sourceMappingURL=babylon.edgesRenderer.js.map
  82445. var __assign = (this && this.__assign) || Object.assign || function(t) {
  82446. for (var s, i = 1, n = arguments.length; i < n; i++) {
  82447. s = arguments[i];
  82448. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  82449. t[p] = s[p];
  82450. }
  82451. return t;
  82452. };
  82453. var BABYLON;
  82454. (function (BABYLON) {
  82455. /**
  82456. * The effect layer Helps adding post process effect blended with the main pass.
  82457. *
  82458. * This can be for instance use to generate glow or higlight effects on the scene.
  82459. *
  82460. * The effect layer class can not be used directly and is intented to inherited from to be
  82461. * customized per effects.
  82462. */
  82463. var EffectLayer = /** @class */ (function () {
  82464. /**
  82465. * Instantiates a new effect Layer and references it in the scene.
  82466. * @param name The name of the layer
  82467. * @param scene The scene to use the layer in
  82468. */
  82469. function EffectLayer(
  82470. /** The Friendly of the effect in the scene */
  82471. name, scene) {
  82472. this.name = name;
  82473. this._vertexBuffers = {};
  82474. this._maxSize = 0;
  82475. this._mainTextureDesiredSize = { width: 0, height: 0 };
  82476. this._shouldRender = true;
  82477. this._postProcesses = [];
  82478. this._textures = [];
  82479. this._emissiveTextureAndColor = { texture: null, color: new BABYLON.Color4() };
  82480. /**
  82481. * The clear color of the texture used to generate the glow map.
  82482. */
  82483. this.neutralColor = new BABYLON.Color4();
  82484. /**
  82485. * Specifies wether the highlight layer is enabled or not.
  82486. */
  82487. this.isEnabled = true;
  82488. /**
  82489. * An event triggered when the effect layer has been disposed.
  82490. */
  82491. this.onDisposeObservable = new BABYLON.Observable();
  82492. /**
  82493. * An event triggered when the effect layer is about rendering the main texture with the glowy parts.
  82494. */
  82495. this.onBeforeRenderMainTextureObservable = new BABYLON.Observable();
  82496. /**
  82497. * An event triggered when the generated texture is being merged in the scene.
  82498. */
  82499. this.onBeforeComposeObservable = new BABYLON.Observable();
  82500. /**
  82501. * An event triggered when the generated texture has been merged in the scene.
  82502. */
  82503. this.onAfterComposeObservable = new BABYLON.Observable();
  82504. /**
  82505. * An event triggered when the efffect layer changes its size.
  82506. */
  82507. this.onSizeChangedObservable = new BABYLON.Observable();
  82508. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  82509. this._engine = scene.getEngine();
  82510. this._maxSize = this._engine.getCaps().maxTextureSize;
  82511. this._scene.effectLayers.push(this);
  82512. // Generate Buffers
  82513. this._generateIndexBuffer();
  82514. this._genrateVertexBuffer();
  82515. }
  82516. Object.defineProperty(EffectLayer.prototype, "camera", {
  82517. /**
  82518. * Gets the camera attached to the layer.
  82519. */
  82520. get: function () {
  82521. return this._effectLayerOptions.camera;
  82522. },
  82523. enumerable: true,
  82524. configurable: true
  82525. });
  82526. /**
  82527. * Initializes the effect layer with the required options.
  82528. * @param options Sets of none mandatory options to use with the layer (see IEffectLayerOptions for more information)
  82529. */
  82530. EffectLayer.prototype._init = function (options) {
  82531. // Adapt options
  82532. this._effectLayerOptions = __assign({ mainTextureRatio: 0.5, alphaBlendingMode: BABYLON.Engine.ALPHA_COMBINE, camera: null }, options);
  82533. this._setMainTextureSize();
  82534. this._createMainTexture();
  82535. this._createTextureAndPostProcesses();
  82536. this._mergeEffect = this._createMergeEffect();
  82537. };
  82538. /**
  82539. * Generates the index buffer of the full screen quad blending to the main canvas.
  82540. */
  82541. EffectLayer.prototype._generateIndexBuffer = function () {
  82542. // Indices
  82543. var indices = [];
  82544. indices.push(0);
  82545. indices.push(1);
  82546. indices.push(2);
  82547. indices.push(0);
  82548. indices.push(2);
  82549. indices.push(3);
  82550. this._indexBuffer = this._engine.createIndexBuffer(indices);
  82551. };
  82552. /**
  82553. * Generates the vertex buffer of the full screen quad blending to the main canvas.
  82554. */
  82555. EffectLayer.prototype._genrateVertexBuffer = function () {
  82556. // VBO
  82557. var vertices = [];
  82558. vertices.push(1, 1);
  82559. vertices.push(-1, 1);
  82560. vertices.push(-1, -1);
  82561. vertices.push(1, -1);
  82562. var vertexBuffer = new BABYLON.VertexBuffer(this._engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  82563. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = vertexBuffer;
  82564. };
  82565. /**
  82566. * Sets the main texture desired size which is the closest power of two
  82567. * of the engine canvas size.
  82568. */
  82569. EffectLayer.prototype._setMainTextureSize = function () {
  82570. if (this._effectLayerOptions.mainTextureFixedSize) {
  82571. this._mainTextureDesiredSize.width = this._effectLayerOptions.mainTextureFixedSize;
  82572. this._mainTextureDesiredSize.height = this._effectLayerOptions.mainTextureFixedSize;
  82573. }
  82574. else {
  82575. this._mainTextureDesiredSize.width = this._engine.getRenderWidth() * this._effectLayerOptions.mainTextureRatio;
  82576. this._mainTextureDesiredSize.height = this._engine.getRenderHeight() * this._effectLayerOptions.mainTextureRatio;
  82577. this._mainTextureDesiredSize.width = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(this._mainTextureDesiredSize.width, this._maxSize) : this._mainTextureDesiredSize.width;
  82578. this._mainTextureDesiredSize.height = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(this._mainTextureDesiredSize.height, this._maxSize) : this._mainTextureDesiredSize.height;
  82579. }
  82580. this._mainTextureDesiredSize.width = Math.floor(this._mainTextureDesiredSize.width);
  82581. this._mainTextureDesiredSize.height = Math.floor(this._mainTextureDesiredSize.height);
  82582. };
  82583. /**
  82584. * Creates the main texture for the effect layer.
  82585. */
  82586. EffectLayer.prototype._createMainTexture = function () {
  82587. var _this = this;
  82588. this._mainTexture = new BABYLON.RenderTargetTexture("HighlightLayerMainRTT", {
  82589. width: this._mainTextureDesiredSize.width,
  82590. height: this._mainTextureDesiredSize.height
  82591. }, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  82592. this._mainTexture.activeCamera = this._effectLayerOptions.camera;
  82593. this._mainTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  82594. this._mainTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  82595. this._mainTexture.anisotropicFilteringLevel = 1;
  82596. this._mainTexture.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  82597. this._mainTexture.renderParticles = false;
  82598. this._mainTexture.renderList = null;
  82599. this._mainTexture.ignoreCameraViewport = true;
  82600. // Custom render function
  82601. this._mainTexture.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  82602. _this.onBeforeRenderMainTextureObservable.notifyObservers(_this);
  82603. var index;
  82604. var engine = _this._scene.getEngine();
  82605. if (depthOnlySubMeshes.length) {
  82606. engine.setColorWrite(false);
  82607. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  82608. _this._renderSubMesh(depthOnlySubMeshes.data[index]);
  82609. }
  82610. engine.setColorWrite(true);
  82611. }
  82612. for (index = 0; index < opaqueSubMeshes.length; index++) {
  82613. _this._renderSubMesh(opaqueSubMeshes.data[index]);
  82614. }
  82615. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  82616. _this._renderSubMesh(alphaTestSubMeshes.data[index]);
  82617. }
  82618. for (index = 0; index < transparentSubMeshes.length; index++) {
  82619. _this._renderSubMesh(transparentSubMeshes.data[index]);
  82620. }
  82621. };
  82622. this._mainTexture.onClearObservable.add(function (engine) {
  82623. engine.clear(_this.neutralColor, true, true, true);
  82624. });
  82625. };
  82626. /**
  82627. * Checks for the readiness of the element composing the layer.
  82628. * @param subMesh the mesh to check for
  82629. * @param useInstances specify wether or not to use instances to render the mesh
  82630. * @param emissiveTexture the associated emissive texture used to generate the glow
  82631. * @return true if ready otherwise, false
  82632. */
  82633. EffectLayer.prototype._isReady = function (subMesh, useInstances, emissiveTexture) {
  82634. var material = subMesh.getMaterial();
  82635. if (!material) {
  82636. return false;
  82637. }
  82638. if (!material.isReady(subMesh.getMesh(), useInstances)) {
  82639. return false;
  82640. }
  82641. var defines = [];
  82642. var attribs = [BABYLON.VertexBuffer.PositionKind];
  82643. var mesh = subMesh.getMesh();
  82644. var uv1 = false;
  82645. var uv2 = false;
  82646. // Alpha test
  82647. if (material && material.needAlphaTesting()) {
  82648. var alphaTexture = material.getAlphaTestTexture();
  82649. if (alphaTexture) {
  82650. defines.push("#define ALPHATEST");
  82651. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind) &&
  82652. alphaTexture.coordinatesIndex === 1) {
  82653. defines.push("#define DIFFUSEUV2");
  82654. uv2 = true;
  82655. }
  82656. else if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  82657. defines.push("#define DIFFUSEUV1");
  82658. uv1 = true;
  82659. }
  82660. }
  82661. }
  82662. // Emissive
  82663. if (emissiveTexture) {
  82664. defines.push("#define EMISSIVE");
  82665. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind) &&
  82666. emissiveTexture.coordinatesIndex === 1) {
  82667. defines.push("#define EMISSIVEUV2");
  82668. uv2 = true;
  82669. }
  82670. else if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  82671. defines.push("#define EMISSIVEUV1");
  82672. uv1 = true;
  82673. }
  82674. }
  82675. if (uv1) {
  82676. attribs.push(BABYLON.VertexBuffer.UVKind);
  82677. defines.push("#define UV1");
  82678. }
  82679. if (uv2) {
  82680. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  82681. defines.push("#define UV2");
  82682. }
  82683. // Bones
  82684. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  82685. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  82686. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  82687. if (mesh.numBoneInfluencers > 4) {
  82688. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  82689. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  82690. }
  82691. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  82692. defines.push("#define BonesPerMesh " + (mesh.skeleton ? (mesh.skeleton.bones.length + 1) : 0));
  82693. }
  82694. else {
  82695. defines.push("#define NUM_BONE_INFLUENCERS 0");
  82696. }
  82697. // Instances
  82698. if (useInstances) {
  82699. defines.push("#define INSTANCES");
  82700. attribs.push("world0");
  82701. attribs.push("world1");
  82702. attribs.push("world2");
  82703. attribs.push("world3");
  82704. }
  82705. // Get correct effect
  82706. var join = defines.join("\n");
  82707. if (this._cachedDefines !== join) {
  82708. this._cachedDefines = join;
  82709. this._effectLayerMapGenerationEffect = this._scene.getEngine().createEffect("glowMapGeneration", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "color", "emissiveMatrix"], ["diffuseSampler", "emissiveSampler"], join);
  82710. }
  82711. return this._effectLayerMapGenerationEffect.isReady();
  82712. };
  82713. /**
  82714. * Renders the glowing part of the scene by blending the blurred glowing meshes on top of the rendered scene.
  82715. */
  82716. EffectLayer.prototype.render = function () {
  82717. var currentEffect = this._mergeEffect;
  82718. // Check
  82719. if (!currentEffect.isReady())
  82720. return;
  82721. for (var i = 0; i < this._postProcesses.length; i++) {
  82722. if (!this._postProcesses[i].isReady()) {
  82723. return;
  82724. }
  82725. }
  82726. var engine = this._scene.getEngine();
  82727. this.onBeforeComposeObservable.notifyObservers(this);
  82728. // Render
  82729. engine.enableEffect(currentEffect);
  82730. engine.setState(false);
  82731. // VBOs
  82732. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect);
  82733. // Cache
  82734. var previousAlphaMode = engine.getAlphaMode();
  82735. // Go Blend.
  82736. engine.setAlphaMode(this._effectLayerOptions.alphaBlendingMode);
  82737. // Blends the map on the main canvas.
  82738. this._internalRender(currentEffect);
  82739. // Restore Alpha
  82740. engine.setAlphaMode(previousAlphaMode);
  82741. this.onAfterComposeObservable.notifyObservers(this);
  82742. // Handle size changes.
  82743. var size = this._mainTexture.getSize();
  82744. this._setMainTextureSize();
  82745. if (size.width !== this._mainTextureDesiredSize.width || size.height !== this._mainTextureDesiredSize.height) {
  82746. // Recreate RTT and post processes on size change.
  82747. this.onSizeChangedObservable.notifyObservers(this);
  82748. this._disposeTextureAndPostProcesses();
  82749. this._createMainTexture();
  82750. this._createTextureAndPostProcesses();
  82751. }
  82752. };
  82753. /**
  82754. * Determine if a given mesh will be used in the current effect.
  82755. * @param mesh mesh to test
  82756. * @returns true if the mesh will be used
  82757. */
  82758. EffectLayer.prototype.hasMesh = function (mesh) {
  82759. return true;
  82760. };
  82761. /**
  82762. * Returns true if the layer contains information to display, otherwise false.
  82763. * @returns true if the glow layer should be rendered
  82764. */
  82765. EffectLayer.prototype.shouldRender = function () {
  82766. return this.isEnabled && this._shouldRender;
  82767. };
  82768. /**
  82769. * Returns true if the mesh should render, otherwise false.
  82770. * @param mesh The mesh to render
  82771. * @returns true if it should render otherwise false
  82772. */
  82773. EffectLayer.prototype._shouldRenderMesh = function (mesh) {
  82774. return true;
  82775. };
  82776. /**
  82777. * Returns true if the mesh should render, otherwise false.
  82778. * @param mesh The mesh to render
  82779. * @returns true if it should render otherwise false
  82780. */
  82781. EffectLayer.prototype._shouldRenderEmissiveTextureForMesh = function (mesh) {
  82782. return true;
  82783. };
  82784. /**
  82785. * Renders the submesh passed in parameter to the generation map.
  82786. */
  82787. EffectLayer.prototype._renderSubMesh = function (subMesh) {
  82788. var _this = this;
  82789. if (!this.shouldRender()) {
  82790. return;
  82791. }
  82792. var material = subMesh.getMaterial();
  82793. var mesh = subMesh.getRenderingMesh();
  82794. var scene = this._scene;
  82795. var engine = scene.getEngine();
  82796. if (!material) {
  82797. return;
  82798. }
  82799. // Do not block in blend mode.
  82800. if (material.needAlphaBlendingForMesh(mesh)) {
  82801. return;
  82802. }
  82803. // Culling
  82804. engine.setState(material.backFaceCulling);
  82805. // Managing instances
  82806. var batch = mesh._getInstancesRenderList(subMesh._id);
  82807. if (batch.mustReturn) {
  82808. return;
  82809. }
  82810. // Early Exit per mesh
  82811. if (!this._shouldRenderMesh(mesh)) {
  82812. return;
  82813. }
  82814. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  82815. this._setEmissiveTextureAndColor(mesh, subMesh, material);
  82816. if (this._isReady(subMesh, hardwareInstancedRendering, this._emissiveTextureAndColor.texture)) {
  82817. engine.enableEffect(this._effectLayerMapGenerationEffect);
  82818. mesh._bind(subMesh, this._effectLayerMapGenerationEffect, BABYLON.Material.TriangleFillMode);
  82819. this._effectLayerMapGenerationEffect.setMatrix("viewProjection", scene.getTransformMatrix());
  82820. this._effectLayerMapGenerationEffect.setFloat4("color", this._emissiveTextureAndColor.color.r, this._emissiveTextureAndColor.color.g, this._emissiveTextureAndColor.color.b, this._emissiveTextureAndColor.color.a);
  82821. // Alpha test
  82822. if (material && material.needAlphaTesting()) {
  82823. var alphaTexture = material.getAlphaTestTexture();
  82824. if (alphaTexture) {
  82825. this._effectLayerMapGenerationEffect.setTexture("diffuseSampler", alphaTexture);
  82826. var textureMatrix = alphaTexture.getTextureMatrix();
  82827. if (textureMatrix) {
  82828. this._effectLayerMapGenerationEffect.setMatrix("diffuseMatrix", textureMatrix);
  82829. }
  82830. }
  82831. }
  82832. // Glow emissive only
  82833. if (this._emissiveTextureAndColor.texture) {
  82834. this._effectLayerMapGenerationEffect.setTexture("emissiveSampler", this._emissiveTextureAndColor.texture);
  82835. this._effectLayerMapGenerationEffect.setMatrix("emissiveMatrix", this._emissiveTextureAndColor.texture.getTextureMatrix());
  82836. }
  82837. // Bones
  82838. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  82839. this._effectLayerMapGenerationEffect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  82840. }
  82841. // Draw
  82842. mesh._processRendering(subMesh, this._effectLayerMapGenerationEffect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effectLayerMapGenerationEffect.setMatrix("world", world); });
  82843. }
  82844. else {
  82845. // Need to reset refresh rate of the shadowMap
  82846. this._mainTexture.resetRefreshCounter();
  82847. }
  82848. };
  82849. /**
  82850. * Rebuild the required buffers.
  82851. * @ignore Internal use only.
  82852. */
  82853. EffectLayer.prototype._rebuild = function () {
  82854. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  82855. if (vb) {
  82856. vb._rebuild();
  82857. }
  82858. this._generateIndexBuffer();
  82859. };
  82860. /**
  82861. * Dispose only the render target textures and post process.
  82862. */
  82863. EffectLayer.prototype._disposeTextureAndPostProcesses = function () {
  82864. this._mainTexture.dispose();
  82865. for (var i = 0; i < this._postProcesses.length; i++) {
  82866. if (this._postProcesses[i]) {
  82867. this._postProcesses[i].dispose();
  82868. }
  82869. }
  82870. this._postProcesses = [];
  82871. for (var i = 0; i < this._textures.length; i++) {
  82872. if (this._textures[i]) {
  82873. this._textures[i].dispose();
  82874. }
  82875. }
  82876. this._textures = [];
  82877. };
  82878. /**
  82879. * Dispose the highlight layer and free resources.
  82880. */
  82881. EffectLayer.prototype.dispose = function () {
  82882. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  82883. if (vertexBuffer) {
  82884. vertexBuffer.dispose();
  82885. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  82886. }
  82887. if (this._indexBuffer) {
  82888. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  82889. this._indexBuffer = null;
  82890. }
  82891. // Clean textures and post processes
  82892. this._disposeTextureAndPostProcesses();
  82893. // Remove from scene
  82894. var index = this._scene.effectLayers.indexOf(this, 0);
  82895. if (index > -1) {
  82896. this._scene.effectLayers.splice(index, 1);
  82897. }
  82898. // Callback
  82899. this.onDisposeObservable.notifyObservers(this);
  82900. this.onDisposeObservable.clear();
  82901. this.onBeforeRenderMainTextureObservable.clear();
  82902. this.onBeforeComposeObservable.clear();
  82903. this.onAfterComposeObservable.clear();
  82904. this.onSizeChangedObservable.clear();
  82905. };
  82906. return EffectLayer;
  82907. }());
  82908. BABYLON.EffectLayer = EffectLayer;
  82909. })(BABYLON || (BABYLON = {}));
  82910. //# sourceMappingURL=babylon.effectLayer.js.map
  82911. var BABYLON;
  82912. (function (BABYLON) {
  82913. /**
  82914. * Special Glow Blur post process only blurring the alpha channel
  82915. * It enforces keeping the most luminous color in the color channel.
  82916. */
  82917. var GlowBlurPostProcess = /** @class */ (function (_super) {
  82918. __extends(GlowBlurPostProcess, _super);
  82919. function GlowBlurPostProcess(name, direction, kernel, options, camera, samplingMode, engine, reusable) {
  82920. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  82921. var _this = _super.call(this, name, "glowBlurPostProcess", ["screenSize", "direction", "blurWidth"], null, options, camera, samplingMode, engine, reusable) || this;
  82922. _this.direction = direction;
  82923. _this.kernel = kernel;
  82924. _this.onApplyObservable.add(function (effect) {
  82925. effect.setFloat2("screenSize", _this.width, _this.height);
  82926. effect.setVector2("direction", _this.direction);
  82927. effect.setFloat("blurWidth", _this.kernel);
  82928. });
  82929. return _this;
  82930. }
  82931. return GlowBlurPostProcess;
  82932. }(BABYLON.PostProcess));
  82933. /**
  82934. * The highlight layer Helps adding a glow effect around a mesh.
  82935. *
  82936. * Once instantiated in a scene, simply use the pushMesh or removeMesh method to add or remove
  82937. * glowy meshes to your scene.
  82938. *
  82939. * !!! THIS REQUIRES AN ACTIVE STENCIL BUFFER ON THE CANVAS !!!
  82940. */
  82941. var HighlightLayer = /** @class */ (function (_super) {
  82942. __extends(HighlightLayer, _super);
  82943. /**
  82944. * Instantiates a new highlight Layer and references it to the scene..
  82945. * @param name The name of the layer
  82946. * @param scene The scene to use the layer in
  82947. * @param options Sets of none mandatory options to use with the layer (see IHighlightLayerOptions for more information)
  82948. */
  82949. function HighlightLayer(name, scene, options) {
  82950. var _this = _super.call(this, name, scene) || this;
  82951. _this.name = name;
  82952. /**
  82953. * Specifies whether or not the inner glow is ACTIVE in the layer.
  82954. */
  82955. _this.innerGlow = true;
  82956. /**
  82957. * Specifies whether or not the outer glow is ACTIVE in the layer.
  82958. */
  82959. _this.outerGlow = true;
  82960. /**
  82961. * An event triggered when the highlight layer is being blurred.
  82962. */
  82963. _this.onBeforeBlurObservable = new BABYLON.Observable();
  82964. /**
  82965. * An event triggered when the highlight layer has been blurred.
  82966. */
  82967. _this.onAfterBlurObservable = new BABYLON.Observable();
  82968. _this._instanceGlowingMeshStencilReference = HighlightLayer.GlowingMeshStencilReference++;
  82969. _this._meshes = {};
  82970. _this._excludedMeshes = {};
  82971. _this.neutralColor = HighlightLayer.NeutralColor;
  82972. // Warn on stencil
  82973. if (!_this._engine.isStencilEnable) {
  82974. 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 }");
  82975. }
  82976. // Adapt options
  82977. _this._options = __assign({ mainTextureRatio: 0.5, blurTextureSizeRatio: 0.5, blurHorizontalSize: 1.0, blurVerticalSize: 1.0, alphaBlendingMode: BABYLON.Engine.ALPHA_COMBINE, camera: null }, options);
  82978. // Initialize the layer
  82979. _this._init({
  82980. alphaBlendingMode: _this._options.alphaBlendingMode,
  82981. camera: _this._options.camera,
  82982. mainTextureFixedSize: _this._options.mainTextureFixedSize,
  82983. mainTextureRatio: _this._options.mainTextureRatio
  82984. });
  82985. // Do not render as long as no meshes have been added
  82986. _this._shouldRender = false;
  82987. return _this;
  82988. }
  82989. Object.defineProperty(HighlightLayer.prototype, "blurHorizontalSize", {
  82990. /**
  82991. * Gets the horizontal size of the blur.
  82992. */
  82993. get: function () {
  82994. return this._horizontalBlurPostprocess.kernel;
  82995. },
  82996. /**
  82997. * Specifies the horizontal size of the blur.
  82998. */
  82999. set: function (value) {
  83000. this._horizontalBlurPostprocess.kernel = value;
  83001. },
  83002. enumerable: true,
  83003. configurable: true
  83004. });
  83005. Object.defineProperty(HighlightLayer.prototype, "blurVerticalSize", {
  83006. /**
  83007. * Gets the vertical size of the blur.
  83008. */
  83009. get: function () {
  83010. return this._verticalBlurPostprocess.kernel;
  83011. },
  83012. /**
  83013. * Specifies the vertical size of the blur.
  83014. */
  83015. set: function (value) {
  83016. this._verticalBlurPostprocess.kernel = value;
  83017. },
  83018. enumerable: true,
  83019. configurable: true
  83020. });
  83021. /**
  83022. * Get the effect name of the layer.
  83023. * @return The effect name
  83024. */
  83025. HighlightLayer.prototype.getEffectName = function () {
  83026. return HighlightLayer.EffectName;
  83027. };
  83028. /**
  83029. * Create the merge effect. This is the shader use to blit the information back
  83030. * to the main canvas at the end of the scene rendering.
  83031. */
  83032. HighlightLayer.prototype._createMergeEffect = function () {
  83033. // Effect
  83034. return this._engine.createEffect("glowMapMerge", [BABYLON.VertexBuffer.PositionKind], ["offset"], ["textureSampler"], this._options.isStroke ? "#define STROKE \n" : undefined);
  83035. };
  83036. /**
  83037. * Creates the render target textures and post processes used in the highlight layer.
  83038. */
  83039. HighlightLayer.prototype._createTextureAndPostProcesses = function () {
  83040. var _this = this;
  83041. var blurTextureWidth = this._mainTextureDesiredSize.width * this._options.blurTextureSizeRatio;
  83042. var blurTextureHeight = this._mainTextureDesiredSize.height * this._options.blurTextureSizeRatio;
  83043. blurTextureWidth = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureWidth, this._maxSize) : blurTextureWidth;
  83044. blurTextureHeight = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureHeight, this._maxSize) : blurTextureHeight;
  83045. this._blurTexture = new BABYLON.RenderTargetTexture("HighlightLayerBlurRTT", {
  83046. width: blurTextureWidth,
  83047. height: blurTextureHeight
  83048. }, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  83049. this._blurTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  83050. this._blurTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  83051. this._blurTexture.anisotropicFilteringLevel = 16;
  83052. this._blurTexture.updateSamplingMode(BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  83053. this._blurTexture.renderParticles = false;
  83054. this._blurTexture.ignoreCameraViewport = true;
  83055. this._textures = [this._blurTexture];
  83056. if (this._options.alphaBlendingMode === BABYLON.Engine.ALPHA_COMBINE) {
  83057. this._downSamplePostprocess = new BABYLON.PassPostProcess("HighlightLayerPPP", this._options.blurTextureSizeRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  83058. this._downSamplePostprocess.onApplyObservable.add(function (effect) {
  83059. effect.setTexture("textureSampler", _this._mainTexture);
  83060. });
  83061. this._horizontalBlurPostprocess = new GlowBlurPostProcess("HighlightLayerHBP", new BABYLON.Vector2(1.0, 0), this._options.blurHorizontalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  83062. this._horizontalBlurPostprocess.onApplyObservable.add(function (effect) {
  83063. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  83064. });
  83065. this._verticalBlurPostprocess = new GlowBlurPostProcess("HighlightLayerVBP", new BABYLON.Vector2(0, 1.0), this._options.blurVerticalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  83066. this._verticalBlurPostprocess.onApplyObservable.add(function (effect) {
  83067. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  83068. });
  83069. this._postProcesses = [this._downSamplePostprocess, this._horizontalBlurPostprocess, this._verticalBlurPostprocess];
  83070. }
  83071. else {
  83072. this._horizontalBlurPostprocess = new BABYLON.BlurPostProcess("HighlightLayerHBP", new BABYLON.Vector2(1.0, 0), this._options.blurHorizontalSize / 2, {
  83073. width: blurTextureWidth,
  83074. height: blurTextureHeight
  83075. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  83076. this._horizontalBlurPostprocess.width = blurTextureWidth;
  83077. this._horizontalBlurPostprocess.height = blurTextureHeight;
  83078. this._horizontalBlurPostprocess.onApplyObservable.add(function (effect) {
  83079. effect.setTexture("textureSampler", _this._mainTexture);
  83080. });
  83081. this._verticalBlurPostprocess = new BABYLON.BlurPostProcess("HighlightLayerVBP", new BABYLON.Vector2(0, 1.0), this._options.blurVerticalSize / 2, {
  83082. width: blurTextureWidth,
  83083. height: blurTextureHeight
  83084. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  83085. this._postProcesses = [this._horizontalBlurPostprocess, this._verticalBlurPostprocess];
  83086. }
  83087. this._mainTexture.onAfterUnbindObservable.add(function () {
  83088. _this.onBeforeBlurObservable.notifyObservers(_this);
  83089. var internalTexture = _this._blurTexture.getInternalTexture();
  83090. if (internalTexture) {
  83091. _this._scene.postProcessManager.directRender(_this._postProcesses, internalTexture, true);
  83092. }
  83093. _this.onAfterBlurObservable.notifyObservers(_this);
  83094. });
  83095. // Prevent autoClear.
  83096. this._postProcesses.map(function (pp) { pp.autoClear = false; });
  83097. };
  83098. /**
  83099. * Returns wether or nood the layer needs stencil enabled during the mesh rendering.
  83100. */
  83101. HighlightLayer.prototype.needStencil = function () {
  83102. return true;
  83103. };
  83104. /**
  83105. * Checks for the readiness of the element composing the layer.
  83106. * @param subMesh the mesh to check for
  83107. * @param useInstances specify wether or not to use instances to render the mesh
  83108. * @param emissiveTexture the associated emissive texture used to generate the glow
  83109. * @return true if ready otherwise, false
  83110. */
  83111. HighlightLayer.prototype.isReady = function (subMesh, useInstances) {
  83112. var material = subMesh.getMaterial();
  83113. var mesh = subMesh.getRenderingMesh();
  83114. if (!material || !mesh || !this._meshes) {
  83115. return false;
  83116. }
  83117. var emissiveTexture = null;
  83118. var highlightLayerMesh = this._meshes[mesh.uniqueId];
  83119. if (highlightLayerMesh && highlightLayerMesh.glowEmissiveOnly && material) {
  83120. emissiveTexture = material.emissiveTexture;
  83121. }
  83122. return _super.prototype._isReady.call(this, subMesh, useInstances, emissiveTexture);
  83123. };
  83124. /**
  83125. * Implementation specific of rendering the generating effect on the main canvas.
  83126. * @param effect The effect used to render through
  83127. */
  83128. HighlightLayer.prototype._internalRender = function (effect) {
  83129. // Texture
  83130. effect.setTexture("textureSampler", this._blurTexture);
  83131. // Cache
  83132. var engine = this._engine;
  83133. var previousStencilBuffer = engine.getStencilBuffer();
  83134. var previousStencilFunction = engine.getStencilFunction();
  83135. var previousStencilMask = engine.getStencilMask();
  83136. var previousStencilOperationPass = engine.getStencilOperationPass();
  83137. var previousStencilOperationFail = engine.getStencilOperationFail();
  83138. var previousStencilOperationDepthFail = engine.getStencilOperationDepthFail();
  83139. var previousStencilReference = engine.getStencilFunctionReference();
  83140. // Stencil operations
  83141. engine.setStencilOperationPass(BABYLON.Engine.REPLACE);
  83142. engine.setStencilOperationFail(BABYLON.Engine.KEEP);
  83143. engine.setStencilOperationDepthFail(BABYLON.Engine.KEEP);
  83144. // Draw order
  83145. engine.setStencilMask(0x00);
  83146. engine.setStencilBuffer(true);
  83147. engine.setStencilFunctionReference(this._instanceGlowingMeshStencilReference);
  83148. // 2 passes inner outer
  83149. if (this.outerGlow) {
  83150. effect.setFloat("offset", 0);
  83151. engine.setStencilFunction(BABYLON.Engine.NOTEQUAL);
  83152. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  83153. }
  83154. if (this.innerGlow) {
  83155. effect.setFloat("offset", 1);
  83156. engine.setStencilFunction(BABYLON.Engine.EQUAL);
  83157. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  83158. }
  83159. // Restore Cache
  83160. engine.setStencilFunction(previousStencilFunction);
  83161. engine.setStencilMask(previousStencilMask);
  83162. engine.setStencilBuffer(previousStencilBuffer);
  83163. engine.setStencilOperationPass(previousStencilOperationPass);
  83164. engine.setStencilOperationFail(previousStencilOperationFail);
  83165. engine.setStencilOperationDepthFail(previousStencilOperationDepthFail);
  83166. engine.setStencilFunctionReference(previousStencilReference);
  83167. };
  83168. /**
  83169. * Returns true if the layer contains information to display, otherwise false.
  83170. */
  83171. HighlightLayer.prototype.shouldRender = function () {
  83172. if (_super.prototype.shouldRender.call(this)) {
  83173. return this._meshes ? true : false;
  83174. }
  83175. return false;
  83176. };
  83177. /**
  83178. * Returns true if the mesh should render, otherwise false.
  83179. * @param mesh The mesh to render
  83180. * @returns true if it should render otherwise false
  83181. */
  83182. HighlightLayer.prototype._shouldRenderMesh = function (mesh) {
  83183. // Excluded Mesh
  83184. if (this._excludedMeshes && this._excludedMeshes[mesh.uniqueId]) {
  83185. return false;
  83186. }
  83187. ;
  83188. return true;
  83189. };
  83190. /**
  83191. * Sets the required values for both the emissive texture and and the main color.
  83192. */
  83193. HighlightLayer.prototype._setEmissiveTextureAndColor = function (mesh, subMesh, material) {
  83194. var highlightLayerMesh = this._meshes[mesh.uniqueId];
  83195. if (highlightLayerMesh) {
  83196. this._emissiveTextureAndColor.color.set(highlightLayerMesh.color.r, highlightLayerMesh.color.g, highlightLayerMesh.color.b, 1.0);
  83197. }
  83198. else {
  83199. this._emissiveTextureAndColor.color.set(this.neutralColor.r, this.neutralColor.g, this.neutralColor.b, this.neutralColor.a);
  83200. }
  83201. if (highlightLayerMesh && highlightLayerMesh.glowEmissiveOnly && material) {
  83202. this._emissiveTextureAndColor.texture = material.emissiveTexture;
  83203. this._emissiveTextureAndColor.color.set(1.0, 1.0, 1.0, 1.0);
  83204. }
  83205. else {
  83206. this._emissiveTextureAndColor.texture = null;
  83207. }
  83208. };
  83209. /**
  83210. * Add a mesh in the exclusion list to prevent it to impact or being impacted by the highlight layer.
  83211. * @param mesh The mesh to exclude from the highlight layer
  83212. */
  83213. HighlightLayer.prototype.addExcludedMesh = function (mesh) {
  83214. if (!this._excludedMeshes) {
  83215. return;
  83216. }
  83217. var meshExcluded = this._excludedMeshes[mesh.uniqueId];
  83218. if (!meshExcluded) {
  83219. this._excludedMeshes[mesh.uniqueId] = {
  83220. mesh: mesh,
  83221. beforeRender: mesh.onBeforeRenderObservable.add(function (mesh) {
  83222. mesh.getEngine().setStencilBuffer(false);
  83223. }),
  83224. afterRender: mesh.onAfterRenderObservable.add(function (mesh) {
  83225. mesh.getEngine().setStencilBuffer(true);
  83226. }),
  83227. };
  83228. }
  83229. };
  83230. /**
  83231. * Remove a mesh from the exclusion list to let it impact or being impacted by the highlight layer.
  83232. * @param mesh The mesh to highlight
  83233. */
  83234. HighlightLayer.prototype.removeExcludedMesh = function (mesh) {
  83235. if (!this._excludedMeshes) {
  83236. return;
  83237. }
  83238. var meshExcluded = this._excludedMeshes[mesh.uniqueId];
  83239. if (meshExcluded) {
  83240. if (meshExcluded.beforeRender) {
  83241. mesh.onBeforeRenderObservable.remove(meshExcluded.beforeRender);
  83242. }
  83243. if (meshExcluded.afterRender) {
  83244. mesh.onAfterRenderObservable.remove(meshExcluded.afterRender);
  83245. }
  83246. }
  83247. this._excludedMeshes[mesh.uniqueId] = null;
  83248. };
  83249. /**
  83250. * Determine if a given mesh will be highlighted by the current HighlightLayer
  83251. * @param mesh mesh to test
  83252. * @returns true if the mesh will be highlighted by the current HighlightLayer
  83253. */
  83254. HighlightLayer.prototype.hasMesh = function (mesh) {
  83255. if (!this._meshes) {
  83256. return false;
  83257. }
  83258. return this._meshes[mesh.uniqueId] !== undefined && this._meshes[mesh.uniqueId] !== null;
  83259. };
  83260. /**
  83261. * Add a mesh in the highlight layer in order to make it glow with the chosen color.
  83262. * @param mesh The mesh to highlight
  83263. * @param color The color of the highlight
  83264. * @param glowEmissiveOnly Extract the glow from the emissive texture
  83265. */
  83266. HighlightLayer.prototype.addMesh = function (mesh, color, glowEmissiveOnly) {
  83267. var _this = this;
  83268. if (glowEmissiveOnly === void 0) { glowEmissiveOnly = false; }
  83269. if (!this._meshes) {
  83270. return;
  83271. }
  83272. var meshHighlight = this._meshes[mesh.uniqueId];
  83273. if (meshHighlight) {
  83274. meshHighlight.color = color;
  83275. }
  83276. else {
  83277. this._meshes[mesh.uniqueId] = {
  83278. mesh: mesh,
  83279. color: color,
  83280. // Lambda required for capture due to Observable this context
  83281. observerHighlight: mesh.onBeforeRenderObservable.add(function (mesh) {
  83282. if (_this._excludedMeshes && _this._excludedMeshes[mesh.uniqueId]) {
  83283. _this._defaultStencilReference(mesh);
  83284. }
  83285. else {
  83286. mesh.getScene().getEngine().setStencilFunctionReference(_this._instanceGlowingMeshStencilReference);
  83287. }
  83288. }),
  83289. observerDefault: mesh.onAfterRenderObservable.add(this._defaultStencilReference),
  83290. glowEmissiveOnly: glowEmissiveOnly
  83291. };
  83292. }
  83293. this._shouldRender = true;
  83294. };
  83295. /**
  83296. * Remove a mesh from the highlight layer in order to make it stop glowing.
  83297. * @param mesh The mesh to highlight
  83298. */
  83299. HighlightLayer.prototype.removeMesh = function (mesh) {
  83300. if (!this._meshes) {
  83301. return;
  83302. }
  83303. var meshHighlight = this._meshes[mesh.uniqueId];
  83304. if (meshHighlight) {
  83305. if (meshHighlight.observerHighlight) {
  83306. mesh.onBeforeRenderObservable.remove(meshHighlight.observerHighlight);
  83307. }
  83308. if (meshHighlight.observerDefault) {
  83309. mesh.onAfterRenderObservable.remove(meshHighlight.observerDefault);
  83310. }
  83311. delete this._meshes[mesh.uniqueId];
  83312. }
  83313. this._shouldRender = false;
  83314. for (var meshHighlightToCheck in this._meshes) {
  83315. if (this._meshes[meshHighlightToCheck]) {
  83316. this._shouldRender = true;
  83317. break;
  83318. }
  83319. }
  83320. };
  83321. /**
  83322. * Force the stencil to the normal expected value for none glowing parts
  83323. */
  83324. HighlightLayer.prototype._defaultStencilReference = function (mesh) {
  83325. mesh.getScene().getEngine().setStencilFunctionReference(HighlightLayer.NormalMeshStencilReference);
  83326. };
  83327. /**
  83328. * Free any resources and references associated to a mesh.
  83329. * Internal use
  83330. * @param mesh The mesh to free.
  83331. */
  83332. HighlightLayer.prototype._disposeMesh = function (mesh) {
  83333. this.removeMesh(mesh);
  83334. this.removeExcludedMesh(mesh);
  83335. };
  83336. /**
  83337. * Dispose the highlight layer and free resources.
  83338. */
  83339. HighlightLayer.prototype.dispose = function () {
  83340. if (this._meshes) {
  83341. // Clean mesh references
  83342. for (var id in this._meshes) {
  83343. var meshHighlight = this._meshes[id];
  83344. if (meshHighlight && meshHighlight.mesh) {
  83345. if (meshHighlight.observerHighlight) {
  83346. meshHighlight.mesh.onBeforeRenderObservable.remove(meshHighlight.observerHighlight);
  83347. }
  83348. if (meshHighlight.observerDefault) {
  83349. meshHighlight.mesh.onAfterRenderObservable.remove(meshHighlight.observerDefault);
  83350. }
  83351. }
  83352. }
  83353. this._meshes = null;
  83354. }
  83355. if (this._excludedMeshes) {
  83356. for (var id in this._excludedMeshes) {
  83357. var meshHighlight = this._excludedMeshes[id];
  83358. if (meshHighlight) {
  83359. if (meshHighlight.beforeRender) {
  83360. meshHighlight.mesh.onBeforeRenderObservable.remove(meshHighlight.beforeRender);
  83361. }
  83362. if (meshHighlight.afterRender) {
  83363. meshHighlight.mesh.onAfterRenderObservable.remove(meshHighlight.afterRender);
  83364. }
  83365. }
  83366. }
  83367. this._excludedMeshes = null;
  83368. }
  83369. _super.prototype.dispose.call(this);
  83370. };
  83371. /**
  83372. * Effect Name of the highlight layer.
  83373. */
  83374. HighlightLayer.EffectName = "HighlightLayer";
  83375. /**
  83376. * The neutral color used during the preparation of the glow effect.
  83377. * This is black by default as the blend operation is a blend operation.
  83378. */
  83379. HighlightLayer.NeutralColor = new BABYLON.Color4(0, 0, 0, 0);
  83380. /**
  83381. * Stencil value used for glowing meshes.
  83382. */
  83383. HighlightLayer.GlowingMeshStencilReference = 0x02;
  83384. /**
  83385. * Stencil value used for the other meshes in the scene.
  83386. */
  83387. HighlightLayer.NormalMeshStencilReference = 0x01;
  83388. return HighlightLayer;
  83389. }(BABYLON.EffectLayer));
  83390. BABYLON.HighlightLayer = HighlightLayer;
  83391. })(BABYLON || (BABYLON = {}));
  83392. //# sourceMappingURL=babylon.highlightLayer.js.map
  83393. var BABYLON;
  83394. (function (BABYLON) {
  83395. /**
  83396. * The glow layer Helps adding a glow effect around the emissive parts of a mesh.
  83397. *
  83398. * Once instantiated in a scene, simply use the pushMesh or removeMesh method to add or remove
  83399. * glowy meshes to your scene.
  83400. *
  83401. * Documentation: https://doc.babylonjs.com/how_to/glow_layer
  83402. */
  83403. var GlowLayer = /** @class */ (function (_super) {
  83404. __extends(GlowLayer, _super);
  83405. /**
  83406. * Instantiates a new glow Layer and references it to the scene.
  83407. * @param name The name of the layer
  83408. * @param scene The scene to use the layer in
  83409. * @param options Sets of none mandatory options to use with the layer (see IGlowLayerOptions for more information)
  83410. */
  83411. function GlowLayer(name, scene, options) {
  83412. var _this = _super.call(this, name, scene) || this;
  83413. _this.name = name;
  83414. _this._intensity = 1.0;
  83415. _this._includedOnlyMeshes = [];
  83416. _this._excludedMeshes = [];
  83417. _this.neutralColor = new BABYLON.Color4(0, 0, 0, 1);
  83418. // Adapt options
  83419. _this._options = __assign({ mainTextureRatio: GlowLayer.DefaultTextureRatio, blurKernelSize: 32, mainTextureFixedSize: undefined, camera: null, mainTextureSamples: 1 }, options);
  83420. // Initialize the layer
  83421. _this._init({
  83422. alphaBlendingMode: BABYLON.Engine.ALPHA_ADD,
  83423. camera: _this._options.camera,
  83424. mainTextureFixedSize: _this._options.mainTextureFixedSize,
  83425. mainTextureRatio: _this._options.mainTextureRatio
  83426. });
  83427. return _this;
  83428. }
  83429. Object.defineProperty(GlowLayer.prototype, "blurKernelSize", {
  83430. /**
  83431. * Gets the kernel size of the blur.
  83432. */
  83433. get: function () {
  83434. return this._horizontalBlurPostprocess1.kernel;
  83435. },
  83436. /**
  83437. * Sets the kernel size of the blur.
  83438. */
  83439. set: function (value) {
  83440. this._horizontalBlurPostprocess1.kernel = value;
  83441. this._verticalBlurPostprocess1.kernel = value;
  83442. this._horizontalBlurPostprocess2.kernel = value;
  83443. this._verticalBlurPostprocess2.kernel = value;
  83444. },
  83445. enumerable: true,
  83446. configurable: true
  83447. });
  83448. Object.defineProperty(GlowLayer.prototype, "intensity", {
  83449. /**
  83450. * Gets the glow intensity.
  83451. */
  83452. get: function () {
  83453. return this._intensity;
  83454. },
  83455. /**
  83456. * Sets the glow intensity.
  83457. */
  83458. set: function (value) {
  83459. this._intensity = value;
  83460. },
  83461. enumerable: true,
  83462. configurable: true
  83463. });
  83464. /**
  83465. * Get the effect name of the layer.
  83466. * @return The effect name
  83467. */
  83468. GlowLayer.prototype.getEffectName = function () {
  83469. return GlowLayer.EffectName;
  83470. };
  83471. /**
  83472. * Create the merge effect. This is the shader use to blit the information back
  83473. * to the main canvas at the end of the scene rendering.
  83474. */
  83475. GlowLayer.prototype._createMergeEffect = function () {
  83476. // Effect
  83477. return this._engine.createEffect("glowMapMerge", [BABYLON.VertexBuffer.PositionKind], ["offset"], ["textureSampler", "textureSampler2"], "#define EMISSIVE \n");
  83478. };
  83479. /**
  83480. * Creates the render target textures and post processes used in the glow layer.
  83481. */
  83482. GlowLayer.prototype._createTextureAndPostProcesses = function () {
  83483. var _this = this;
  83484. var blurTextureWidth = this._mainTextureDesiredSize.width;
  83485. var blurTextureHeight = this._mainTextureDesiredSize.height;
  83486. blurTextureWidth = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureWidth, this._maxSize) : blurTextureWidth;
  83487. blurTextureHeight = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureHeight, this._maxSize) : blurTextureHeight;
  83488. this._blurTexture1 = new BABYLON.RenderTargetTexture("GlowLayerBlurRTT", {
  83489. width: blurTextureWidth,
  83490. height: blurTextureHeight
  83491. }, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  83492. this._blurTexture1.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  83493. this._blurTexture1.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  83494. this._blurTexture1.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  83495. this._blurTexture1.renderParticles = false;
  83496. this._blurTexture1.ignoreCameraViewport = true;
  83497. var blurTextureWidth2 = Math.floor(blurTextureWidth / 2);
  83498. var blurTextureHeight2 = Math.floor(blurTextureHeight / 2);
  83499. this._blurTexture2 = new BABYLON.RenderTargetTexture("GlowLayerBlurRTT2", {
  83500. width: blurTextureWidth2,
  83501. height: blurTextureHeight2
  83502. }, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  83503. this._blurTexture2.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  83504. this._blurTexture2.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  83505. this._blurTexture2.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  83506. this._blurTexture2.renderParticles = false;
  83507. this._blurTexture2.ignoreCameraViewport = true;
  83508. this._textures = [this._blurTexture1, this._blurTexture2];
  83509. this._horizontalBlurPostprocess1 = new BABYLON.BlurPostProcess("GlowLayerHBP1", new BABYLON.Vector2(1.0, 0), this._options.blurKernelSize / 2, {
  83510. width: blurTextureWidth,
  83511. height: blurTextureHeight
  83512. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  83513. this._horizontalBlurPostprocess1.width = blurTextureWidth;
  83514. this._horizontalBlurPostprocess1.height = blurTextureHeight;
  83515. this._horizontalBlurPostprocess1.onApplyObservable.add(function (effect) {
  83516. effect.setTexture("textureSampler", _this._mainTexture);
  83517. });
  83518. this._verticalBlurPostprocess1 = new BABYLON.BlurPostProcess("GlowLayerVBP1", new BABYLON.Vector2(0, 1.0), this._options.blurKernelSize / 2, {
  83519. width: blurTextureWidth,
  83520. height: blurTextureHeight
  83521. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  83522. this._horizontalBlurPostprocess2 = new BABYLON.BlurPostProcess("GlowLayerHBP2", new BABYLON.Vector2(1.0, 0), this._options.blurKernelSize / 2, {
  83523. width: blurTextureWidth2,
  83524. height: blurTextureHeight2
  83525. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  83526. this._horizontalBlurPostprocess2.width = blurTextureWidth2;
  83527. this._horizontalBlurPostprocess2.height = blurTextureHeight2;
  83528. this._horizontalBlurPostprocess2.onApplyObservable.add(function (effect) {
  83529. effect.setTexture("textureSampler", _this._blurTexture1);
  83530. });
  83531. this._verticalBlurPostprocess2 = new BABYLON.BlurPostProcess("GlowLayerVBP2", new BABYLON.Vector2(0, 1.0), this._options.blurKernelSize / 2, {
  83532. width: blurTextureWidth2,
  83533. height: blurTextureHeight2
  83534. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  83535. this._postProcesses = [this._horizontalBlurPostprocess1, this._verticalBlurPostprocess1, this._horizontalBlurPostprocess2, this._verticalBlurPostprocess2];
  83536. this._postProcesses1 = [this._horizontalBlurPostprocess1, this._verticalBlurPostprocess1];
  83537. this._postProcesses2 = [this._horizontalBlurPostprocess2, this._verticalBlurPostprocess2];
  83538. this._mainTexture.samples = this._options.mainTextureSamples;
  83539. this._mainTexture.onAfterUnbindObservable.add(function () {
  83540. var internalTexture = _this._blurTexture1.getInternalTexture();
  83541. if (internalTexture) {
  83542. _this._scene.postProcessManager.directRender(_this._postProcesses1, internalTexture, true);
  83543. internalTexture = _this._blurTexture2.getInternalTexture();
  83544. if (internalTexture) {
  83545. _this._scene.postProcessManager.directRender(_this._postProcesses2, internalTexture, true);
  83546. }
  83547. }
  83548. });
  83549. // Prevent autoClear.
  83550. this._postProcesses.map(function (pp) { pp.autoClear = false; });
  83551. };
  83552. /**
  83553. * Checks for the readiness of the element composing the layer.
  83554. * @param subMesh the mesh to check for
  83555. * @param useInstances specify wether or not to use instances to render the mesh
  83556. * @param emissiveTexture the associated emissive texture used to generate the glow
  83557. * @return true if ready otherwise, false
  83558. */
  83559. GlowLayer.prototype.isReady = function (subMesh, useInstances) {
  83560. var material = subMesh.getMaterial();
  83561. var mesh = subMesh.getRenderingMesh();
  83562. if (!material || !mesh) {
  83563. return false;
  83564. }
  83565. var emissiveTexture = material.emissiveTexture;
  83566. return _super.prototype._isReady.call(this, subMesh, useInstances, emissiveTexture);
  83567. };
  83568. /**
  83569. * Returns wether or nood the layer needs stencil enabled during the mesh rendering.
  83570. */
  83571. GlowLayer.prototype.needStencil = function () {
  83572. return false;
  83573. };
  83574. /**
  83575. * Implementation specific of rendering the generating effect on the main canvas.
  83576. * @param effect The effect used to render through
  83577. */
  83578. GlowLayer.prototype._internalRender = function (effect) {
  83579. // Texture
  83580. effect.setTexture("textureSampler", this._blurTexture1);
  83581. effect.setTexture("textureSampler2", this._blurTexture2);
  83582. effect.setFloat("offset", this._intensity);
  83583. // Cache
  83584. var engine = this._engine;
  83585. var previousStencilBuffer = engine.getStencilBuffer();
  83586. // Draw order
  83587. engine.setStencilBuffer(false);
  83588. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  83589. // Draw order
  83590. engine.setStencilBuffer(previousStencilBuffer);
  83591. };
  83592. /**
  83593. * Sets the required values for both the emissive texture and and the main color.
  83594. */
  83595. GlowLayer.prototype._setEmissiveTextureAndColor = function (mesh, subMesh, material) {
  83596. var textureLevel = 1.0;
  83597. if (this.customEmissiveTextureSelector) {
  83598. this._emissiveTextureAndColor.texture = this.customEmissiveTextureSelector(mesh, subMesh, material);
  83599. }
  83600. else {
  83601. if (material) {
  83602. this._emissiveTextureAndColor.texture = material.emissiveTexture;
  83603. if (this._emissiveTextureAndColor.texture) {
  83604. textureLevel = this._emissiveTextureAndColor.texture.level;
  83605. }
  83606. }
  83607. else {
  83608. this._emissiveTextureAndColor.texture = null;
  83609. }
  83610. }
  83611. if (this.customEmissiveColorSelector) {
  83612. this.customEmissiveColorSelector(mesh, subMesh, material, this._emissiveTextureAndColor.color);
  83613. }
  83614. else {
  83615. if (material.emissiveColor) {
  83616. this._emissiveTextureAndColor.color.set(material.emissiveColor.r * textureLevel, material.emissiveColor.g * textureLevel, material.emissiveColor.b * textureLevel, 1.0);
  83617. }
  83618. else {
  83619. this._emissiveTextureAndColor.color.set(this.neutralColor.r, this.neutralColor.g, this.neutralColor.b, this.neutralColor.a);
  83620. }
  83621. }
  83622. };
  83623. /**
  83624. * Returns true if the mesh should render, otherwise false.
  83625. * @param mesh The mesh to render
  83626. * @returns true if it should render otherwise false
  83627. */
  83628. GlowLayer.prototype._shouldRenderMesh = function (mesh) {
  83629. return this.hasMesh(mesh);
  83630. };
  83631. /**
  83632. * Add a mesh in the exclusion list to prevent it to impact or being impacted by the glow layer.
  83633. * @param mesh The mesh to exclude from the glow layer
  83634. */
  83635. GlowLayer.prototype.addExcludedMesh = function (mesh) {
  83636. if (this._excludedMeshes.indexOf(mesh.uniqueId) === -1) {
  83637. this._excludedMeshes.push(mesh.uniqueId);
  83638. }
  83639. };
  83640. /**
  83641. * Remove a mesh from the exclusion list to let it impact or being impacted by the glow layer.
  83642. * @param mesh The mesh to remove
  83643. */
  83644. GlowLayer.prototype.removeExcludedMesh = function (mesh) {
  83645. var index = this._excludedMeshes.indexOf(mesh.uniqueId);
  83646. if (index !== -1) {
  83647. this._excludedMeshes.splice(index, 1);
  83648. }
  83649. };
  83650. /**
  83651. * Add a mesh in the inclusion list to impact or being impacted by the glow layer.
  83652. * @param mesh The mesh to include in the glow layer
  83653. */
  83654. GlowLayer.prototype.addIncludedOnlyMesh = function (mesh) {
  83655. if (this._includedOnlyMeshes.indexOf(mesh.uniqueId) === -1) {
  83656. this._includedOnlyMeshes.push(mesh.uniqueId);
  83657. }
  83658. };
  83659. /**
  83660. * Remove a mesh from the Inclusion list to prevent it to impact or being impacted by the glow layer.
  83661. * @param mesh The mesh to remove
  83662. */
  83663. GlowLayer.prototype.removeIncludedOnlyMesh = function (mesh) {
  83664. var index = this._includedOnlyMeshes.indexOf(mesh.uniqueId);
  83665. if (index !== -1) {
  83666. this._includedOnlyMeshes.splice(index, 1);
  83667. }
  83668. };
  83669. /**
  83670. * Determine if a given mesh will be used in the glow layer
  83671. * @param mesh The mesh to test
  83672. * @returns true if the mesh will be highlighted by the current glow layer
  83673. */
  83674. GlowLayer.prototype.hasMesh = function (mesh) {
  83675. // Included Mesh
  83676. if (this._includedOnlyMeshes.length) {
  83677. return this._includedOnlyMeshes.indexOf(mesh.uniqueId) !== -1;
  83678. }
  83679. ;
  83680. // Excluded Mesh
  83681. if (this._excludedMeshes.length) {
  83682. return this._excludedMeshes.indexOf(mesh.uniqueId) === -1;
  83683. }
  83684. ;
  83685. return true;
  83686. };
  83687. /**
  83688. * Free any resources and references associated to a mesh.
  83689. * Internal use
  83690. * @param mesh The mesh to free.
  83691. */
  83692. GlowLayer.prototype._disposeMesh = function (mesh) {
  83693. this.removeIncludedOnlyMesh(mesh);
  83694. this.removeExcludedMesh(mesh);
  83695. };
  83696. /**
  83697. * Effect Name of the layer.
  83698. */
  83699. GlowLayer.EffectName = "GlowLayer";
  83700. /**
  83701. * The default blur kernel size used for the glow.
  83702. */
  83703. GlowLayer.DefaultBlurKernelSize = 32;
  83704. /**
  83705. * The default texture size ratio used for the glow.
  83706. */
  83707. GlowLayer.DefaultTextureRatio = 0.5;
  83708. return GlowLayer;
  83709. }(BABYLON.EffectLayer));
  83710. BABYLON.GlowLayer = GlowLayer;
  83711. })(BABYLON || (BABYLON = {}));
  83712. //# sourceMappingURL=babylon.glowLayer.js.map
  83713. var BABYLON;
  83714. (function (BABYLON) {
  83715. /**
  83716. * Defines the list of states available for a task inside a {BABYLON.AssetsManager}
  83717. */
  83718. var AssetTaskState;
  83719. (function (AssetTaskState) {
  83720. /**
  83721. * Initialization
  83722. */
  83723. AssetTaskState[AssetTaskState["INIT"] = 0] = "INIT";
  83724. /**
  83725. * Running
  83726. */
  83727. AssetTaskState[AssetTaskState["RUNNING"] = 1] = "RUNNING";
  83728. /**
  83729. * Done
  83730. */
  83731. AssetTaskState[AssetTaskState["DONE"] = 2] = "DONE";
  83732. /**
  83733. * Error
  83734. */
  83735. AssetTaskState[AssetTaskState["ERROR"] = 3] = "ERROR";
  83736. })(AssetTaskState = BABYLON.AssetTaskState || (BABYLON.AssetTaskState = {}));
  83737. /**
  83738. * Define an abstract asset task used with a {BABYLON.AssetsManager} class to load assets into a scene
  83739. */
  83740. var AbstractAssetTask = /** @class */ (function () {
  83741. /**
  83742. * Creates a new {BABYLON.AssetsManager}
  83743. * @param name defines the name of the task
  83744. */
  83745. function AbstractAssetTask(
  83746. /**
  83747. * Task name
  83748. */ name) {
  83749. this.name = name;
  83750. this._isCompleted = false;
  83751. this._taskState = AssetTaskState.INIT;
  83752. }
  83753. Object.defineProperty(AbstractAssetTask.prototype, "isCompleted", {
  83754. /**
  83755. * Get if the task is completed
  83756. */
  83757. get: function () {
  83758. return this._isCompleted;
  83759. },
  83760. enumerable: true,
  83761. configurable: true
  83762. });
  83763. Object.defineProperty(AbstractAssetTask.prototype, "taskState", {
  83764. /**
  83765. * Gets the current state of the task
  83766. */
  83767. get: function () {
  83768. return this._taskState;
  83769. },
  83770. enumerable: true,
  83771. configurable: true
  83772. });
  83773. Object.defineProperty(AbstractAssetTask.prototype, "errorObject", {
  83774. /**
  83775. * Gets the current error object (if task is in error)
  83776. */
  83777. get: function () {
  83778. return this._errorObject;
  83779. },
  83780. enumerable: true,
  83781. configurable: true
  83782. });
  83783. /**
  83784. * Internal only
  83785. * @ignore
  83786. */
  83787. AbstractAssetTask.prototype._setErrorObject = function (message, exception) {
  83788. if (this._errorObject) {
  83789. return;
  83790. }
  83791. this._errorObject = {
  83792. message: message,
  83793. exception: exception
  83794. };
  83795. };
  83796. /**
  83797. * Execute the current task
  83798. * @param scene defines the scene where you want your assets to be loaded
  83799. * @param onSuccess is a callback called when the task is successfully executed
  83800. * @param onError is a callback called if an error occurs
  83801. */
  83802. AbstractAssetTask.prototype.run = function (scene, onSuccess, onError) {
  83803. var _this = this;
  83804. this._taskState = AssetTaskState.RUNNING;
  83805. this.runTask(scene, function () {
  83806. _this.onDoneCallback(onSuccess, onError);
  83807. }, function (msg, exception) {
  83808. _this.onErrorCallback(onError, msg, exception);
  83809. });
  83810. };
  83811. /**
  83812. * Execute the current task
  83813. * @param scene defines the scene where you want your assets to be loaded
  83814. * @param onSuccess is a callback called when the task is successfully executed
  83815. * @param onError is a callback called if an error occurs
  83816. */
  83817. AbstractAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  83818. throw new Error("runTask is not implemented");
  83819. };
  83820. AbstractAssetTask.prototype.onErrorCallback = function (onError, message, exception) {
  83821. this._taskState = AssetTaskState.ERROR;
  83822. this._errorObject = {
  83823. message: message,
  83824. exception: exception
  83825. };
  83826. if (this.onError) {
  83827. this.onError(this, message, exception);
  83828. }
  83829. onError();
  83830. };
  83831. AbstractAssetTask.prototype.onDoneCallback = function (onSuccess, onError) {
  83832. try {
  83833. this._taskState = AssetTaskState.DONE;
  83834. this._isCompleted = true;
  83835. if (this.onSuccess) {
  83836. this.onSuccess(this);
  83837. }
  83838. onSuccess();
  83839. }
  83840. catch (e) {
  83841. this.onErrorCallback(onError, "Task is done, error executing success callback(s)", e);
  83842. }
  83843. };
  83844. return AbstractAssetTask;
  83845. }());
  83846. BABYLON.AbstractAssetTask = AbstractAssetTask;
  83847. /**
  83848. * Class used to share progress information about assets loading
  83849. */
  83850. var AssetsProgressEvent = /** @class */ (function () {
  83851. /**
  83852. * Creates a {BABYLON.AssetsProgressEvent}
  83853. * @param remainingCount defines the number of remaining tasks to process
  83854. * @param totalCount defines the total number of tasks
  83855. * @param task defines the task that was just processed
  83856. */
  83857. function AssetsProgressEvent(remainingCount, totalCount, task) {
  83858. this.remainingCount = remainingCount;
  83859. this.totalCount = totalCount;
  83860. this.task = task;
  83861. }
  83862. return AssetsProgressEvent;
  83863. }());
  83864. BABYLON.AssetsProgressEvent = AssetsProgressEvent;
  83865. /**
  83866. * Define a task used by {BABYLON.AssetsManager} to load meshes
  83867. */
  83868. var MeshAssetTask = /** @class */ (function (_super) {
  83869. __extends(MeshAssetTask, _super);
  83870. /**
  83871. * Creates a new {BABYLON.MeshAssetTask}
  83872. * @param name defines the name of the task
  83873. * @param meshesNames defines the list of mesh's names you want to load
  83874. * @param rootUrl defines the root url to use as a base to load your meshes and associated resources
  83875. * @param sceneFilename defines the filename of the scene to load from
  83876. */
  83877. function MeshAssetTask(
  83878. /**
  83879. * Defines the name of the task
  83880. */
  83881. name,
  83882. /**
  83883. * Defines the list of mesh's names you want to load
  83884. */
  83885. meshesNames,
  83886. /**
  83887. * Defines the root url to use as a base to load your meshes and associated resources
  83888. */
  83889. rootUrl,
  83890. /**
  83891. * Defines the filename of the scene to load from
  83892. */
  83893. sceneFilename) {
  83894. var _this = _super.call(this, name) || this;
  83895. _this.name = name;
  83896. _this.meshesNames = meshesNames;
  83897. _this.rootUrl = rootUrl;
  83898. _this.sceneFilename = sceneFilename;
  83899. return _this;
  83900. }
  83901. /**
  83902. * Execute the current task
  83903. * @param scene defines the scene where you want your assets to be loaded
  83904. * @param onSuccess is a callback called when the task is successfully executed
  83905. * @param onError is a callback called if an error occurs
  83906. */
  83907. MeshAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  83908. var _this = this;
  83909. BABYLON.SceneLoader.ImportMesh(this.meshesNames, this.rootUrl, this.sceneFilename, scene, function (meshes, particleSystems, skeletons) {
  83910. _this.loadedMeshes = meshes;
  83911. _this.loadedParticleSystems = particleSystems;
  83912. _this.loadedSkeletons = skeletons;
  83913. onSuccess();
  83914. }, null, function (scene, message, exception) {
  83915. onError(message, exception);
  83916. });
  83917. };
  83918. return MeshAssetTask;
  83919. }(AbstractAssetTask));
  83920. BABYLON.MeshAssetTask = MeshAssetTask;
  83921. /**
  83922. * Define a task used by {BABYLON.AssetsManager} to load text content
  83923. */
  83924. var TextFileAssetTask = /** @class */ (function (_super) {
  83925. __extends(TextFileAssetTask, _super);
  83926. /**
  83927. * Creates a new TextFileAssetTask object
  83928. * @param name defines the name of the task
  83929. * @param url defines the location of the file to load
  83930. */
  83931. function TextFileAssetTask(
  83932. /**
  83933. * Defines the name of the task
  83934. */
  83935. name,
  83936. /**
  83937. * Defines the location of the file to load
  83938. */
  83939. url) {
  83940. var _this = _super.call(this, name) || this;
  83941. _this.name = name;
  83942. _this.url = url;
  83943. return _this;
  83944. }
  83945. /**
  83946. * Execute the current task
  83947. * @param scene defines the scene where you want your assets to be loaded
  83948. * @param onSuccess is a callback called when the task is successfully executed
  83949. * @param onError is a callback called if an error occurs
  83950. */
  83951. TextFileAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  83952. var _this = this;
  83953. scene._loadFile(this.url, function (data) {
  83954. _this.text = data;
  83955. onSuccess();
  83956. }, undefined, false, false, function (request, exception) {
  83957. if (request) {
  83958. onError(request.status + " " + request.statusText, exception);
  83959. }
  83960. });
  83961. };
  83962. return TextFileAssetTask;
  83963. }(AbstractAssetTask));
  83964. BABYLON.TextFileAssetTask = TextFileAssetTask;
  83965. /**
  83966. * Define a task used by {BABYLON.AssetsManager} to load binary data
  83967. */
  83968. var BinaryFileAssetTask = /** @class */ (function (_super) {
  83969. __extends(BinaryFileAssetTask, _super);
  83970. /**
  83971. * Creates a new BinaryFileAssetTask object
  83972. * @param name defines the name of the new task
  83973. * @param url defines the location of the file to load
  83974. */
  83975. function BinaryFileAssetTask(
  83976. /**
  83977. * Defines the name of the task
  83978. */
  83979. name,
  83980. /**
  83981. * Defines the location of the file to load
  83982. */
  83983. url) {
  83984. var _this = _super.call(this, name) || this;
  83985. _this.name = name;
  83986. _this.url = url;
  83987. return _this;
  83988. }
  83989. /**
  83990. * Execute the current task
  83991. * @param scene defines the scene where you want your assets to be loaded
  83992. * @param onSuccess is a callback called when the task is successfully executed
  83993. * @param onError is a callback called if an error occurs
  83994. */
  83995. BinaryFileAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  83996. var _this = this;
  83997. scene._loadFile(this.url, function (data) {
  83998. _this.data = data;
  83999. onSuccess();
  84000. }, undefined, true, true, function (request, exception) {
  84001. if (request) {
  84002. onError(request.status + " " + request.statusText, exception);
  84003. }
  84004. });
  84005. };
  84006. return BinaryFileAssetTask;
  84007. }(AbstractAssetTask));
  84008. BABYLON.BinaryFileAssetTask = BinaryFileAssetTask;
  84009. /**
  84010. * Define a task used by {BABYLON.AssetsManager} to load images
  84011. */
  84012. var ImageAssetTask = /** @class */ (function (_super) {
  84013. __extends(ImageAssetTask, _super);
  84014. /**
  84015. * Creates a new ImageAssetTask
  84016. * @param name defines the name of the task
  84017. * @param url defines the location of the image to load
  84018. */
  84019. function ImageAssetTask(
  84020. /**
  84021. * Defines the name of the task
  84022. */
  84023. name,
  84024. /**
  84025. * Defines the location of the image to load
  84026. */
  84027. url) {
  84028. var _this = _super.call(this, name) || this;
  84029. _this.name = name;
  84030. _this.url = url;
  84031. return _this;
  84032. }
  84033. /**
  84034. * Execute the current task
  84035. * @param scene defines the scene where you want your assets to be loaded
  84036. * @param onSuccess is a callback called when the task is successfully executed
  84037. * @param onError is a callback called if an error occurs
  84038. */
  84039. ImageAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  84040. var _this = this;
  84041. var img = new Image();
  84042. BABYLON.Tools.SetCorsBehavior(this.url, img);
  84043. img.onload = function () {
  84044. _this.image = img;
  84045. onSuccess();
  84046. };
  84047. img.onerror = function (err) {
  84048. onError("Error loading image", err);
  84049. };
  84050. img.src = this.url;
  84051. };
  84052. return ImageAssetTask;
  84053. }(AbstractAssetTask));
  84054. BABYLON.ImageAssetTask = ImageAssetTask;
  84055. /**
  84056. * Define a task used by {BABYLON.AssetsManager} to load 2D textures
  84057. */
  84058. var TextureAssetTask = /** @class */ (function (_super) {
  84059. __extends(TextureAssetTask, _super);
  84060. /**
  84061. * Creates a new TextureAssetTask object
  84062. * @param name defines the name of the task
  84063. * @param url defines the location of the file to load
  84064. * @param noMipmap defines if mipmap should not be generated (default is false)
  84065. * @param invertY defines if texture must be inverted on Y axis (default is false)
  84066. * @param samplingMode defines the sampling mode to use (default is BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  84067. */
  84068. function TextureAssetTask(
  84069. /**
  84070. * Defines the name of the task
  84071. */
  84072. name,
  84073. /**
  84074. * Defines the location of the file to load
  84075. */
  84076. url,
  84077. /**
  84078. * Defines if mipmap should not be generated (default is false)
  84079. */
  84080. noMipmap,
  84081. /**
  84082. * Defines if texture must be inverted on Y axis (default is false)
  84083. */
  84084. invertY,
  84085. /**
  84086. * Defines the sampling mode to use (default is BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  84087. */
  84088. samplingMode) {
  84089. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  84090. var _this = _super.call(this, name) || this;
  84091. _this.name = name;
  84092. _this.url = url;
  84093. _this.noMipmap = noMipmap;
  84094. _this.invertY = invertY;
  84095. _this.samplingMode = samplingMode;
  84096. return _this;
  84097. }
  84098. /**
  84099. * Execute the current task
  84100. * @param scene defines the scene where you want your assets to be loaded
  84101. * @param onSuccess is a callback called when the task is successfully executed
  84102. * @param onError is a callback called if an error occurs
  84103. */
  84104. TextureAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  84105. var onload = function () {
  84106. onSuccess();
  84107. };
  84108. var onerror = function (message, exception) {
  84109. onError(message, exception);
  84110. };
  84111. this.texture = new BABYLON.Texture(this.url, scene, this.noMipmap, this.invertY, this.samplingMode, onload, onerror);
  84112. };
  84113. return TextureAssetTask;
  84114. }(AbstractAssetTask));
  84115. BABYLON.TextureAssetTask = TextureAssetTask;
  84116. /**
  84117. * Define a task used by {BABYLON.AssetsManager} to load cube textures
  84118. */
  84119. var CubeTextureAssetTask = /** @class */ (function (_super) {
  84120. __extends(CubeTextureAssetTask, _super);
  84121. /**
  84122. * Creates a new CubeTextureAssetTask
  84123. * @param name defines the name of the task
  84124. * @param url defines the location of the files to load (You have to specify the folder where the files are + filename with no extension)
  84125. * @param extensions defines the extensions to use to load files (["_px", "_py", "_pz", "_nx", "_ny", "_nz"] by default)
  84126. * @param noMipmap defines if mipmaps should not be generated (default is false)
  84127. * @param files defines the explicit list of files (undefined by default)
  84128. */
  84129. function CubeTextureAssetTask(
  84130. /**
  84131. * Defines the name of the task
  84132. */
  84133. name,
  84134. /**
  84135. * Defines the location of the files to load (You have to specify the folder where the files are + filename with no extension)
  84136. */
  84137. url,
  84138. /**
  84139. * Defines the extensions to use to load files (["_px", "_py", "_pz", "_nx", "_ny", "_nz"] by default)
  84140. */
  84141. extensions,
  84142. /**
  84143. * Defines if mipmaps should not be generated (default is false)
  84144. */
  84145. noMipmap,
  84146. /**
  84147. * Defines the explicit list of files (undefined by default)
  84148. */
  84149. files) {
  84150. var _this = _super.call(this, name) || this;
  84151. _this.name = name;
  84152. _this.url = url;
  84153. _this.extensions = extensions;
  84154. _this.noMipmap = noMipmap;
  84155. _this.files = files;
  84156. return _this;
  84157. }
  84158. /**
  84159. * Execute the current task
  84160. * @param scene defines the scene where you want your assets to be loaded
  84161. * @param onSuccess is a callback called when the task is successfully executed
  84162. * @param onError is a callback called if an error occurs
  84163. */
  84164. CubeTextureAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  84165. var onload = function () {
  84166. onSuccess();
  84167. };
  84168. var onerror = function (message, exception) {
  84169. onError(message, exception);
  84170. };
  84171. this.texture = new BABYLON.CubeTexture(this.url, scene, this.extensions, this.noMipmap, this.files, onload, onerror);
  84172. };
  84173. return CubeTextureAssetTask;
  84174. }(AbstractAssetTask));
  84175. BABYLON.CubeTextureAssetTask = CubeTextureAssetTask;
  84176. /**
  84177. * Define a task used by {BABYLON.AssetsManager} to load HDR cube textures
  84178. */
  84179. var HDRCubeTextureAssetTask = /** @class */ (function (_super) {
  84180. __extends(HDRCubeTextureAssetTask, _super);
  84181. /**
  84182. * Creates a new HDRCubeTextureAssetTask object
  84183. * @param name defines the name of the task
  84184. * @param url defines the location of the file to load
  84185. * @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.
  84186. * @param noMipmap defines if mipmaps should not be generated (default is false)
  84187. * @param generateHarmonics specifies whether you want to extract the polynomial harmonics during the generation process (default is true)
  84188. * @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)
  84189. * @param usePMREMGenerator specifies whether or not to generate the CubeMap through CubeMapGen to avoid seams issue at run time (default is false)
  84190. */
  84191. function HDRCubeTextureAssetTask(
  84192. /**
  84193. * Defines the name of the task
  84194. */
  84195. name,
  84196. /**
  84197. * Defines the location of the file to load
  84198. */
  84199. url,
  84200. /**
  84201. * 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.
  84202. */
  84203. size,
  84204. /**
  84205. * Defines if mipmaps should not be generated (default is false)
  84206. */
  84207. noMipmap,
  84208. /**
  84209. * Specifies whether you want to extract the polynomial harmonics during the generation process (default is true)
  84210. */
  84211. generateHarmonics,
  84212. /**
  84213. * 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)
  84214. */
  84215. useInGammaSpace,
  84216. /**
  84217. * Specifies whether or not to generate the CubeMap through CubeMapGen to avoid seams issue at run time (default is false)
  84218. */
  84219. usePMREMGenerator) {
  84220. if (noMipmap === void 0) { noMipmap = false; }
  84221. if (generateHarmonics === void 0) { generateHarmonics = true; }
  84222. if (useInGammaSpace === void 0) { useInGammaSpace = false; }
  84223. if (usePMREMGenerator === void 0) { usePMREMGenerator = false; }
  84224. var _this = _super.call(this, name) || this;
  84225. _this.name = name;
  84226. _this.url = url;
  84227. _this.size = size;
  84228. _this.noMipmap = noMipmap;
  84229. _this.generateHarmonics = generateHarmonics;
  84230. _this.useInGammaSpace = useInGammaSpace;
  84231. _this.usePMREMGenerator = usePMREMGenerator;
  84232. return _this;
  84233. }
  84234. /**
  84235. * Execute the current task
  84236. * @param scene defines the scene where you want your assets to be loaded
  84237. * @param onSuccess is a callback called when the task is successfully executed
  84238. * @param onError is a callback called if an error occurs
  84239. */
  84240. HDRCubeTextureAssetTask.prototype.run = function (scene, onSuccess, onError) {
  84241. var onload = function () {
  84242. onSuccess();
  84243. };
  84244. var onerror = function (message, exception) {
  84245. onError(message, exception);
  84246. };
  84247. this.texture = new BABYLON.HDRCubeTexture(this.url, scene, this.size, this.noMipmap, this.generateHarmonics, this.useInGammaSpace, this.usePMREMGenerator, onload, onerror);
  84248. };
  84249. return HDRCubeTextureAssetTask;
  84250. }(AbstractAssetTask));
  84251. BABYLON.HDRCubeTextureAssetTask = HDRCubeTextureAssetTask;
  84252. /**
  84253. * This class can be used to easily import assets into a scene
  84254. * @see http://doc.babylonjs.com/how_to/how_to_use_assetsmanager
  84255. */
  84256. var AssetsManager = /** @class */ (function () {
  84257. /**
  84258. * Creates a new AssetsManager
  84259. * @param scene defines the scene to work on
  84260. */
  84261. function AssetsManager(scene) {
  84262. this._isLoading = false;
  84263. this._tasks = new Array();
  84264. this._waitingTasksCount = 0;
  84265. this._totalTasksCount = 0;
  84266. /**
  84267. * Observable called when all tasks are processed
  84268. */
  84269. this.onTaskSuccessObservable = new BABYLON.Observable();
  84270. /**
  84271. * Observable called when a task had an error
  84272. */
  84273. this.onTaskErrorObservable = new BABYLON.Observable();
  84274. /**
  84275. * Observable called when a task is successful
  84276. */
  84277. this.onTasksDoneObservable = new BABYLON.Observable();
  84278. /**
  84279. * Observable called when a task is done (whatever the result is)
  84280. */
  84281. this.onProgressObservable = new BABYLON.Observable();
  84282. /**
  84283. * Gets or sets a boolean defining if the {BABYLON.AssetsManager} should use the default loading screen
  84284. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  84285. */
  84286. this.useDefaultLoadingScreen = true;
  84287. this._scene = scene;
  84288. }
  84289. /**
  84290. * Add a {BABYLON.MeshAssetTask} to the list of active tasks
  84291. * @param taskName defines the name of the new task
  84292. * @param meshesNames defines the name of meshes to load
  84293. * @param rootUrl defines the root url to use to locate files
  84294. * @param sceneFilename defines the filename of the scene file
  84295. * @returns a new {BABYLON.MeshAssetTask} object
  84296. */
  84297. AssetsManager.prototype.addMeshTask = function (taskName, meshesNames, rootUrl, sceneFilename) {
  84298. var task = new MeshAssetTask(taskName, meshesNames, rootUrl, sceneFilename);
  84299. this._tasks.push(task);
  84300. return task;
  84301. };
  84302. /**
  84303. * Add a {BABYLON.TextFileAssetTask} to the list of active tasks
  84304. * @param taskName defines the name of the new task
  84305. * @param url defines the url of the file to load
  84306. * @returns a new {BABYLON.TextFileAssetTask} object
  84307. */
  84308. AssetsManager.prototype.addTextFileTask = function (taskName, url) {
  84309. var task = new TextFileAssetTask(taskName, url);
  84310. this._tasks.push(task);
  84311. return task;
  84312. };
  84313. /**
  84314. * Add a {BABYLON.BinaryFileAssetTask} to the list of active tasks
  84315. * @param taskName defines the name of the new task
  84316. * @param url defines the url of the file to load
  84317. * @returns a new {BABYLON.BinaryFileAssetTask} object
  84318. */
  84319. AssetsManager.prototype.addBinaryFileTask = function (taskName, url) {
  84320. var task = new BinaryFileAssetTask(taskName, url);
  84321. this._tasks.push(task);
  84322. return task;
  84323. };
  84324. /**
  84325. * Add a {BABYLON.ImageAssetTask} to the list of active tasks
  84326. * @param taskName defines the name of the new task
  84327. * @param url defines the url of the file to load
  84328. * @returns a new {BABYLON.ImageAssetTask} object
  84329. */
  84330. AssetsManager.prototype.addImageTask = function (taskName, url) {
  84331. var task = new ImageAssetTask(taskName, url);
  84332. this._tasks.push(task);
  84333. return task;
  84334. };
  84335. /**
  84336. * Add a {BABYLON.TextureAssetTask} to the list of active tasks
  84337. * @param taskName defines the name of the new task
  84338. * @param url defines the url of the file to load
  84339. * @param noMipmap defines if the texture must not receive mipmaps (false by default)
  84340. * @param invertY defines if you want to invert Y axis of the loaded texture (false by default)
  84341. * @param samplingMode defines the sampling mode to use (BABYLON.Texture.TRILINEAR_SAMPLINGMODE by default)
  84342. * @returns a new {BABYLON.TextureAssetTask} object
  84343. */
  84344. AssetsManager.prototype.addTextureTask = function (taskName, url, noMipmap, invertY, samplingMode) {
  84345. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  84346. var task = new TextureAssetTask(taskName, url, noMipmap, invertY, samplingMode);
  84347. this._tasks.push(task);
  84348. return task;
  84349. };
  84350. /**
  84351. * Add a {BABYLON.CubeTextureAssetTask} to the list of active tasks
  84352. * @param taskName defines the name of the new task
  84353. * @param url defines the url of the file to load
  84354. * @param extensions defines the extension to use to load the cube map (can be null)
  84355. * @param noMipmap defines if the texture must not receive mipmaps (false by default)
  84356. * @param files defines the list of files to load (can be null)
  84357. * @returns a new {BABYLON.CubeTextureAssetTask} object
  84358. */
  84359. AssetsManager.prototype.addCubeTextureTask = function (taskName, url, extensions, noMipmap, files) {
  84360. var task = new CubeTextureAssetTask(taskName, url, extensions, noMipmap, files);
  84361. this._tasks.push(task);
  84362. return task;
  84363. };
  84364. /**
  84365. *
  84366. * Add a {BABYLON.HDRCubeTextureAssetTask} to the list of active tasks
  84367. * @param taskName defines the name of the new task
  84368. * @param url defines the url of the file to load
  84369. * @param size defines the size you want for the cubemap (can be null)
  84370. * @param noMipmap defines if the texture must not receive mipmaps (false by default)
  84371. * @param generateHarmonics defines if you want to automatically generate (true by default)
  84372. * @param useInGammaSpace defines if the texture must be considered in gamma space (false by default)
  84373. * @param usePMREMGenerator is a reserved parameter and must be set to false or ignored
  84374. * @returns a new {BABYLON.HDRCubeTextureAssetTask} object
  84375. */
  84376. AssetsManager.prototype.addHDRCubeTextureTask = function (taskName, url, size, noMipmap, generateHarmonics, useInGammaSpace, usePMREMGenerator) {
  84377. if (noMipmap === void 0) { noMipmap = false; }
  84378. if (generateHarmonics === void 0) { generateHarmonics = true; }
  84379. if (useInGammaSpace === void 0) { useInGammaSpace = false; }
  84380. if (usePMREMGenerator === void 0) { usePMREMGenerator = false; }
  84381. var task = new HDRCubeTextureAssetTask(taskName, url, size, noMipmap, generateHarmonics, useInGammaSpace, usePMREMGenerator);
  84382. this._tasks.push(task);
  84383. return task;
  84384. };
  84385. AssetsManager.prototype._decreaseWaitingTasksCount = function (task) {
  84386. var _this = this;
  84387. this._waitingTasksCount--;
  84388. try {
  84389. if (task.taskState === AssetTaskState.DONE) {
  84390. // Let's remove successfull tasks
  84391. BABYLON.Tools.SetImmediate(function () {
  84392. var index = _this._tasks.indexOf(task);
  84393. if (index > -1) {
  84394. _this._tasks.splice(index, 1);
  84395. }
  84396. });
  84397. }
  84398. if (this.onProgress) {
  84399. this.onProgress(this._waitingTasksCount, this._totalTasksCount, task);
  84400. }
  84401. this.onProgressObservable.notifyObservers(new AssetsProgressEvent(this._waitingTasksCount, this._totalTasksCount, task));
  84402. }
  84403. catch (e) {
  84404. BABYLON.Tools.Error("Error running progress callbacks.");
  84405. console.log(e);
  84406. }
  84407. if (this._waitingTasksCount === 0) {
  84408. try {
  84409. if (this.onFinish) {
  84410. this.onFinish(this._tasks);
  84411. }
  84412. this.onTasksDoneObservable.notifyObservers(this._tasks);
  84413. }
  84414. catch (e) {
  84415. BABYLON.Tools.Error("Error running tasks-done callbacks.");
  84416. console.log(e);
  84417. }
  84418. this._isLoading = false;
  84419. this._scene.getEngine().hideLoadingUI();
  84420. }
  84421. };
  84422. AssetsManager.prototype._runTask = function (task) {
  84423. var _this = this;
  84424. var done = function () {
  84425. try {
  84426. if (_this.onTaskSuccess) {
  84427. _this.onTaskSuccess(task);
  84428. }
  84429. _this.onTaskSuccessObservable.notifyObservers(task);
  84430. _this._decreaseWaitingTasksCount(task);
  84431. }
  84432. catch (e) {
  84433. error("Error executing task success callbacks", e);
  84434. }
  84435. };
  84436. var error = function (message, exception) {
  84437. task._setErrorObject(message, exception);
  84438. if (_this.onTaskError) {
  84439. _this.onTaskError(task);
  84440. }
  84441. _this.onTaskErrorObservable.notifyObservers(task);
  84442. _this._decreaseWaitingTasksCount(task);
  84443. };
  84444. task.run(this._scene, done, error);
  84445. };
  84446. /**
  84447. * Reset the {BABYLON.AssetsManager} and remove all tasks
  84448. * @return the current instance of the {BABYLON.AssetsManager}
  84449. */
  84450. AssetsManager.prototype.reset = function () {
  84451. this._isLoading = false;
  84452. this._tasks = new Array();
  84453. return this;
  84454. };
  84455. /**
  84456. * Start the loading process
  84457. * @return the current instance of the {BABYLON.AssetsManager}
  84458. */
  84459. AssetsManager.prototype.load = function () {
  84460. if (this._isLoading) {
  84461. return this;
  84462. }
  84463. this._isLoading = true;
  84464. this._waitingTasksCount = this._tasks.length;
  84465. this._totalTasksCount = this._tasks.length;
  84466. if (this._waitingTasksCount === 0) {
  84467. this._isLoading = false;
  84468. if (this.onFinish) {
  84469. this.onFinish(this._tasks);
  84470. }
  84471. this.onTasksDoneObservable.notifyObservers(this._tasks);
  84472. return this;
  84473. }
  84474. if (this.useDefaultLoadingScreen) {
  84475. this._scene.getEngine().displayLoadingUI();
  84476. }
  84477. for (var index = 0; index < this._tasks.length; index++) {
  84478. var task = this._tasks[index];
  84479. this._runTask(task);
  84480. }
  84481. return this;
  84482. };
  84483. return AssetsManager;
  84484. }());
  84485. BABYLON.AssetsManager = AssetsManager;
  84486. })(BABYLON || (BABYLON = {}));
  84487. //# sourceMappingURL=babylon.assetsManager.js.map
  84488. var BABYLON;
  84489. (function (BABYLON) {
  84490. var serializedGeometries = [];
  84491. var serializeGeometry = function (geometry, serializationGeometries) {
  84492. if (serializedGeometries[geometry.id]) {
  84493. return;
  84494. }
  84495. if (geometry.doNotSerialize) {
  84496. return;
  84497. }
  84498. if (geometry instanceof BABYLON.BoxGeometry) {
  84499. serializationGeometries.boxes.push(geometry.serialize());
  84500. }
  84501. else if (geometry instanceof BABYLON.SphereGeometry) {
  84502. serializationGeometries.spheres.push(geometry.serialize());
  84503. }
  84504. else if (geometry instanceof BABYLON.CylinderGeometry) {
  84505. serializationGeometries.cylinders.push(geometry.serialize());
  84506. }
  84507. else if (geometry instanceof BABYLON.TorusGeometry) {
  84508. serializationGeometries.toruses.push(geometry.serialize());
  84509. }
  84510. else if (geometry instanceof BABYLON.GroundGeometry) {
  84511. serializationGeometries.grounds.push(geometry.serialize());
  84512. }
  84513. else if (geometry instanceof BABYLON.Plane) {
  84514. serializationGeometries.planes.push(geometry.serialize());
  84515. }
  84516. else if (geometry instanceof BABYLON.TorusKnotGeometry) {
  84517. serializationGeometries.torusKnots.push(geometry.serialize());
  84518. }
  84519. else if (geometry instanceof BABYLON._PrimitiveGeometry) {
  84520. throw new Error("Unknown primitive type");
  84521. }
  84522. else {
  84523. serializationGeometries.vertexData.push(geometry.serializeVerticeData());
  84524. }
  84525. serializedGeometries[geometry.id] = true;
  84526. };
  84527. var serializeMesh = function (mesh, serializationScene) {
  84528. var serializationObject = {};
  84529. // Geometry
  84530. var geometry = mesh._geometry;
  84531. if (geometry) {
  84532. if (!mesh.getScene().getGeometryByID(geometry.id)) {
  84533. // 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
  84534. serializeGeometry(geometry, serializationScene.geometries);
  84535. }
  84536. }
  84537. // Custom
  84538. if (mesh.serialize) {
  84539. mesh.serialize(serializationObject);
  84540. }
  84541. return serializationObject;
  84542. };
  84543. var finalizeSingleMesh = function (mesh, serializationObject) {
  84544. //only works if the mesh is already loaded
  84545. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  84546. //serialize material
  84547. if (mesh.material) {
  84548. if (mesh.material instanceof BABYLON.StandardMaterial) {
  84549. serializationObject.materials = serializationObject.materials || [];
  84550. if (!serializationObject.materials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  84551. serializationObject.materials.push(mesh.material.serialize());
  84552. }
  84553. }
  84554. else if (mesh.material instanceof BABYLON.MultiMaterial) {
  84555. serializationObject.multiMaterials = serializationObject.multiMaterials || [];
  84556. if (!serializationObject.multiMaterials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  84557. serializationObject.multiMaterials.push(mesh.material.serialize());
  84558. }
  84559. }
  84560. }
  84561. //serialize geometry
  84562. var geometry = mesh._geometry;
  84563. if (geometry) {
  84564. if (!serializationObject.geometries) {
  84565. serializationObject.geometries = {};
  84566. serializationObject.geometries.boxes = [];
  84567. serializationObject.geometries.spheres = [];
  84568. serializationObject.geometries.cylinders = [];
  84569. serializationObject.geometries.toruses = [];
  84570. serializationObject.geometries.grounds = [];
  84571. serializationObject.geometries.planes = [];
  84572. serializationObject.geometries.torusKnots = [];
  84573. serializationObject.geometries.vertexData = [];
  84574. }
  84575. serializeGeometry(geometry, serializationObject.geometries);
  84576. }
  84577. // Skeletons
  84578. if (mesh.skeleton) {
  84579. serializationObject.skeletons = serializationObject.skeletons || [];
  84580. serializationObject.skeletons.push(mesh.skeleton.serialize());
  84581. }
  84582. //serialize the actual mesh
  84583. serializationObject.meshes = serializationObject.meshes || [];
  84584. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  84585. }
  84586. };
  84587. var SceneSerializer = /** @class */ (function () {
  84588. function SceneSerializer() {
  84589. }
  84590. SceneSerializer.ClearCache = function () {
  84591. serializedGeometries = [];
  84592. };
  84593. SceneSerializer.Serialize = function (scene) {
  84594. var serializationObject = {};
  84595. SceneSerializer.ClearCache();
  84596. // Scene
  84597. serializationObject.useDelayedTextureLoading = scene.useDelayedTextureLoading;
  84598. serializationObject.autoClear = scene.autoClear;
  84599. serializationObject.clearColor = scene.clearColor.asArray();
  84600. serializationObject.ambientColor = scene.ambientColor.asArray();
  84601. serializationObject.gravity = scene.gravity.asArray();
  84602. serializationObject.collisionsEnabled = scene.collisionsEnabled;
  84603. serializationObject.workerCollisions = scene.workerCollisions;
  84604. // Fog
  84605. if (scene.fogMode && scene.fogMode !== 0) {
  84606. serializationObject.fogMode = scene.fogMode;
  84607. serializationObject.fogColor = scene.fogColor.asArray();
  84608. serializationObject.fogStart = scene.fogStart;
  84609. serializationObject.fogEnd = scene.fogEnd;
  84610. serializationObject.fogDensity = scene.fogDensity;
  84611. }
  84612. //Physics
  84613. if (scene.isPhysicsEnabled()) {
  84614. var physicEngine = scene.getPhysicsEngine();
  84615. if (physicEngine) {
  84616. serializationObject.physicsEnabled = true;
  84617. serializationObject.physicsGravity = physicEngine.gravity.asArray();
  84618. serializationObject.physicsEngine = physicEngine.getPhysicsPluginName();
  84619. }
  84620. }
  84621. // Metadata
  84622. if (scene.metadata) {
  84623. serializationObject.metadata = scene.metadata;
  84624. }
  84625. // Morph targets
  84626. serializationObject.morphTargetManagers = [];
  84627. for (var _i = 0, _a = scene.meshes; _i < _a.length; _i++) {
  84628. var abstractMesh = _a[_i];
  84629. var manager = abstractMesh.morphTargetManager;
  84630. if (manager) {
  84631. serializationObject.morphTargetManagers.push(manager.serialize());
  84632. }
  84633. }
  84634. // Lights
  84635. serializationObject.lights = [];
  84636. var index;
  84637. var light;
  84638. for (index = 0; index < scene.lights.length; index++) {
  84639. light = scene.lights[index];
  84640. if (!light.doNotSerialize) {
  84641. serializationObject.lights.push(light.serialize());
  84642. }
  84643. }
  84644. // Cameras
  84645. serializationObject.cameras = [];
  84646. for (index = 0; index < scene.cameras.length; index++) {
  84647. var camera = scene.cameras[index];
  84648. if (!camera.doNotSerialize) {
  84649. serializationObject.cameras.push(camera.serialize());
  84650. }
  84651. }
  84652. if (scene.activeCamera) {
  84653. serializationObject.activeCameraID = scene.activeCamera.id;
  84654. }
  84655. // Animations
  84656. BABYLON.Animation.AppendSerializedAnimations(scene, serializationObject);
  84657. // Materials
  84658. serializationObject.materials = [];
  84659. serializationObject.multiMaterials = [];
  84660. var material;
  84661. for (index = 0; index < scene.materials.length; index++) {
  84662. material = scene.materials[index];
  84663. if (!material.doNotSerialize) {
  84664. serializationObject.materials.push(material.serialize());
  84665. }
  84666. }
  84667. // MultiMaterials
  84668. serializationObject.multiMaterials = [];
  84669. for (index = 0; index < scene.multiMaterials.length; index++) {
  84670. var multiMaterial = scene.multiMaterials[index];
  84671. serializationObject.multiMaterials.push(multiMaterial.serialize());
  84672. }
  84673. // Environment texture
  84674. if (scene.environmentTexture) {
  84675. serializationObject.environmentTexture = scene.environmentTexture.name;
  84676. }
  84677. // Skeletons
  84678. serializationObject.skeletons = [];
  84679. for (index = 0; index < scene.skeletons.length; index++) {
  84680. var skeleton = scene.skeletons[index];
  84681. if (!skeleton.doNotSerialize) {
  84682. serializationObject.skeletons.push(skeleton.serialize());
  84683. }
  84684. }
  84685. // Transform nodes
  84686. serializationObject.transformNodes = [];
  84687. for (index = 0; index < scene.transformNodes.length; index++) {
  84688. serializationObject.transformNodes.push(scene.transformNodes[index].serialize());
  84689. }
  84690. // Geometries
  84691. serializationObject.geometries = {};
  84692. serializationObject.geometries.boxes = [];
  84693. serializationObject.geometries.spheres = [];
  84694. serializationObject.geometries.cylinders = [];
  84695. serializationObject.geometries.toruses = [];
  84696. serializationObject.geometries.grounds = [];
  84697. serializationObject.geometries.planes = [];
  84698. serializationObject.geometries.torusKnots = [];
  84699. serializationObject.geometries.vertexData = [];
  84700. serializedGeometries = [];
  84701. var geometries = scene.getGeometries();
  84702. for (index = 0; index < geometries.length; index++) {
  84703. var geometry = geometries[index];
  84704. if (geometry.isReady()) {
  84705. serializeGeometry(geometry, serializationObject.geometries);
  84706. }
  84707. }
  84708. // Meshes
  84709. serializationObject.meshes = [];
  84710. for (index = 0; index < scene.meshes.length; index++) {
  84711. var abstractMesh = scene.meshes[index];
  84712. if (abstractMesh instanceof BABYLON.Mesh) {
  84713. var mesh = abstractMesh;
  84714. if (!mesh.doNotSerialize) {
  84715. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  84716. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  84717. }
  84718. }
  84719. }
  84720. }
  84721. // Particles Systems
  84722. serializationObject.particleSystems = [];
  84723. for (index = 0; index < scene.particleSystems.length; index++) {
  84724. serializationObject.particleSystems.push(scene.particleSystems[index].serialize());
  84725. }
  84726. // Lens flares
  84727. serializationObject.lensFlareSystems = [];
  84728. for (index = 0; index < scene.lensFlareSystems.length; index++) {
  84729. serializationObject.lensFlareSystems.push(scene.lensFlareSystems[index].serialize());
  84730. }
  84731. // Shadows
  84732. serializationObject.shadowGenerators = [];
  84733. for (index = 0; index < scene.lights.length; index++) {
  84734. light = scene.lights[index];
  84735. var shadowGenerator = light.getShadowGenerator();
  84736. if (shadowGenerator) {
  84737. serializationObject.shadowGenerators.push(shadowGenerator.serialize());
  84738. }
  84739. }
  84740. // Action Manager
  84741. if (scene.actionManager) {
  84742. serializationObject.actions = scene.actionManager.serialize("scene");
  84743. }
  84744. // Audio
  84745. serializationObject.sounds = [];
  84746. for (index = 0; index < scene.soundTracks.length; index++) {
  84747. var soundtrack = scene.soundTracks[index];
  84748. for (var soundId = 0; soundId < soundtrack.soundCollection.length; soundId++) {
  84749. serializationObject.sounds.push(soundtrack.soundCollection[soundId].serialize());
  84750. }
  84751. }
  84752. return serializationObject;
  84753. };
  84754. SceneSerializer.SerializeMesh = function (toSerialize /* Mesh || Mesh[] */, withParents, withChildren) {
  84755. if (withParents === void 0) { withParents = false; }
  84756. if (withChildren === void 0) { withChildren = false; }
  84757. var serializationObject = {};
  84758. SceneSerializer.ClearCache();
  84759. toSerialize = (toSerialize instanceof Array) ? toSerialize : [toSerialize];
  84760. if (withParents || withChildren) {
  84761. //deliberate for loop! not for each, appended should be processed as well.
  84762. for (var i = 0; i < toSerialize.length; ++i) {
  84763. if (withChildren) {
  84764. toSerialize[i].getDescendants().forEach(function (node) {
  84765. if (node instanceof BABYLON.Mesh && (toSerialize.indexOf(node) < 0)) {
  84766. toSerialize.push(node);
  84767. }
  84768. });
  84769. }
  84770. //make sure the array doesn't contain the object already
  84771. if (withParents && toSerialize[i].parent && (toSerialize.indexOf(toSerialize[i].parent) < 0)) {
  84772. toSerialize.push(toSerialize[i].parent);
  84773. }
  84774. }
  84775. }
  84776. toSerialize.forEach(function (mesh) {
  84777. finalizeSingleMesh(mesh, serializationObject);
  84778. });
  84779. return serializationObject;
  84780. };
  84781. return SceneSerializer;
  84782. }());
  84783. BABYLON.SceneSerializer = SceneSerializer;
  84784. })(BABYLON || (BABYLON = {}));
  84785. //# sourceMappingURL=babylon.sceneSerializer.js.map
  84786. var BABYLON;
  84787. (function (BABYLON) {
  84788. var ReflectionProbe = /** @class */ (function () {
  84789. function ReflectionProbe(name, size, scene, generateMipMaps) {
  84790. if (generateMipMaps === void 0) { generateMipMaps = true; }
  84791. var _this = this;
  84792. this.name = name;
  84793. this._viewMatrix = BABYLON.Matrix.Identity();
  84794. this._target = BABYLON.Vector3.Zero();
  84795. this._add = BABYLON.Vector3.Zero();
  84796. this.invertYAxis = false;
  84797. this.position = BABYLON.Vector3.Zero();
  84798. this._scene = scene;
  84799. this._scene.reflectionProbes.push(this);
  84800. this._renderTargetTexture = new BABYLON.RenderTargetTexture(name, size, scene, generateMipMaps, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, true);
  84801. this._renderTargetTexture.onBeforeRenderObservable.add(function (faceIndex) {
  84802. switch (faceIndex) {
  84803. case 0:
  84804. _this._add.copyFromFloats(1, 0, 0);
  84805. break;
  84806. case 1:
  84807. _this._add.copyFromFloats(-1, 0, 0);
  84808. break;
  84809. case 2:
  84810. _this._add.copyFromFloats(0, _this.invertYAxis ? 1 : -1, 0);
  84811. break;
  84812. case 3:
  84813. _this._add.copyFromFloats(0, _this.invertYAxis ? -1 : 1, 0);
  84814. break;
  84815. case 4:
  84816. _this._add.copyFromFloats(0, 0, 1);
  84817. break;
  84818. case 5:
  84819. _this._add.copyFromFloats(0, 0, -1);
  84820. break;
  84821. }
  84822. if (_this._attachedMesh) {
  84823. _this.position.copyFrom(_this._attachedMesh.getAbsolutePosition());
  84824. }
  84825. _this.position.addToRef(_this._add, _this._target);
  84826. BABYLON.Matrix.LookAtLHToRef(_this.position, _this._target, BABYLON.Vector3.Up(), _this._viewMatrix);
  84827. scene.setTransformMatrix(_this._viewMatrix, _this._projectionMatrix);
  84828. scene._forcedViewPosition = _this.position;
  84829. });
  84830. this._renderTargetTexture.onAfterUnbindObservable.add(function () {
  84831. scene._forcedViewPosition = null;
  84832. scene.updateTransformMatrix(true);
  84833. });
  84834. if (scene.activeCamera) {
  84835. this._projectionMatrix = BABYLON.Matrix.PerspectiveFovLH(Math.PI / 2, 1, scene.activeCamera.minZ, scene.activeCamera.maxZ);
  84836. }
  84837. }
  84838. Object.defineProperty(ReflectionProbe.prototype, "samples", {
  84839. get: function () {
  84840. return this._renderTargetTexture.samples;
  84841. },
  84842. set: function (value) {
  84843. this._renderTargetTexture.samples = value;
  84844. },
  84845. enumerable: true,
  84846. configurable: true
  84847. });
  84848. Object.defineProperty(ReflectionProbe.prototype, "refreshRate", {
  84849. get: function () {
  84850. return this._renderTargetTexture.refreshRate;
  84851. },
  84852. set: function (value) {
  84853. this._renderTargetTexture.refreshRate = value;
  84854. },
  84855. enumerable: true,
  84856. configurable: true
  84857. });
  84858. ReflectionProbe.prototype.getScene = function () {
  84859. return this._scene;
  84860. };
  84861. Object.defineProperty(ReflectionProbe.prototype, "cubeTexture", {
  84862. get: function () {
  84863. return this._renderTargetTexture;
  84864. },
  84865. enumerable: true,
  84866. configurable: true
  84867. });
  84868. Object.defineProperty(ReflectionProbe.prototype, "renderList", {
  84869. get: function () {
  84870. return this._renderTargetTexture.renderList;
  84871. },
  84872. enumerable: true,
  84873. configurable: true
  84874. });
  84875. ReflectionProbe.prototype.attachToMesh = function (mesh) {
  84876. this._attachedMesh = mesh;
  84877. };
  84878. /**
  84879. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  84880. *
  84881. * @param renderingGroupId The rendering group id corresponding to its index
  84882. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  84883. */
  84884. ReflectionProbe.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil) {
  84885. this._renderTargetTexture.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil);
  84886. };
  84887. ReflectionProbe.prototype.dispose = function () {
  84888. var index = this._scene.reflectionProbes.indexOf(this);
  84889. if (index !== -1) {
  84890. // Remove from the scene if found
  84891. this._scene.reflectionProbes.splice(index, 1);
  84892. }
  84893. if (this._renderTargetTexture) {
  84894. this._renderTargetTexture.dispose();
  84895. this._renderTargetTexture = null;
  84896. }
  84897. };
  84898. return ReflectionProbe;
  84899. }());
  84900. BABYLON.ReflectionProbe = ReflectionProbe;
  84901. })(BABYLON || (BABYLON = {}));
  84902. //# sourceMappingURL=babylon.reflectionProbe.js.map
  84903. var BABYLON;
  84904. (function (BABYLON) {
  84905. var Layer = /** @class */ (function () {
  84906. function Layer(name, imgUrl, scene, isBackground, color) {
  84907. this.name = name;
  84908. this.scale = new BABYLON.Vector2(1, 1);
  84909. this.offset = new BABYLON.Vector2(0, 0);
  84910. this.alphaBlendingMode = BABYLON.Engine.ALPHA_COMBINE;
  84911. this.layerMask = 0x0FFFFFFF;
  84912. this._vertexBuffers = {};
  84913. // Events
  84914. /**
  84915. * An event triggered when the layer is disposed.
  84916. * @type {BABYLON.Observable}
  84917. */
  84918. this.onDisposeObservable = new BABYLON.Observable();
  84919. /**
  84920. * An event triggered before rendering the scene
  84921. * @type {BABYLON.Observable}
  84922. */
  84923. this.onBeforeRenderObservable = new BABYLON.Observable();
  84924. /**
  84925. * An event triggered after rendering the scene
  84926. * @type {BABYLON.Observable}
  84927. */
  84928. this.onAfterRenderObservable = new BABYLON.Observable();
  84929. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, scene, true) : null;
  84930. this.isBackground = isBackground === undefined ? true : isBackground;
  84931. this.color = color === undefined ? new BABYLON.Color4(1, 1, 1, 1) : color;
  84932. this._scene = (scene || BABYLON.Engine.LastCreatedScene);
  84933. this._scene.layers.push(this);
  84934. var engine = this._scene.getEngine();
  84935. // VBO
  84936. var vertices = [];
  84937. vertices.push(1, 1);
  84938. vertices.push(-1, 1);
  84939. vertices.push(-1, -1);
  84940. vertices.push(1, -1);
  84941. var vertexBuffer = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  84942. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = vertexBuffer;
  84943. this._createIndexBuffer();
  84944. // Effects
  84945. this._effect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "");
  84946. this._alphaTestEffect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "#define ALPHATEST");
  84947. }
  84948. Object.defineProperty(Layer.prototype, "onDispose", {
  84949. set: function (callback) {
  84950. if (this._onDisposeObserver) {
  84951. this.onDisposeObservable.remove(this._onDisposeObserver);
  84952. }
  84953. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  84954. },
  84955. enumerable: true,
  84956. configurable: true
  84957. });
  84958. Object.defineProperty(Layer.prototype, "onBeforeRender", {
  84959. set: function (callback) {
  84960. if (this._onBeforeRenderObserver) {
  84961. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  84962. }
  84963. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  84964. },
  84965. enumerable: true,
  84966. configurable: true
  84967. });
  84968. Object.defineProperty(Layer.prototype, "onAfterRender", {
  84969. set: function (callback) {
  84970. if (this._onAfterRenderObserver) {
  84971. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  84972. }
  84973. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  84974. },
  84975. enumerable: true,
  84976. configurable: true
  84977. });
  84978. Layer.prototype._createIndexBuffer = function () {
  84979. var engine = this._scene.getEngine();
  84980. // Indices
  84981. var indices = [];
  84982. indices.push(0);
  84983. indices.push(1);
  84984. indices.push(2);
  84985. indices.push(0);
  84986. indices.push(2);
  84987. indices.push(3);
  84988. this._indexBuffer = engine.createIndexBuffer(indices);
  84989. };
  84990. Layer.prototype._rebuild = function () {
  84991. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  84992. if (vb) {
  84993. vb._rebuild();
  84994. }
  84995. this._createIndexBuffer();
  84996. };
  84997. Layer.prototype.render = function () {
  84998. var currentEffect = this.alphaTest ? this._alphaTestEffect : this._effect;
  84999. // Check
  85000. if (!currentEffect.isReady() || !this.texture || !this.texture.isReady())
  85001. return;
  85002. var engine = this._scene.getEngine();
  85003. this.onBeforeRenderObservable.notifyObservers(this);
  85004. // Render
  85005. engine.enableEffect(currentEffect);
  85006. engine.setState(false);
  85007. // Texture
  85008. currentEffect.setTexture("textureSampler", this.texture);
  85009. currentEffect.setMatrix("textureMatrix", this.texture.getTextureMatrix());
  85010. // Color
  85011. currentEffect.setFloat4("color", this.color.r, this.color.g, this.color.b, this.color.a);
  85012. // Scale / offset
  85013. currentEffect.setVector2("offset", this.offset);
  85014. currentEffect.setVector2("scale", this.scale);
  85015. // VBOs
  85016. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect);
  85017. // Draw order
  85018. if (!this.alphaTest) {
  85019. engine.setAlphaMode(this.alphaBlendingMode);
  85020. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  85021. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  85022. }
  85023. else {
  85024. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  85025. }
  85026. this.onAfterRenderObservable.notifyObservers(this);
  85027. };
  85028. Layer.prototype.dispose = function () {
  85029. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  85030. if (vertexBuffer) {
  85031. vertexBuffer.dispose();
  85032. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  85033. }
  85034. if (this._indexBuffer) {
  85035. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  85036. this._indexBuffer = null;
  85037. }
  85038. if (this.texture) {
  85039. this.texture.dispose();
  85040. this.texture = null;
  85041. }
  85042. // Remove from scene
  85043. var index = this._scene.layers.indexOf(this);
  85044. this._scene.layers.splice(index, 1);
  85045. // Callback
  85046. this.onDisposeObservable.notifyObservers(this);
  85047. this.onDisposeObservable.clear();
  85048. this.onAfterRenderObservable.clear();
  85049. this.onBeforeRenderObservable.clear();
  85050. };
  85051. return Layer;
  85052. }());
  85053. BABYLON.Layer = Layer;
  85054. })(BABYLON || (BABYLON = {}));
  85055. //# sourceMappingURL=babylon.layer.js.map
  85056. var BABYLON;
  85057. (function (BABYLON) {
  85058. var TextureTools = /** @class */ (function () {
  85059. function TextureTools() {
  85060. }
  85061. /**
  85062. * Uses the GPU to create a copy texture rescaled at a given size
  85063. * @param texture Texture to copy from
  85064. * @param width Desired width
  85065. * @param height Desired height
  85066. * @return Generated texture
  85067. */
  85068. TextureTools.CreateResizedCopy = function (texture, width, height, useBilinearMode) {
  85069. if (useBilinearMode === void 0) { useBilinearMode = true; }
  85070. var scene = texture.getScene();
  85071. var engine = scene.getEngine();
  85072. var rtt = new BABYLON.RenderTargetTexture('resized' + texture.name, { width: width, height: height }, scene, !texture.noMipmap, true, texture._texture.type, false, texture._samplingMode, false);
  85073. rtt.wrapU = texture.wrapU;
  85074. rtt.wrapV = texture.wrapV;
  85075. rtt.uOffset = texture.uOffset;
  85076. rtt.vOffset = texture.vOffset;
  85077. rtt.uScale = texture.uScale;
  85078. rtt.vScale = texture.vScale;
  85079. rtt.uAng = texture.uAng;
  85080. rtt.vAng = texture.vAng;
  85081. rtt.wAng = texture.wAng;
  85082. rtt.coordinatesIndex = texture.coordinatesIndex;
  85083. rtt.level = texture.level;
  85084. rtt.anisotropicFilteringLevel = texture.anisotropicFilteringLevel;
  85085. rtt._texture.isReady = false;
  85086. texture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  85087. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  85088. var passPostProcess = new BABYLON.PassPostProcess("pass", 1, null, useBilinearMode ? BABYLON.Texture.BILINEAR_SAMPLINGMODE : BABYLON.Texture.NEAREST_SAMPLINGMODE, engine, false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  85089. passPostProcess.getEffect().executeWhenCompiled(function () {
  85090. passPostProcess.onApply = function (effect) {
  85091. effect.setTexture("textureSampler", texture);
  85092. };
  85093. var internalTexture = rtt.getInternalTexture();
  85094. if (internalTexture) {
  85095. scene.postProcessManager.directRender([passPostProcess], internalTexture);
  85096. engine.unBindFramebuffer(internalTexture);
  85097. rtt.disposeFramebufferObjects();
  85098. passPostProcess.dispose();
  85099. internalTexture.isReady = true;
  85100. }
  85101. });
  85102. return rtt;
  85103. };
  85104. TextureTools.GetEnvironmentBRDFTexture = function (scene) {
  85105. if (!scene._environmentBRDFTexture) {
  85106. var texture = BABYLON.Texture.CreateFromBase64String(this._environmentBRDFBase64Texture, "EnvironmentBRDFTexture", scene, true, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  85107. texture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  85108. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  85109. scene._environmentBRDFTexture = texture;
  85110. }
  85111. return scene._environmentBRDFTexture;
  85112. };
  85113. 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=";
  85114. return TextureTools;
  85115. }());
  85116. BABYLON.TextureTools = TextureTools;
  85117. })(BABYLON || (BABYLON = {}));
  85118. //# sourceMappingURL=babylon.textureTools.js.map
  85119. var BABYLON;
  85120. (function (BABYLON) {
  85121. var FramingBehavior = /** @class */ (function () {
  85122. function FramingBehavior() {
  85123. this._mode = FramingBehavior.FitFrustumSidesMode;
  85124. this._radiusScale = 1.0;
  85125. this._positionScale = 0.5;
  85126. this._defaultElevation = 0.3;
  85127. this._elevationReturnTime = 1500;
  85128. this._elevationReturnWaitTime = 1000;
  85129. this._zoomStopsAnimation = false;
  85130. this._framingTime = 1500;
  85131. this._isPointerDown = false;
  85132. this._lastInteractionTime = -Infinity;
  85133. // Framing control
  85134. this._animatables = new Array();
  85135. this._betaIsAnimating = false;
  85136. }
  85137. Object.defineProperty(FramingBehavior.prototype, "name", {
  85138. get: function () {
  85139. return "Framing";
  85140. },
  85141. enumerable: true,
  85142. configurable: true
  85143. });
  85144. Object.defineProperty(FramingBehavior.prototype, "mode", {
  85145. /**
  85146. * Gets current mode used by the behavior.
  85147. */
  85148. get: function () {
  85149. return this._mode;
  85150. },
  85151. /**
  85152. * Sets the current mode used by the behavior
  85153. */
  85154. set: function (mode) {
  85155. this._mode = mode;
  85156. },
  85157. enumerable: true,
  85158. configurable: true
  85159. });
  85160. Object.defineProperty(FramingBehavior.prototype, "radiusScale", {
  85161. /**
  85162. * Gets the scale applied to the radius
  85163. */
  85164. get: function () {
  85165. return this._radiusScale;
  85166. },
  85167. /**
  85168. * Sets the scale applied to the radius (1 by default)
  85169. */
  85170. set: function (radius) {
  85171. this._radiusScale = radius;
  85172. },
  85173. enumerable: true,
  85174. configurable: true
  85175. });
  85176. Object.defineProperty(FramingBehavior.prototype, "positionScale", {
  85177. /**
  85178. * Gets the scale to apply on Y axis to position camera focus. 0.5 by default which means the center of the bounding box.
  85179. */
  85180. get: function () {
  85181. return this._positionScale;
  85182. },
  85183. /**
  85184. * Sets the scale to apply on Y axis to position camera focus. 0.5 by default which means the center of the bounding box.
  85185. */
  85186. set: function (scale) {
  85187. this._positionScale = scale;
  85188. },
  85189. enumerable: true,
  85190. configurable: true
  85191. });
  85192. Object.defineProperty(FramingBehavior.prototype, "defaultElevation", {
  85193. /**
  85194. * Gets the angle above/below the horizontal plane to return to when the return to default elevation idle
  85195. * behaviour is triggered, in radians.
  85196. */
  85197. get: function () {
  85198. return this._defaultElevation;
  85199. },
  85200. /**
  85201. * Sets the angle above/below the horizontal plane to return to when the return to default elevation idle
  85202. * behaviour is triggered, in radians.
  85203. */
  85204. set: function (elevation) {
  85205. this._defaultElevation = elevation;
  85206. },
  85207. enumerable: true,
  85208. configurable: true
  85209. });
  85210. Object.defineProperty(FramingBehavior.prototype, "elevationReturnTime", {
  85211. /**
  85212. * Gets the time (in milliseconds) taken to return to the default beta position.
  85213. * Negative value indicates camera should not return to default.
  85214. */
  85215. get: function () {
  85216. return this._elevationReturnTime;
  85217. },
  85218. /**
  85219. * Sets the time (in milliseconds) taken to return to the default beta position.
  85220. * Negative value indicates camera should not return to default.
  85221. */
  85222. set: function (speed) {
  85223. this._elevationReturnTime = speed;
  85224. },
  85225. enumerable: true,
  85226. configurable: true
  85227. });
  85228. Object.defineProperty(FramingBehavior.prototype, "elevationReturnWaitTime", {
  85229. /**
  85230. * Gets the delay (in milliseconds) taken before the camera returns to the default beta position.
  85231. */
  85232. get: function () {
  85233. return this._elevationReturnWaitTime;
  85234. },
  85235. /**
  85236. * Sets the delay (in milliseconds) taken before the camera returns to the default beta position.
  85237. */
  85238. set: function (time) {
  85239. this._elevationReturnWaitTime = time;
  85240. },
  85241. enumerable: true,
  85242. configurable: true
  85243. });
  85244. Object.defineProperty(FramingBehavior.prototype, "zoomStopsAnimation", {
  85245. /**
  85246. * Gets the flag that indicates if user zooming should stop animation.
  85247. */
  85248. get: function () {
  85249. return this._zoomStopsAnimation;
  85250. },
  85251. /**
  85252. * Sets the flag that indicates if user zooming should stop animation.
  85253. */
  85254. set: function (flag) {
  85255. this._zoomStopsAnimation = flag;
  85256. },
  85257. enumerable: true,
  85258. configurable: true
  85259. });
  85260. Object.defineProperty(FramingBehavior.prototype, "framingTime", {
  85261. /**
  85262. * Gets the transition time when framing the mesh, in milliseconds
  85263. */
  85264. get: function () {
  85265. return this._framingTime;
  85266. },
  85267. /**
  85268. * Sets the transition time when framing the mesh, in milliseconds
  85269. */
  85270. set: function (time) {
  85271. this._framingTime = time;
  85272. },
  85273. enumerable: true,
  85274. configurable: true
  85275. });
  85276. FramingBehavior.prototype.init = function () {
  85277. // Do notihng
  85278. };
  85279. FramingBehavior.prototype.attach = function (camera) {
  85280. var _this = this;
  85281. this._attachedCamera = camera;
  85282. var scene = this._attachedCamera.getScene();
  85283. FramingBehavior.EasingFunction.setEasingMode(FramingBehavior.EasingMode);
  85284. this._onPrePointerObservableObserver = scene.onPrePointerObservable.add(function (pointerInfoPre) {
  85285. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  85286. _this._isPointerDown = true;
  85287. return;
  85288. }
  85289. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERUP) {
  85290. _this._isPointerDown = false;
  85291. }
  85292. });
  85293. this._onMeshTargetChangedObserver = camera.onMeshTargetChangedObservable.add(function (mesh) {
  85294. if (mesh) {
  85295. _this.zoomOnMesh(mesh);
  85296. }
  85297. });
  85298. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  85299. // Stop the animation if there is user interaction and the animation should stop for this interaction
  85300. _this._applyUserInteraction();
  85301. // Maintain the camera above the ground. If the user pulls the camera beneath the ground plane, lift it
  85302. // back to the default position after a given timeout
  85303. _this._maintainCameraAboveGround();
  85304. });
  85305. };
  85306. FramingBehavior.prototype.detach = function () {
  85307. if (!this._attachedCamera) {
  85308. return;
  85309. }
  85310. var scene = this._attachedCamera.getScene();
  85311. if (this._onPrePointerObservableObserver) {
  85312. scene.onPrePointerObservable.remove(this._onPrePointerObservableObserver);
  85313. }
  85314. if (this._onAfterCheckInputsObserver) {
  85315. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  85316. }
  85317. if (this._onMeshTargetChangedObserver) {
  85318. this._attachedCamera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  85319. }
  85320. this._attachedCamera = null;
  85321. };
  85322. /**
  85323. * Targets the given mesh and updates zoom level accordingly.
  85324. * @param mesh The mesh to target.
  85325. * @param radius Optional. If a cached radius position already exists, overrides default.
  85326. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  85327. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  85328. * @param onAnimationEnd Callback triggered at the end of the framing animation
  85329. */
  85330. FramingBehavior.prototype.zoomOnMesh = function (mesh, focusOnOriginXZ, onAnimationEnd) {
  85331. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  85332. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  85333. mesh.computeWorldMatrix(true);
  85334. var boundingBox = mesh.getBoundingInfo().boundingBox;
  85335. this.zoomOnBoundingInfo(boundingBox.minimumWorld, boundingBox.maximumWorld, focusOnOriginXZ, onAnimationEnd);
  85336. };
  85337. /**
  85338. * Targets the given mesh with its children and updates zoom level accordingly.
  85339. * @param mesh The mesh to target.
  85340. * @param radius Optional. If a cached radius position already exists, overrides default.
  85341. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  85342. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  85343. * @param onAnimationEnd Callback triggered at the end of the framing animation
  85344. */
  85345. FramingBehavior.prototype.zoomOnMeshHierarchy = function (mesh, focusOnOriginXZ, onAnimationEnd) {
  85346. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  85347. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  85348. mesh.computeWorldMatrix(true);
  85349. var boundingBox = mesh.getHierarchyBoundingVectors(true);
  85350. this.zoomOnBoundingInfo(boundingBox.min, boundingBox.max, focusOnOriginXZ, onAnimationEnd);
  85351. };
  85352. /**
  85353. * Targets the given meshes with their children and updates zoom level accordingly.
  85354. * @param meshes The mesh to target.
  85355. * @param radius Optional. If a cached radius position already exists, overrides default.
  85356. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  85357. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  85358. * @param onAnimationEnd Callback triggered at the end of the framing animation
  85359. */
  85360. FramingBehavior.prototype.zoomOnMeshesHierarchy = function (meshes, focusOnOriginXZ, onAnimationEnd) {
  85361. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  85362. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  85363. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  85364. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  85365. for (var i = 0; i < meshes.length; i++) {
  85366. var boundingInfo = meshes[i].getHierarchyBoundingVectors(true);
  85367. BABYLON.Tools.CheckExtends(boundingInfo.min, min, max);
  85368. BABYLON.Tools.CheckExtends(boundingInfo.max, min, max);
  85369. }
  85370. this.zoomOnBoundingInfo(min, max, focusOnOriginXZ, onAnimationEnd);
  85371. };
  85372. /**
  85373. * Targets the given mesh and updates zoom level accordingly.
  85374. * @param mesh The mesh to target.
  85375. * @param radius Optional. If a cached radius position already exists, overrides default.
  85376. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  85377. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  85378. * @param onAnimationEnd Callback triggered at the end of the framing animation
  85379. */
  85380. FramingBehavior.prototype.zoomOnBoundingInfo = function (minimumWorld, maximumWorld, focusOnOriginXZ, onAnimationEnd) {
  85381. var _this = this;
  85382. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  85383. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  85384. var zoomTarget;
  85385. if (!this._attachedCamera) {
  85386. return;
  85387. }
  85388. // Find target by interpolating from bottom of bounding box in world-space to top via framingPositionY
  85389. var bottom = minimumWorld.y;
  85390. var top = maximumWorld.y;
  85391. var zoomTargetY = bottom + (top - bottom) * this._positionScale;
  85392. var radiusWorld = maximumWorld.subtract(minimumWorld).scale(0.5);
  85393. if (focusOnOriginXZ) {
  85394. zoomTarget = new BABYLON.Vector3(0, zoomTargetY, 0);
  85395. }
  85396. else {
  85397. var centerWorld = minimumWorld.add(radiusWorld);
  85398. zoomTarget = new BABYLON.Vector3(centerWorld.x, zoomTargetY, centerWorld.z);
  85399. }
  85400. if (!this._vectorTransition) {
  85401. this._vectorTransition = BABYLON.Animation.CreateAnimation("target", BABYLON.Animation.ANIMATIONTYPE_VECTOR3, 60, FramingBehavior.EasingFunction);
  85402. }
  85403. this._betaIsAnimating = true;
  85404. var animatable = BABYLON.Animation.TransitionTo("target", zoomTarget, this._attachedCamera, this._attachedCamera.getScene(), 60, this._vectorTransition, this._framingTime);
  85405. if (animatable) {
  85406. this._animatables.push(animatable);
  85407. }
  85408. // sets the radius and lower radius bounds
  85409. // Small delta ensures camera is not always at lower zoom limit.
  85410. var radius = 0;
  85411. if (this._mode === FramingBehavior.FitFrustumSidesMode) {
  85412. var position = this._calculateLowerRadiusFromModelBoundingSphere(minimumWorld, maximumWorld);
  85413. this._attachedCamera.lowerRadiusLimit = radiusWorld.length() + this._attachedCamera.minZ;
  85414. radius = position;
  85415. }
  85416. else if (this._mode === FramingBehavior.IgnoreBoundsSizeMode) {
  85417. radius = this._calculateLowerRadiusFromModelBoundingSphere(minimumWorld, maximumWorld);
  85418. if (this._attachedCamera.lowerRadiusLimit === null) {
  85419. this._attachedCamera.lowerRadiusLimit = this._attachedCamera.minZ;
  85420. }
  85421. }
  85422. // Set sensibilities
  85423. var extend = maximumWorld.subtract(minimumWorld).length();
  85424. this._attachedCamera.panningSensibility = 5000 / extend;
  85425. this._attachedCamera.wheelPrecision = 100 / radius;
  85426. // transition to new radius
  85427. if (!this._radiusTransition) {
  85428. this._radiusTransition = BABYLON.Animation.CreateAnimation("radius", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, FramingBehavior.EasingFunction);
  85429. }
  85430. animatable = BABYLON.Animation.TransitionTo("radius", radius, this._attachedCamera, this._attachedCamera.getScene(), 60, this._radiusTransition, this._framingTime, function () {
  85431. if (onAnimationEnd) {
  85432. onAnimationEnd();
  85433. }
  85434. if (_this._attachedCamera) {
  85435. _this._attachedCamera.storeState();
  85436. }
  85437. });
  85438. if (animatable) {
  85439. this._animatables.push(animatable);
  85440. }
  85441. };
  85442. /**
  85443. * Calculates the lowest radius for the camera based on the bounding box of the mesh.
  85444. * @param mesh The mesh on which to base the calculation. mesh boundingInfo used to estimate necessary
  85445. * frustum width.
  85446. * @return The minimum distance from the primary mesh's center point at which the camera must be kept in order
  85447. * to fully enclose the mesh in the viewing frustum.
  85448. */
  85449. FramingBehavior.prototype._calculateLowerRadiusFromModelBoundingSphere = function (minimumWorld, maximumWorld) {
  85450. var size = maximumWorld.subtract(minimumWorld);
  85451. var boxVectorGlobalDiagonal = size.length();
  85452. var frustumSlope = this._getFrustumSlope();
  85453. // Formula for setting distance
  85454. // (Good explanation: http://stackoverflow.com/questions/2866350/move-camera-to-fit-3d-scene)
  85455. var radiusWithoutFraming = boxVectorGlobalDiagonal * 0.5;
  85456. // Horizon distance
  85457. var radius = radiusWithoutFraming * this._radiusScale;
  85458. var distanceForHorizontalFrustum = radius * Math.sqrt(1.0 + 1.0 / (frustumSlope.x * frustumSlope.x));
  85459. var distanceForVerticalFrustum = radius * Math.sqrt(1.0 + 1.0 / (frustumSlope.y * frustumSlope.y));
  85460. var distance = Math.max(distanceForHorizontalFrustum, distanceForVerticalFrustum);
  85461. var camera = this._attachedCamera;
  85462. if (!camera) {
  85463. return 0;
  85464. }
  85465. if (camera.lowerRadiusLimit && this._mode === FramingBehavior.IgnoreBoundsSizeMode) {
  85466. // Don't exceed the requested limit
  85467. distance = distance < camera.lowerRadiusLimit ? camera.lowerRadiusLimit : distance;
  85468. }
  85469. // Don't exceed the upper radius limit
  85470. if (camera.upperRadiusLimit) {
  85471. distance = distance > camera.upperRadiusLimit ? camera.upperRadiusLimit : distance;
  85472. }
  85473. return distance;
  85474. };
  85475. /**
  85476. * Keeps the camera above the ground plane. If the user pulls the camera below the ground plane, the camera
  85477. * is automatically returned to its default position (expected to be above ground plane).
  85478. */
  85479. FramingBehavior.prototype._maintainCameraAboveGround = function () {
  85480. var _this = this;
  85481. if (this._elevationReturnTime < 0) {
  85482. return;
  85483. }
  85484. var timeSinceInteraction = BABYLON.Tools.Now - this._lastInteractionTime;
  85485. var defaultBeta = Math.PI * 0.5 - this._defaultElevation;
  85486. var limitBeta = Math.PI * 0.5;
  85487. // Bring the camera back up if below the ground plane
  85488. if (this._attachedCamera && !this._betaIsAnimating && this._attachedCamera.beta > limitBeta && timeSinceInteraction >= this._elevationReturnWaitTime) {
  85489. this._betaIsAnimating = true;
  85490. //Transition to new position
  85491. this.stopAllAnimations();
  85492. if (!this._betaTransition) {
  85493. this._betaTransition = BABYLON.Animation.CreateAnimation("beta", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, FramingBehavior.EasingFunction);
  85494. }
  85495. var animatabe = BABYLON.Animation.TransitionTo("beta", defaultBeta, this._attachedCamera, this._attachedCamera.getScene(), 60, this._betaTransition, this._elevationReturnTime, function () {
  85496. _this._clearAnimationLocks();
  85497. _this.stopAllAnimations();
  85498. });
  85499. if (animatabe) {
  85500. this._animatables.push(animatabe);
  85501. }
  85502. }
  85503. };
  85504. /**
  85505. * Returns the frustum slope based on the canvas ratio and camera FOV
  85506. * @returns The frustum slope represented as a Vector2 with X and Y slopes
  85507. */
  85508. FramingBehavior.prototype._getFrustumSlope = function () {
  85509. // Calculate the viewport ratio
  85510. // Aspect Ratio is Height/Width.
  85511. var camera = this._attachedCamera;
  85512. if (!camera) {
  85513. return BABYLON.Vector2.Zero();
  85514. }
  85515. var engine = camera.getScene().getEngine();
  85516. var aspectRatio = engine.getAspectRatio(camera);
  85517. // Camera FOV is the vertical field of view (top-bottom) in radians.
  85518. // Slope of the frustum top/bottom planes in view space, relative to the forward vector.
  85519. var frustumSlopeY = Math.tan(camera.fov / 2);
  85520. // Slope of the frustum left/right planes in view space, relative to the forward vector.
  85521. // Provides the amount that one side (e.g. left) of the frustum gets wider for every unit
  85522. // along the forward vector.
  85523. var frustumSlopeX = frustumSlopeY * aspectRatio;
  85524. return new BABYLON.Vector2(frustumSlopeX, frustumSlopeY);
  85525. };
  85526. /**
  85527. * Removes all animation locks. Allows new animations to be added to any of the arcCamera properties.
  85528. */
  85529. FramingBehavior.prototype._clearAnimationLocks = function () {
  85530. this._betaIsAnimating = false;
  85531. };
  85532. /**
  85533. * Applies any current user interaction to the camera. Takes into account maximum alpha rotation.
  85534. */
  85535. FramingBehavior.prototype._applyUserInteraction = function () {
  85536. if (this.isUserIsMoving) {
  85537. this._lastInteractionTime = BABYLON.Tools.Now;
  85538. this.stopAllAnimations();
  85539. this._clearAnimationLocks();
  85540. }
  85541. };
  85542. /**
  85543. * Stops and removes all animations that have been applied to the camera
  85544. */
  85545. FramingBehavior.prototype.stopAllAnimations = function () {
  85546. if (this._attachedCamera) {
  85547. this._attachedCamera.animations = [];
  85548. }
  85549. while (this._animatables.length) {
  85550. if (this._animatables[0]) {
  85551. this._animatables[0].onAnimationEnd = null;
  85552. this._animatables[0].stop();
  85553. }
  85554. this._animatables.shift();
  85555. }
  85556. };
  85557. Object.defineProperty(FramingBehavior.prototype, "isUserIsMoving", {
  85558. /**
  85559. * Gets a value indicating if the user is moving the camera
  85560. */
  85561. get: function () {
  85562. if (!this._attachedCamera) {
  85563. return false;
  85564. }
  85565. return this._attachedCamera.inertialAlphaOffset !== 0 ||
  85566. this._attachedCamera.inertialBetaOffset !== 0 ||
  85567. this._attachedCamera.inertialRadiusOffset !== 0 ||
  85568. this._attachedCamera.inertialPanningX !== 0 ||
  85569. this._attachedCamera.inertialPanningY !== 0 ||
  85570. this._isPointerDown;
  85571. },
  85572. enumerable: true,
  85573. configurable: true
  85574. });
  85575. /**
  85576. * The easing function used by animations
  85577. */
  85578. FramingBehavior.EasingFunction = new BABYLON.ExponentialEase();
  85579. /**
  85580. * The easing mode used by animations
  85581. */
  85582. FramingBehavior.EasingMode = BABYLON.EasingFunction.EASINGMODE_EASEINOUT;
  85583. // Statics
  85584. /**
  85585. * The camera can move all the way towards the mesh.
  85586. */
  85587. FramingBehavior.IgnoreBoundsSizeMode = 0;
  85588. /**
  85589. * The camera is not allowed to zoom closer to the mesh than the point at which the adjusted bounding sphere touches the frustum sides
  85590. */
  85591. FramingBehavior.FitFrustumSidesMode = 1;
  85592. return FramingBehavior;
  85593. }());
  85594. BABYLON.FramingBehavior = FramingBehavior;
  85595. })(BABYLON || (BABYLON = {}));
  85596. //# sourceMappingURL=babylon.framingBehavior.js.map
  85597. var BABYLON;
  85598. (function (BABYLON) {
  85599. /**
  85600. * Add a bouncing effect to an ArcRotateCamera when reaching a specified minimum and maximum radius
  85601. */
  85602. var BouncingBehavior = /** @class */ (function () {
  85603. function BouncingBehavior() {
  85604. /**
  85605. * The duration of the animation, in milliseconds
  85606. */
  85607. this.transitionDuration = 450;
  85608. /**
  85609. * Length of the distance animated by the transition when lower radius is reached
  85610. */
  85611. this.lowerRadiusTransitionRange = 2;
  85612. /**
  85613. * Length of the distance animated by the transition when upper radius is reached
  85614. */
  85615. this.upperRadiusTransitionRange = -2;
  85616. this._autoTransitionRange = false;
  85617. // Animations
  85618. this._radiusIsAnimating = false;
  85619. this._radiusBounceTransition = null;
  85620. this._animatables = new Array();
  85621. }
  85622. Object.defineProperty(BouncingBehavior.prototype, "name", {
  85623. get: function () {
  85624. return "Bouncing";
  85625. },
  85626. enumerable: true,
  85627. configurable: true
  85628. });
  85629. Object.defineProperty(BouncingBehavior.prototype, "autoTransitionRange", {
  85630. /**
  85631. * Gets a value indicating if the lowerRadiusTransitionRange and upperRadiusTransitionRange are defined automatically
  85632. */
  85633. get: function () {
  85634. return this._autoTransitionRange;
  85635. },
  85636. /**
  85637. * Sets a value indicating if the lowerRadiusTransitionRange and upperRadiusTransitionRange are defined automatically
  85638. * Transition ranges will be set to 5% of the bounding box diagonal in world space
  85639. */
  85640. set: function (value) {
  85641. var _this = this;
  85642. if (this._autoTransitionRange === value) {
  85643. return;
  85644. }
  85645. this._autoTransitionRange = value;
  85646. var camera = this._attachedCamera;
  85647. if (!camera) {
  85648. return;
  85649. }
  85650. if (value) {
  85651. this._onMeshTargetChangedObserver = camera.onMeshTargetChangedObservable.add(function (mesh) {
  85652. if (!mesh) {
  85653. return;
  85654. }
  85655. mesh.computeWorldMatrix(true);
  85656. var diagonal = mesh.getBoundingInfo().diagonalLength;
  85657. _this.lowerRadiusTransitionRange = diagonal * 0.05;
  85658. _this.upperRadiusTransitionRange = diagonal * 0.05;
  85659. });
  85660. }
  85661. else if (this._onMeshTargetChangedObserver) {
  85662. camera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  85663. }
  85664. },
  85665. enumerable: true,
  85666. configurable: true
  85667. });
  85668. BouncingBehavior.prototype.init = function () {
  85669. // Do notihng
  85670. };
  85671. BouncingBehavior.prototype.attach = function (camera) {
  85672. var _this = this;
  85673. this._attachedCamera = camera;
  85674. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  85675. if (!_this._attachedCamera) {
  85676. return;
  85677. }
  85678. // Add the bounce animation to the lower radius limit
  85679. if (_this._isRadiusAtLimit(_this._attachedCamera.lowerRadiusLimit)) {
  85680. _this._applyBoundRadiusAnimation(_this.lowerRadiusTransitionRange);
  85681. }
  85682. // Add the bounce animation to the upper radius limit
  85683. if (_this._isRadiusAtLimit(_this._attachedCamera.upperRadiusLimit)) {
  85684. _this._applyBoundRadiusAnimation(_this.upperRadiusTransitionRange);
  85685. }
  85686. });
  85687. };
  85688. BouncingBehavior.prototype.detach = function () {
  85689. if (!this._attachedCamera) {
  85690. return;
  85691. }
  85692. if (this._onAfterCheckInputsObserver) {
  85693. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  85694. }
  85695. if (this._onMeshTargetChangedObserver) {
  85696. this._attachedCamera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  85697. }
  85698. this._attachedCamera = null;
  85699. };
  85700. /**
  85701. * Checks if the camera radius is at the specified limit. Takes into account animation locks.
  85702. * @param radiusLimit The limit to check against.
  85703. * @return Bool to indicate if at limit.
  85704. */
  85705. BouncingBehavior.prototype._isRadiusAtLimit = function (radiusLimit) {
  85706. if (!this._attachedCamera) {
  85707. return false;
  85708. }
  85709. if (this._attachedCamera.radius === radiusLimit && !this._radiusIsAnimating) {
  85710. return true;
  85711. }
  85712. return false;
  85713. };
  85714. /**
  85715. * Applies an animation to the radius of the camera, extending by the radiusDelta.
  85716. * @param radiusDelta The delta by which to animate to. Can be negative.
  85717. */
  85718. BouncingBehavior.prototype._applyBoundRadiusAnimation = function (radiusDelta) {
  85719. var _this = this;
  85720. if (!this._attachedCamera) {
  85721. return;
  85722. }
  85723. if (!this._radiusBounceTransition) {
  85724. BouncingBehavior.EasingFunction.setEasingMode(BouncingBehavior.EasingMode);
  85725. this._radiusBounceTransition = BABYLON.Animation.CreateAnimation("radius", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, BouncingBehavior.EasingFunction);
  85726. }
  85727. // Prevent zoom until bounce has completed
  85728. this._cachedWheelPrecision = this._attachedCamera.wheelPrecision;
  85729. this._attachedCamera.wheelPrecision = Infinity;
  85730. this._attachedCamera.inertialRadiusOffset = 0;
  85731. // Animate to the radius limit
  85732. this.stopAllAnimations();
  85733. this._radiusIsAnimating = true;
  85734. var animatable = BABYLON.Animation.TransitionTo("radius", this._attachedCamera.radius + radiusDelta, this._attachedCamera, this._attachedCamera.getScene(), 60, this._radiusBounceTransition, this.transitionDuration, function () { return _this._clearAnimationLocks(); });
  85735. if (animatable) {
  85736. this._animatables.push(animatable);
  85737. }
  85738. };
  85739. /**
  85740. * Removes all animation locks. Allows new animations to be added to any of the camera properties.
  85741. */
  85742. BouncingBehavior.prototype._clearAnimationLocks = function () {
  85743. this._radiusIsAnimating = false;
  85744. if (this._attachedCamera) {
  85745. this._attachedCamera.wheelPrecision = this._cachedWheelPrecision;
  85746. }
  85747. };
  85748. /**
  85749. * Stops and removes all animations that have been applied to the camera
  85750. */
  85751. BouncingBehavior.prototype.stopAllAnimations = function () {
  85752. if (this._attachedCamera) {
  85753. this._attachedCamera.animations = [];
  85754. }
  85755. while (this._animatables.length) {
  85756. this._animatables[0].onAnimationEnd = null;
  85757. this._animatables[0].stop();
  85758. this._animatables.shift();
  85759. }
  85760. };
  85761. /**
  85762. * The easing function used by animations
  85763. */
  85764. BouncingBehavior.EasingFunction = new BABYLON.BackEase(0.3);
  85765. /**
  85766. * The easing mode used by animations
  85767. */
  85768. BouncingBehavior.EasingMode = BABYLON.EasingFunction.EASINGMODE_EASEOUT;
  85769. return BouncingBehavior;
  85770. }());
  85771. BABYLON.BouncingBehavior = BouncingBehavior;
  85772. })(BABYLON || (BABYLON = {}));
  85773. //# sourceMappingURL=babylon.bouncingBehavior.js.map
  85774. var BABYLON;
  85775. (function (BABYLON) {
  85776. var AutoRotationBehavior = /** @class */ (function () {
  85777. function AutoRotationBehavior() {
  85778. this._zoomStopsAnimation = false;
  85779. this._idleRotationSpeed = 0.05;
  85780. this._idleRotationWaitTime = 2000;
  85781. this._idleRotationSpinupTime = 2000;
  85782. this._isPointerDown = false;
  85783. this._lastFrameTime = null;
  85784. this._lastInteractionTime = -Infinity;
  85785. this._cameraRotationSpeed = 0;
  85786. this._lastFrameRadius = 0;
  85787. }
  85788. Object.defineProperty(AutoRotationBehavior.prototype, "name", {
  85789. get: function () {
  85790. return "AutoRotation";
  85791. },
  85792. enumerable: true,
  85793. configurable: true
  85794. });
  85795. Object.defineProperty(AutoRotationBehavior.prototype, "zoomStopsAnimation", {
  85796. /**
  85797. * Gets the flag that indicates if user zooming should stop animation.
  85798. */
  85799. get: function () {
  85800. return this._zoomStopsAnimation;
  85801. },
  85802. /**
  85803. * Sets the flag that indicates if user zooming should stop animation.
  85804. */
  85805. set: function (flag) {
  85806. this._zoomStopsAnimation = flag;
  85807. },
  85808. enumerable: true,
  85809. configurable: true
  85810. });
  85811. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationSpeed", {
  85812. /**
  85813. * Gets the default speed at which the camera rotates around the model.
  85814. */
  85815. get: function () {
  85816. return this._idleRotationSpeed;
  85817. },
  85818. /**
  85819. * Sets the default speed at which the camera rotates around the model.
  85820. */
  85821. set: function (speed) {
  85822. this._idleRotationSpeed = speed;
  85823. },
  85824. enumerable: true,
  85825. configurable: true
  85826. });
  85827. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationWaitTime", {
  85828. /**
  85829. * Gets the time (milliseconds) to wait after user interaction before the camera starts rotating.
  85830. */
  85831. get: function () {
  85832. return this._idleRotationWaitTime;
  85833. },
  85834. /**
  85835. * Sets the time (in milliseconds) to wait after user interaction before the camera starts rotating.
  85836. */
  85837. set: function (time) {
  85838. this._idleRotationWaitTime = time;
  85839. },
  85840. enumerable: true,
  85841. configurable: true
  85842. });
  85843. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationSpinupTime", {
  85844. /**
  85845. * Gets the time (milliseconds) to take to spin up to the full idle rotation speed.
  85846. */
  85847. get: function () {
  85848. return this._idleRotationSpinupTime;
  85849. },
  85850. /**
  85851. * Sets the time (milliseconds) to take to spin up to the full idle rotation speed.
  85852. */
  85853. set: function (time) {
  85854. this._idleRotationSpinupTime = time;
  85855. },
  85856. enumerable: true,
  85857. configurable: true
  85858. });
  85859. Object.defineProperty(AutoRotationBehavior.prototype, "rotationInProgress", {
  85860. /**
  85861. * Gets a value indicating if the camera is currently rotating because of this behavior
  85862. */
  85863. get: function () {
  85864. return Math.abs(this._cameraRotationSpeed) > 0;
  85865. },
  85866. enumerable: true,
  85867. configurable: true
  85868. });
  85869. AutoRotationBehavior.prototype.init = function () {
  85870. // Do notihng
  85871. };
  85872. AutoRotationBehavior.prototype.attach = function (camera) {
  85873. var _this = this;
  85874. this._attachedCamera = camera;
  85875. var scene = this._attachedCamera.getScene();
  85876. this._onPrePointerObservableObserver = scene.onPrePointerObservable.add(function (pointerInfoPre) {
  85877. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  85878. _this._isPointerDown = true;
  85879. return;
  85880. }
  85881. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERUP) {
  85882. _this._isPointerDown = false;
  85883. }
  85884. });
  85885. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  85886. var now = BABYLON.Tools.Now;
  85887. var dt = 0;
  85888. if (_this._lastFrameTime != null) {
  85889. dt = now - _this._lastFrameTime;
  85890. }
  85891. _this._lastFrameTime = now;
  85892. // Stop the animation if there is user interaction and the animation should stop for this interaction
  85893. _this._applyUserInteraction();
  85894. var timeToRotation = now - _this._lastInteractionTime - _this._idleRotationWaitTime;
  85895. var scale = Math.max(Math.min(timeToRotation / (_this._idleRotationSpinupTime), 1), 0);
  85896. _this._cameraRotationSpeed = _this._idleRotationSpeed * scale;
  85897. // Step camera rotation by rotation speed
  85898. if (_this._attachedCamera) {
  85899. _this._attachedCamera.alpha -= _this._cameraRotationSpeed * (dt / 1000);
  85900. }
  85901. });
  85902. };
  85903. AutoRotationBehavior.prototype.detach = function () {
  85904. if (!this._attachedCamera) {
  85905. return;
  85906. }
  85907. var scene = this._attachedCamera.getScene();
  85908. if (this._onPrePointerObservableObserver) {
  85909. scene.onPrePointerObservable.remove(this._onPrePointerObservableObserver);
  85910. }
  85911. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  85912. this._attachedCamera = null;
  85913. };
  85914. /**
  85915. * Returns true if user is scrolling.
  85916. * @return true if user is scrolling.
  85917. */
  85918. AutoRotationBehavior.prototype._userIsZooming = function () {
  85919. if (!this._attachedCamera) {
  85920. return false;
  85921. }
  85922. return this._attachedCamera.inertialRadiusOffset !== 0;
  85923. };
  85924. AutoRotationBehavior.prototype._shouldAnimationStopForInteraction = function () {
  85925. if (!this._attachedCamera) {
  85926. return false;
  85927. }
  85928. var zoomHasHitLimit = false;
  85929. if (this._lastFrameRadius === this._attachedCamera.radius && this._attachedCamera.inertialRadiusOffset !== 0) {
  85930. zoomHasHitLimit = true;
  85931. }
  85932. // Update the record of previous radius - works as an approx. indicator of hitting radius limits
  85933. this._lastFrameRadius = this._attachedCamera.radius;
  85934. return this._zoomStopsAnimation ? zoomHasHitLimit : this._userIsZooming();
  85935. };
  85936. /**
  85937. * Applies any current user interaction to the camera. Takes into account maximum alpha rotation.
  85938. */
  85939. AutoRotationBehavior.prototype._applyUserInteraction = function () {
  85940. if (this._userIsMoving() && !this._shouldAnimationStopForInteraction()) {
  85941. this._lastInteractionTime = BABYLON.Tools.Now;
  85942. }
  85943. };
  85944. // Tools
  85945. AutoRotationBehavior.prototype._userIsMoving = function () {
  85946. if (!this._attachedCamera) {
  85947. return false;
  85948. }
  85949. return this._attachedCamera.inertialAlphaOffset !== 0 ||
  85950. this._attachedCamera.inertialBetaOffset !== 0 ||
  85951. this._attachedCamera.inertialRadiusOffset !== 0 ||
  85952. this._attachedCamera.inertialPanningX !== 0 ||
  85953. this._attachedCamera.inertialPanningY !== 0 ||
  85954. this._isPointerDown;
  85955. };
  85956. return AutoRotationBehavior;
  85957. }());
  85958. BABYLON.AutoRotationBehavior = AutoRotationBehavior;
  85959. })(BABYLON || (BABYLON = {}));
  85960. //# sourceMappingURL=babylon.autoRotationBehavior.js.map
  85961. var BABYLON;
  85962. (function (BABYLON) {
  85963. /**
  85964. * This class can be used to get instrumentation data from a Babylon engine
  85965. */
  85966. var EngineInstrumentation = /** @class */ (function () {
  85967. function EngineInstrumentation(engine) {
  85968. this.engine = engine;
  85969. this._captureGPUFrameTime = false;
  85970. this._gpuFrameTime = new BABYLON.PerfCounter();
  85971. this._captureShaderCompilationTime = false;
  85972. this._shaderCompilationTime = new BABYLON.PerfCounter();
  85973. // Observers
  85974. this._onBeginFrameObserver = null;
  85975. this._onEndFrameObserver = null;
  85976. this._onBeforeShaderCompilationObserver = null;
  85977. this._onAfterShaderCompilationObserver = null;
  85978. }
  85979. Object.defineProperty(EngineInstrumentation.prototype, "gpuFrameTimeCounter", {
  85980. // Properties
  85981. /**
  85982. * Gets the perf counter used for GPU frame time
  85983. */
  85984. get: function () {
  85985. return this._gpuFrameTime;
  85986. },
  85987. enumerable: true,
  85988. configurable: true
  85989. });
  85990. Object.defineProperty(EngineInstrumentation.prototype, "captureGPUFrameTime", {
  85991. /**
  85992. * Gets the GPU frame time capture status
  85993. */
  85994. get: function () {
  85995. return this._captureGPUFrameTime;
  85996. },
  85997. /**
  85998. * Enable or disable the GPU frame time capture
  85999. */
  86000. set: function (value) {
  86001. var _this = this;
  86002. if (value === this._captureGPUFrameTime) {
  86003. return;
  86004. }
  86005. this._captureGPUFrameTime = value;
  86006. if (value) {
  86007. this._onBeginFrameObserver = this.engine.onBeginFrameObservable.add(function () {
  86008. if (!_this._gpuFrameTimeToken) {
  86009. _this._gpuFrameTimeToken = _this.engine.startTimeQuery();
  86010. }
  86011. });
  86012. this._onEndFrameObserver = this.engine.onEndFrameObservable.add(function () {
  86013. if (!_this._gpuFrameTimeToken) {
  86014. return;
  86015. }
  86016. var time = _this.engine.endTimeQuery(_this._gpuFrameTimeToken);
  86017. if (time > -1) {
  86018. _this._gpuFrameTimeToken = null;
  86019. _this._gpuFrameTime.fetchNewFrame();
  86020. _this._gpuFrameTime.addCount(time, true);
  86021. }
  86022. });
  86023. }
  86024. else {
  86025. this.engine.onBeginFrameObservable.remove(this._onBeginFrameObserver);
  86026. this._onBeginFrameObserver = null;
  86027. this.engine.onEndFrameObservable.remove(this._onEndFrameObserver);
  86028. this._onEndFrameObserver = null;
  86029. }
  86030. },
  86031. enumerable: true,
  86032. configurable: true
  86033. });
  86034. Object.defineProperty(EngineInstrumentation.prototype, "shaderCompilationTimeCounter", {
  86035. /**
  86036. * Gets the perf counter used for shader compilation time
  86037. */
  86038. get: function () {
  86039. return this._shaderCompilationTime;
  86040. },
  86041. enumerable: true,
  86042. configurable: true
  86043. });
  86044. Object.defineProperty(EngineInstrumentation.prototype, "captureShaderCompilationTime", {
  86045. /**
  86046. * Gets the shader compilation time capture status
  86047. */
  86048. get: function () {
  86049. return this._captureShaderCompilationTime;
  86050. },
  86051. /**
  86052. * Enable or disable the shader compilation time capture
  86053. */
  86054. set: function (value) {
  86055. var _this = this;
  86056. if (value === this._captureShaderCompilationTime) {
  86057. return;
  86058. }
  86059. this._captureShaderCompilationTime = value;
  86060. if (value) {
  86061. this._onBeforeShaderCompilationObserver = this.engine.onBeforeShaderCompilationObservable.add(function () {
  86062. _this._shaderCompilationTime.fetchNewFrame();
  86063. _this._shaderCompilationTime.beginMonitoring();
  86064. });
  86065. this._onAfterShaderCompilationObserver = this.engine.onAfterShaderCompilationObservable.add(function () {
  86066. _this._shaderCompilationTime.endMonitoring();
  86067. });
  86068. }
  86069. else {
  86070. this.engine.onBeforeShaderCompilationObservable.remove(this._onBeforeShaderCompilationObserver);
  86071. this._onBeforeShaderCompilationObserver = null;
  86072. this.engine.onAfterShaderCompilationObservable.remove(this._onAfterShaderCompilationObserver);
  86073. this._onAfterShaderCompilationObserver = null;
  86074. }
  86075. },
  86076. enumerable: true,
  86077. configurable: true
  86078. });
  86079. EngineInstrumentation.prototype.dispose = function () {
  86080. this.engine.onBeginFrameObservable.remove(this._onBeginFrameObserver);
  86081. this._onBeginFrameObserver = null;
  86082. this.engine.onEndFrameObservable.remove(this._onEndFrameObserver);
  86083. this._onEndFrameObserver = null;
  86084. this.engine.onBeforeShaderCompilationObservable.remove(this._onBeforeShaderCompilationObserver);
  86085. this._onBeforeShaderCompilationObserver = null;
  86086. this.engine.onAfterShaderCompilationObservable.remove(this._onAfterShaderCompilationObserver);
  86087. this._onAfterShaderCompilationObserver = null;
  86088. this.engine = null;
  86089. };
  86090. return EngineInstrumentation;
  86091. }());
  86092. BABYLON.EngineInstrumentation = EngineInstrumentation;
  86093. })(BABYLON || (BABYLON = {}));
  86094. //# sourceMappingURL=babylon.engineInstrumentation.js.map
  86095. var BABYLON;
  86096. (function (BABYLON) {
  86097. /**
  86098. * This class can be used to get instrumentation data from a Babylon engine
  86099. */
  86100. var SceneInstrumentation = /** @class */ (function () {
  86101. function SceneInstrumentation(scene) {
  86102. var _this = this;
  86103. this.scene = scene;
  86104. this._captureActiveMeshesEvaluationTime = false;
  86105. this._activeMeshesEvaluationTime = new BABYLON.PerfCounter();
  86106. this._captureRenderTargetsRenderTime = false;
  86107. this._renderTargetsRenderTime = new BABYLON.PerfCounter();
  86108. this._captureFrameTime = false;
  86109. this._frameTime = new BABYLON.PerfCounter();
  86110. this._captureRenderTime = false;
  86111. this._renderTime = new BABYLON.PerfCounter();
  86112. this._captureInterFrameTime = false;
  86113. this._interFrameTime = new BABYLON.PerfCounter();
  86114. this._captureParticlesRenderTime = false;
  86115. this._particlesRenderTime = new BABYLON.PerfCounter();
  86116. this._captureSpritesRenderTime = false;
  86117. this._spritesRenderTime = new BABYLON.PerfCounter();
  86118. this._capturePhysicsTime = false;
  86119. this._physicsTime = new BABYLON.PerfCounter();
  86120. this._captureAnimationsTime = false;
  86121. this._animationsTime = new BABYLON.PerfCounter();
  86122. // Observers
  86123. this._onBeforeActiveMeshesEvaluationObserver = null;
  86124. this._onAfterActiveMeshesEvaluationObserver = null;
  86125. this._onBeforeRenderTargetsRenderObserver = null;
  86126. this._onAfterRenderTargetsRenderObserver = null;
  86127. this._onAfterRenderObserver = null;
  86128. this._onBeforeDrawPhaseObserver = null;
  86129. this._onAfterDrawPhaseObserver = null;
  86130. this._onBeforeAnimationsObserver = null;
  86131. this._onBeforeParticlesRenderingObserver = null;
  86132. this._onAfterParticlesRenderingObserver = null;
  86133. this._onBeforeSpritesRenderingObserver = null;
  86134. this._onAfterSpritesRenderingObserver = null;
  86135. this._onBeforePhysicsObserver = null;
  86136. this._onAfterPhysicsObserver = null;
  86137. this._onAfterAnimationsObserver = null;
  86138. // Before render
  86139. this._onBeforeAnimationsObserver = scene.onBeforeAnimationsObservable.add(function () {
  86140. if (_this._captureActiveMeshesEvaluationTime) {
  86141. _this._activeMeshesEvaluationTime.fetchNewFrame();
  86142. }
  86143. if (_this._captureRenderTargetsRenderTime) {
  86144. _this._renderTargetsRenderTime.fetchNewFrame();
  86145. }
  86146. if (_this._captureFrameTime) {
  86147. BABYLON.Tools.StartPerformanceCounter("Scene rendering");
  86148. _this._frameTime.beginMonitoring();
  86149. }
  86150. if (_this._captureInterFrameTime) {
  86151. _this._interFrameTime.endMonitoring();
  86152. }
  86153. if (_this._captureParticlesRenderTime) {
  86154. _this._particlesRenderTime.fetchNewFrame();
  86155. }
  86156. if (_this._captureSpritesRenderTime) {
  86157. _this._spritesRenderTime.fetchNewFrame();
  86158. }
  86159. if (_this._captureAnimationsTime) {
  86160. _this._animationsTime.beginMonitoring();
  86161. }
  86162. _this.scene.getEngine()._drawCalls.fetchNewFrame();
  86163. _this.scene.getEngine()._textureCollisions.fetchNewFrame();
  86164. });
  86165. // After render
  86166. this._onAfterRenderObserver = scene.onAfterRenderObservable.add(function () {
  86167. if (_this._captureFrameTime) {
  86168. BABYLON.Tools.EndPerformanceCounter("Scene rendering");
  86169. _this._frameTime.endMonitoring();
  86170. }
  86171. if (_this._captureRenderTime) {
  86172. _this._renderTime.endMonitoring(false);
  86173. }
  86174. if (_this._captureInterFrameTime) {
  86175. _this._interFrameTime.beginMonitoring();
  86176. }
  86177. });
  86178. }
  86179. Object.defineProperty(SceneInstrumentation.prototype, "activeMeshesEvaluationTimeCounter", {
  86180. // Properties
  86181. /**
  86182. * Gets the perf counter used for active meshes evaluation time
  86183. */
  86184. get: function () {
  86185. return this._activeMeshesEvaluationTime;
  86186. },
  86187. enumerable: true,
  86188. configurable: true
  86189. });
  86190. Object.defineProperty(SceneInstrumentation.prototype, "captureActiveMeshesEvaluationTime", {
  86191. /**
  86192. * Gets the active meshes evaluation time capture status
  86193. */
  86194. get: function () {
  86195. return this._captureActiveMeshesEvaluationTime;
  86196. },
  86197. /**
  86198. * Enable or disable the active meshes evaluation time capture
  86199. */
  86200. set: function (value) {
  86201. var _this = this;
  86202. if (value === this._captureActiveMeshesEvaluationTime) {
  86203. return;
  86204. }
  86205. this._captureActiveMeshesEvaluationTime = value;
  86206. if (value) {
  86207. this._onBeforeActiveMeshesEvaluationObserver = this.scene.onBeforeActiveMeshesEvaluationObservable.add(function () {
  86208. BABYLON.Tools.StartPerformanceCounter("Active meshes evaluation");
  86209. _this._activeMeshesEvaluationTime.beginMonitoring();
  86210. });
  86211. this._onAfterActiveMeshesEvaluationObserver = this.scene.onAfterActiveMeshesEvaluationObservable.add(function () {
  86212. BABYLON.Tools.EndPerformanceCounter("Active meshes evaluation");
  86213. _this._activeMeshesEvaluationTime.endMonitoring();
  86214. });
  86215. }
  86216. else {
  86217. this.scene.onBeforeActiveMeshesEvaluationObservable.remove(this._onBeforeActiveMeshesEvaluationObserver);
  86218. this._onBeforeActiveMeshesEvaluationObserver = null;
  86219. this.scene.onAfterActiveMeshesEvaluationObservable.remove(this._onAfterActiveMeshesEvaluationObserver);
  86220. this._onAfterActiveMeshesEvaluationObserver = null;
  86221. }
  86222. },
  86223. enumerable: true,
  86224. configurable: true
  86225. });
  86226. Object.defineProperty(SceneInstrumentation.prototype, "renderTargetsRenderTimeCounter", {
  86227. /**
  86228. * Gets the perf counter used for render targets render time
  86229. */
  86230. get: function () {
  86231. return this._renderTargetsRenderTime;
  86232. },
  86233. enumerable: true,
  86234. configurable: true
  86235. });
  86236. Object.defineProperty(SceneInstrumentation.prototype, "captureRenderTargetsRenderTime", {
  86237. /**
  86238. * Gets the render targets render time capture status
  86239. */
  86240. get: function () {
  86241. return this._captureRenderTargetsRenderTime;
  86242. },
  86243. /**
  86244. * Enable or disable the render targets render time capture
  86245. */
  86246. set: function (value) {
  86247. var _this = this;
  86248. if (value === this._captureRenderTargetsRenderTime) {
  86249. return;
  86250. }
  86251. this._captureRenderTargetsRenderTime = value;
  86252. if (value) {
  86253. this._onBeforeRenderTargetsRenderObserver = this.scene.OnBeforeRenderTargetsRenderObservable.add(function () {
  86254. BABYLON.Tools.StartPerformanceCounter("Render targets rendering");
  86255. _this._renderTargetsRenderTime.beginMonitoring();
  86256. });
  86257. this._onAfterRenderTargetsRenderObserver = this.scene.OnAfterRenderTargetsRenderObservable.add(function () {
  86258. BABYLON.Tools.EndPerformanceCounter("Render targets rendering");
  86259. _this._renderTargetsRenderTime.endMonitoring(false);
  86260. });
  86261. }
  86262. else {
  86263. this.scene.OnBeforeRenderTargetsRenderObservable.remove(this._onBeforeRenderTargetsRenderObserver);
  86264. this._onBeforeRenderTargetsRenderObserver = null;
  86265. this.scene.OnAfterRenderTargetsRenderObservable.remove(this._onAfterRenderTargetsRenderObserver);
  86266. this._onAfterRenderTargetsRenderObserver = null;
  86267. }
  86268. },
  86269. enumerable: true,
  86270. configurable: true
  86271. });
  86272. Object.defineProperty(SceneInstrumentation.prototype, "particlesRenderTimeCounter", {
  86273. /**
  86274. * Gets the perf counter used for particles render time
  86275. */
  86276. get: function () {
  86277. return this._particlesRenderTime;
  86278. },
  86279. enumerable: true,
  86280. configurable: true
  86281. });
  86282. Object.defineProperty(SceneInstrumentation.prototype, "captureParticlesRenderTime", {
  86283. /**
  86284. * Gets the particles render time capture status
  86285. */
  86286. get: function () {
  86287. return this._captureParticlesRenderTime;
  86288. },
  86289. /**
  86290. * Enable or disable the particles render time capture
  86291. */
  86292. set: function (value) {
  86293. var _this = this;
  86294. if (value === this._captureParticlesRenderTime) {
  86295. return;
  86296. }
  86297. this._captureParticlesRenderTime = value;
  86298. if (value) {
  86299. this._onBeforeParticlesRenderingObserver = this.scene.onBeforeParticlesRenderingObservable.add(function () {
  86300. BABYLON.Tools.StartPerformanceCounter("Particles");
  86301. _this._particlesRenderTime.beginMonitoring();
  86302. });
  86303. this._onAfterParticlesRenderingObserver = this.scene.onAfterParticlesRenderingObservable.add(function () {
  86304. BABYLON.Tools.EndPerformanceCounter("Particles");
  86305. _this._particlesRenderTime.endMonitoring(false);
  86306. });
  86307. }
  86308. else {
  86309. this.scene.onBeforeParticlesRenderingObservable.remove(this._onBeforeParticlesRenderingObserver);
  86310. this._onBeforeParticlesRenderingObserver = null;
  86311. this.scene.onAfterParticlesRenderingObservable.remove(this._onAfterParticlesRenderingObserver);
  86312. this._onAfterParticlesRenderingObserver = null;
  86313. }
  86314. },
  86315. enumerable: true,
  86316. configurable: true
  86317. });
  86318. Object.defineProperty(SceneInstrumentation.prototype, "spritesRenderTimeCounter", {
  86319. /**
  86320. * Gets the perf counter used for sprites render time
  86321. */
  86322. get: function () {
  86323. return this._spritesRenderTime;
  86324. },
  86325. enumerable: true,
  86326. configurable: true
  86327. });
  86328. Object.defineProperty(SceneInstrumentation.prototype, "captureSpritesRenderTime", {
  86329. /**
  86330. * Gets the sprites render time capture status
  86331. */
  86332. get: function () {
  86333. return this._captureSpritesRenderTime;
  86334. },
  86335. /**
  86336. * Enable or disable the sprites render time capture
  86337. */
  86338. set: function (value) {
  86339. var _this = this;
  86340. if (value === this._captureSpritesRenderTime) {
  86341. return;
  86342. }
  86343. this._captureSpritesRenderTime = value;
  86344. if (value) {
  86345. this._onBeforeSpritesRenderingObserver = this.scene.onBeforeSpritesRenderingObservable.add(function () {
  86346. BABYLON.Tools.StartPerformanceCounter("Sprites");
  86347. _this._spritesRenderTime.beginMonitoring();
  86348. });
  86349. this._onAfterSpritesRenderingObserver = this.scene.onAfterSpritesRenderingObservable.add(function () {
  86350. BABYLON.Tools.EndPerformanceCounter("Sprites");
  86351. _this._spritesRenderTime.endMonitoring(false);
  86352. });
  86353. }
  86354. else {
  86355. this.scene.onBeforeSpritesRenderingObservable.remove(this._onBeforeSpritesRenderingObserver);
  86356. this._onBeforeSpritesRenderingObserver = null;
  86357. this.scene.onAfterSpritesRenderingObservable.remove(this._onAfterSpritesRenderingObserver);
  86358. this._onAfterSpritesRenderingObserver = null;
  86359. }
  86360. },
  86361. enumerable: true,
  86362. configurable: true
  86363. });
  86364. Object.defineProperty(SceneInstrumentation.prototype, "physicsTimeCounter", {
  86365. /**
  86366. * Gets the perf counter used for physics time
  86367. */
  86368. get: function () {
  86369. return this._physicsTime;
  86370. },
  86371. enumerable: true,
  86372. configurable: true
  86373. });
  86374. Object.defineProperty(SceneInstrumentation.prototype, "capturePhysicsTime", {
  86375. /**
  86376. * Gets the physics time capture status
  86377. */
  86378. get: function () {
  86379. return this._capturePhysicsTime;
  86380. },
  86381. /**
  86382. * Enable or disable the physics time capture
  86383. */
  86384. set: function (value) {
  86385. var _this = this;
  86386. if (value === this._capturePhysicsTime) {
  86387. return;
  86388. }
  86389. this._capturePhysicsTime = value;
  86390. if (value) {
  86391. this._onBeforePhysicsObserver = this.scene.onBeforePhysicsObservable.add(function () {
  86392. BABYLON.Tools.StartPerformanceCounter("Physics");
  86393. _this._physicsTime.beginMonitoring();
  86394. });
  86395. this._onAfterPhysicsObserver = this.scene.onAfterPhysicsObservable.add(function () {
  86396. BABYLON.Tools.EndPerformanceCounter("Physics");
  86397. _this._physicsTime.endMonitoring();
  86398. });
  86399. }
  86400. else {
  86401. this.scene.onBeforePhysicsObservable.remove(this._onBeforePhysicsObserver);
  86402. this._onBeforePhysicsObserver = null;
  86403. this.scene.onAfterPhysicsObservable.remove(this._onAfterPhysicsObserver);
  86404. this._onAfterPhysicsObserver = null;
  86405. }
  86406. },
  86407. enumerable: true,
  86408. configurable: true
  86409. });
  86410. Object.defineProperty(SceneInstrumentation.prototype, "animationsTimeCounter", {
  86411. /**
  86412. * Gets the perf counter used for animations time
  86413. */
  86414. get: function () {
  86415. return this._animationsTime;
  86416. },
  86417. enumerable: true,
  86418. configurable: true
  86419. });
  86420. Object.defineProperty(SceneInstrumentation.prototype, "captureAnimationsTime", {
  86421. /**
  86422. * Gets the animations time capture status
  86423. */
  86424. get: function () {
  86425. return this._captureAnimationsTime;
  86426. },
  86427. /**
  86428. * Enable or disable the animations time capture
  86429. */
  86430. set: function (value) {
  86431. var _this = this;
  86432. if (value === this._captureAnimationsTime) {
  86433. return;
  86434. }
  86435. this._captureAnimationsTime = value;
  86436. if (value) {
  86437. this._onAfterAnimationsObserver = this.scene.onAfterAnimationsObservable.add(function () {
  86438. _this._animationsTime.endMonitoring();
  86439. });
  86440. }
  86441. else {
  86442. this.scene.onAfterAnimationsObservable.remove(this._onAfterAnimationsObserver);
  86443. this._onAfterAnimationsObserver = null;
  86444. }
  86445. },
  86446. enumerable: true,
  86447. configurable: true
  86448. });
  86449. Object.defineProperty(SceneInstrumentation.prototype, "frameTimeCounter", {
  86450. /**
  86451. * Gets the perf counter used for frame time capture
  86452. */
  86453. get: function () {
  86454. return this._frameTime;
  86455. },
  86456. enumerable: true,
  86457. configurable: true
  86458. });
  86459. Object.defineProperty(SceneInstrumentation.prototype, "captureFrameTime", {
  86460. /**
  86461. * Gets the frame time capture status
  86462. */
  86463. get: function () {
  86464. return this._captureFrameTime;
  86465. },
  86466. /**
  86467. * Enable or disable the frame time capture
  86468. */
  86469. set: function (value) {
  86470. this._captureFrameTime = value;
  86471. },
  86472. enumerable: true,
  86473. configurable: true
  86474. });
  86475. Object.defineProperty(SceneInstrumentation.prototype, "interFrameTimeCounter", {
  86476. /**
  86477. * Gets the perf counter used for inter-frames time capture
  86478. */
  86479. get: function () {
  86480. return this._interFrameTime;
  86481. },
  86482. enumerable: true,
  86483. configurable: true
  86484. });
  86485. Object.defineProperty(SceneInstrumentation.prototype, "captureInterFrameTime", {
  86486. /**
  86487. * Gets the inter-frames time capture status
  86488. */
  86489. get: function () {
  86490. return this._captureInterFrameTime;
  86491. },
  86492. /**
  86493. * Enable or disable the inter-frames time capture
  86494. */
  86495. set: function (value) {
  86496. this._captureInterFrameTime = value;
  86497. },
  86498. enumerable: true,
  86499. configurable: true
  86500. });
  86501. Object.defineProperty(SceneInstrumentation.prototype, "renderTimeCounter", {
  86502. /**
  86503. * Gets the perf counter used for render time capture
  86504. */
  86505. get: function () {
  86506. return this._renderTime;
  86507. },
  86508. enumerable: true,
  86509. configurable: true
  86510. });
  86511. Object.defineProperty(SceneInstrumentation.prototype, "captureRenderTime", {
  86512. /**
  86513. * Gets the render time capture status
  86514. */
  86515. get: function () {
  86516. return this._captureRenderTime;
  86517. },
  86518. /**
  86519. * Enable or disable the render time capture
  86520. */
  86521. set: function (value) {
  86522. var _this = this;
  86523. if (value === this._captureRenderTime) {
  86524. return;
  86525. }
  86526. this._captureRenderTime = value;
  86527. if (value) {
  86528. this._onBeforeDrawPhaseObserver = this.scene.onBeforeDrawPhaseObservable.add(function () {
  86529. _this._renderTime.beginMonitoring();
  86530. BABYLON.Tools.StartPerformanceCounter("Main render");
  86531. });
  86532. this._onAfterDrawPhaseObserver = this.scene.onAfterDrawPhaseObservable.add(function () {
  86533. _this._renderTime.endMonitoring(false);
  86534. BABYLON.Tools.EndPerformanceCounter("Main render");
  86535. });
  86536. }
  86537. else {
  86538. this.scene.onBeforeDrawPhaseObservable.remove(this._onBeforeDrawPhaseObserver);
  86539. this._onBeforeDrawPhaseObserver = null;
  86540. this.scene.onAfterDrawPhaseObservable.remove(this._onAfterDrawPhaseObserver);
  86541. this._onAfterDrawPhaseObserver = null;
  86542. }
  86543. },
  86544. enumerable: true,
  86545. configurable: true
  86546. });
  86547. Object.defineProperty(SceneInstrumentation.prototype, "drawCallsCounter", {
  86548. /**
  86549. * Gets the perf counter used for draw calls
  86550. */
  86551. get: function () {
  86552. return this.scene.getEngine()._drawCalls;
  86553. },
  86554. enumerable: true,
  86555. configurable: true
  86556. });
  86557. Object.defineProperty(SceneInstrumentation.prototype, "textureCollisionsCounter", {
  86558. /**
  86559. * Gets the perf counter used for texture collisions
  86560. */
  86561. get: function () {
  86562. return this.scene.getEngine()._textureCollisions;
  86563. },
  86564. enumerable: true,
  86565. configurable: true
  86566. });
  86567. SceneInstrumentation.prototype.dispose = function () {
  86568. this.scene.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  86569. this._onAfterRenderObserver = null;
  86570. this.scene.onBeforeActiveMeshesEvaluationObservable.remove(this._onBeforeActiveMeshesEvaluationObserver);
  86571. this._onBeforeActiveMeshesEvaluationObserver = null;
  86572. this.scene.onAfterActiveMeshesEvaluationObservable.remove(this._onAfterActiveMeshesEvaluationObserver);
  86573. this._onAfterActiveMeshesEvaluationObserver = null;
  86574. this.scene.OnBeforeRenderTargetsRenderObservable.remove(this._onBeforeRenderTargetsRenderObserver);
  86575. this._onBeforeRenderTargetsRenderObserver = null;
  86576. this.scene.OnAfterRenderTargetsRenderObservable.remove(this._onAfterRenderTargetsRenderObserver);
  86577. this._onAfterRenderTargetsRenderObserver = null;
  86578. this.scene.onBeforeAnimationsObservable.remove(this._onBeforeAnimationsObserver);
  86579. this._onBeforeAnimationsObserver = null;
  86580. this.scene.onBeforeParticlesRenderingObservable.remove(this._onBeforeParticlesRenderingObserver);
  86581. this._onBeforeParticlesRenderingObserver = null;
  86582. this.scene.onAfterParticlesRenderingObservable.remove(this._onAfterParticlesRenderingObserver);
  86583. this._onAfterParticlesRenderingObserver = null;
  86584. this.scene.onBeforeSpritesRenderingObservable.remove(this._onBeforeSpritesRenderingObserver);
  86585. this._onBeforeSpritesRenderingObserver = null;
  86586. this.scene.onAfterSpritesRenderingObservable.remove(this._onAfterSpritesRenderingObserver);
  86587. this._onAfterSpritesRenderingObserver = null;
  86588. this.scene.onBeforeDrawPhaseObservable.remove(this._onBeforeDrawPhaseObserver);
  86589. this._onBeforeDrawPhaseObserver = null;
  86590. this.scene.onAfterDrawPhaseObservable.remove(this._onAfterDrawPhaseObserver);
  86591. this._onAfterDrawPhaseObserver = null;
  86592. this.scene.onBeforePhysicsObservable.remove(this._onBeforePhysicsObserver);
  86593. this._onBeforePhysicsObserver = null;
  86594. this.scene.onAfterPhysicsObservable.remove(this._onAfterPhysicsObserver);
  86595. this._onAfterPhysicsObserver = null;
  86596. this.scene.onAfterAnimationsObservable.remove(this._onAfterAnimationsObserver);
  86597. this._onAfterAnimationsObserver = null;
  86598. this.scene = null;
  86599. };
  86600. return SceneInstrumentation;
  86601. }());
  86602. BABYLON.SceneInstrumentation = SceneInstrumentation;
  86603. })(BABYLON || (BABYLON = {}));
  86604. //# sourceMappingURL=babylon.sceneInstrumentation.js.map
  86605. var BABYLON;
  86606. (function (BABYLON) {
  86607. var _TimeToken = /** @class */ (function () {
  86608. function _TimeToken() {
  86609. this._timeElapsedQueryEnded = false;
  86610. }
  86611. return _TimeToken;
  86612. }());
  86613. BABYLON._TimeToken = _TimeToken;
  86614. })(BABYLON || (BABYLON = {}));
  86615. //# sourceMappingURL=babylon.timeToken.js.map
  86616. var BABYLON;
  86617. (function (BABYLON) {
  86618. /**
  86619. * Background material defines definition.
  86620. * @ignore Mainly internal Use
  86621. */
  86622. var BackgroundMaterialDefines = /** @class */ (function (_super) {
  86623. __extends(BackgroundMaterialDefines, _super);
  86624. /**
  86625. * Constructor of the defines.
  86626. */
  86627. function BackgroundMaterialDefines() {
  86628. var _this = _super.call(this) || this;
  86629. /**
  86630. * True if the diffuse texture is in use.
  86631. */
  86632. _this.DIFFUSE = false;
  86633. /**
  86634. * The direct UV channel to use.
  86635. */
  86636. _this.DIFFUSEDIRECTUV = 0;
  86637. /**
  86638. * True if the diffuse texture is in gamma space.
  86639. */
  86640. _this.GAMMADIFFUSE = false;
  86641. /**
  86642. * True if the diffuse texture has opacity in the alpha channel.
  86643. */
  86644. _this.DIFFUSEHASALPHA = false;
  86645. /**
  86646. * True if you want the material to fade to transparent at grazing angle.
  86647. */
  86648. _this.OPACITYFRESNEL = false;
  86649. /**
  86650. * True if an extra blur needs to be added in the reflection.
  86651. */
  86652. _this.REFLECTIONBLUR = false;
  86653. /**
  86654. * True if you want the material to fade to reflection at grazing angle.
  86655. */
  86656. _this.REFLECTIONFRESNEL = false;
  86657. /**
  86658. * True if you want the material to falloff as far as you move away from the scene center.
  86659. */
  86660. _this.REFLECTIONFALLOFF = false;
  86661. /**
  86662. * False if the current Webgl implementation does not support the texture lod extension.
  86663. */
  86664. _this.TEXTURELODSUPPORT = false;
  86665. /**
  86666. * True to ensure the data are premultiplied.
  86667. */
  86668. _this.PREMULTIPLYALPHA = false;
  86669. /**
  86670. * True if the texture contains cooked RGB values and not gray scaled multipliers.
  86671. */
  86672. _this.USERGBCOLOR = false;
  86673. /**
  86674. * True to add noise in order to reduce the banding effect.
  86675. */
  86676. _this.NOISE = false;
  86677. // Image Processing Configuration.
  86678. _this.IMAGEPROCESSING = false;
  86679. _this.VIGNETTE = false;
  86680. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  86681. _this.VIGNETTEBLENDMODEOPAQUE = false;
  86682. _this.TONEMAPPING = false;
  86683. _this.CONTRAST = false;
  86684. _this.COLORCURVES = false;
  86685. _this.COLORGRADING = false;
  86686. _this.COLORGRADING3D = false;
  86687. _this.SAMPLER3DGREENDEPTH = false;
  86688. _this.SAMPLER3DBGRMAP = false;
  86689. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  86690. _this.EXPOSURE = false;
  86691. // Reflection.
  86692. _this.REFLECTION = false;
  86693. _this.REFLECTIONMAP_3D = false;
  86694. _this.REFLECTIONMAP_SPHERICAL = false;
  86695. _this.REFLECTIONMAP_PLANAR = false;
  86696. _this.REFLECTIONMAP_CUBIC = false;
  86697. _this.REFLECTIONMAP_PROJECTION = false;
  86698. _this.REFLECTIONMAP_SKYBOX = false;
  86699. _this.REFLECTIONMAP_EXPLICIT = false;
  86700. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  86701. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  86702. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  86703. _this.INVERTCUBICMAP = false;
  86704. _this.REFLECTIONMAP_OPPOSITEZ = false;
  86705. _this.LODINREFLECTIONALPHA = false;
  86706. _this.GAMMAREFLECTION = false;
  86707. _this.EQUIRECTANGULAR_RELFECTION_FOV = false;
  86708. // Default BJS.
  86709. _this.MAINUV1 = false;
  86710. _this.MAINUV2 = false;
  86711. _this.UV1 = false;
  86712. _this.UV2 = false;
  86713. _this.CLIPPLANE = false;
  86714. _this.POINTSIZE = false;
  86715. _this.FOG = false;
  86716. _this.NORMAL = false;
  86717. _this.NUM_BONE_INFLUENCERS = 0;
  86718. _this.BonesPerMesh = 0;
  86719. _this.INSTANCES = false;
  86720. _this.SHADOWFLOAT = false;
  86721. _this.rebuild();
  86722. return _this;
  86723. }
  86724. return BackgroundMaterialDefines;
  86725. }(BABYLON.MaterialDefines));
  86726. /**
  86727. * Background material used to create an efficient environement around your scene.
  86728. */
  86729. var BackgroundMaterial = /** @class */ (function (_super) {
  86730. __extends(BackgroundMaterial, _super);
  86731. /**
  86732. * Instantiates a Background Material in the given scene
  86733. * @param name The friendly name of the material
  86734. * @param scene The scene to add the material to
  86735. */
  86736. function BackgroundMaterial(name, scene) {
  86737. var _this = _super.call(this, name, scene) || this;
  86738. /**
  86739. * Key light Color (multiply against the R channel of the environement texture)
  86740. */
  86741. _this.primaryColor = BABYLON.Color3.White();
  86742. /**
  86743. * Key light Level (allowing HDR output of the background)
  86744. */
  86745. _this.primaryLevel = 1;
  86746. /**
  86747. * Secondary light Color (multiply against the G channel of the environement texture)
  86748. */
  86749. _this.secondaryColor = BABYLON.Color3.Gray();
  86750. /**
  86751. * Secondary light Level (allowing HDR output of the background)
  86752. */
  86753. _this.secondaryLevel = 1;
  86754. /**
  86755. * Tertiary light Color (multiply against the B channel of the environement texture)
  86756. */
  86757. _this.tertiaryColor = BABYLON.Color3.Black();
  86758. /**
  86759. * Tertiary light Level (allowing HDR output of the background)
  86760. */
  86761. _this.tertiaryLevel = 1;
  86762. /**
  86763. * Reflection Texture used in the material.
  86764. * Should be author in a specific way for the best result (refer to the documentation).
  86765. */
  86766. _this.reflectionTexture = null;
  86767. /**
  86768. * Reflection Texture level of blur.
  86769. *
  86770. * Can be use to reuse an existing HDR Texture and target a specific LOD to prevent authoring the
  86771. * texture twice.
  86772. */
  86773. _this.reflectionBlur = 0;
  86774. /**
  86775. * Diffuse Texture used in the material.
  86776. * Should be author in a specific way for the best result (refer to the documentation).
  86777. */
  86778. _this.diffuseTexture = null;
  86779. _this._shadowLights = null;
  86780. /**
  86781. * Specify the list of lights casting shadow on the material.
  86782. * All scene shadow lights will be included if null.
  86783. */
  86784. _this.shadowLights = null;
  86785. /**
  86786. * For the lights having a blurred shadow generator, this can add a second blur pass in order to reach
  86787. * soft lighting on the background.
  86788. */
  86789. _this.shadowBlurScale = 1;
  86790. /**
  86791. * Helps adjusting the shadow to a softer level if required.
  86792. * 0 means black shadows and 1 means no shadows.
  86793. */
  86794. _this.shadowLevel = 0;
  86795. /**
  86796. * In case of opacity Fresnel or reflection falloff, this is use as a scene center.
  86797. * It is usually zero but might be interesting to modify according to your setup.
  86798. */
  86799. _this.sceneCenter = BABYLON.Vector3.Zero();
  86800. /**
  86801. * This helps specifying that the material is falling off to the sky box at grazing angle.
  86802. * This helps ensuring a nice transition when the camera goes under the ground.
  86803. */
  86804. _this.opacityFresnel = true;
  86805. /**
  86806. * This helps specifying that the material is falling off from diffuse to the reflection texture at grazing angle.
  86807. * This helps adding a mirror texture on the ground.
  86808. */
  86809. _this.reflectionFresnel = false;
  86810. /**
  86811. * This helps specifying the falloff radius off the reflection texture from the sceneCenter.
  86812. * This helps adding a nice falloff effect to the reflection if used as a mirror for instance.
  86813. */
  86814. _this.reflectionFalloffDistance = 0.0;
  86815. /**
  86816. * This specifies the weight of the reflection against the background in case of reflection Fresnel.
  86817. */
  86818. _this.reflectionAmount = 1.0;
  86819. /**
  86820. * This specifies the weight of the reflection at grazing angle.
  86821. */
  86822. _this.reflectionReflectance0 = 0.05;
  86823. /**
  86824. * This specifies the weight of the reflection at a perpendicular point of view.
  86825. */
  86826. _this.reflectionReflectance90 = 0.5;
  86827. /**
  86828. * Helps to directly use the maps channels instead of their level.
  86829. */
  86830. _this.useRGBColor = true;
  86831. /**
  86832. * This helps reducing the banding effect that could occur on the background.
  86833. */
  86834. _this.enableNoise = false;
  86835. _this._fovMultiplier = 1.0;
  86836. /**
  86837. * Enable the FOV adjustment feature controlled by fovMultiplier.
  86838. * @type {boolean}
  86839. */
  86840. _this.useEquirectangularFOV = false;
  86841. _this._maxSimultaneousLights = 4;
  86842. /**
  86843. * Number of Simultaneous lights allowed on the material.
  86844. */
  86845. _this.maxSimultaneousLights = 4;
  86846. /**
  86847. * Keep track of the image processing observer to allow dispose and replace.
  86848. */
  86849. _this._imageProcessingObserver = null;
  86850. // Temp values kept as cache in the material.
  86851. _this._renderTargets = new BABYLON.SmartArray(16);
  86852. _this._reflectionControls = BABYLON.Vector4.Zero();
  86853. // Setup the default processing configuration to the scene.
  86854. _this._attachImageProcessingConfiguration(null);
  86855. _this.getRenderTargetTextures = function () {
  86856. _this._renderTargets.reset();
  86857. if (_this._diffuseTexture && _this._diffuseTexture.isRenderTarget) {
  86858. _this._renderTargets.push(_this._diffuseTexture);
  86859. }
  86860. if (_this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  86861. _this._renderTargets.push(_this._reflectionTexture);
  86862. }
  86863. return _this._renderTargets;
  86864. };
  86865. return _this;
  86866. }
  86867. Object.defineProperty(BackgroundMaterial.prototype, "reflectionStandardFresnelWeight", {
  86868. /**
  86869. * Sets the reflection reflectance fresnel values according to the default standard
  86870. * empirically know to work well :-)
  86871. */
  86872. set: function (value) {
  86873. var reflectionWeight = value;
  86874. if (reflectionWeight < 0.5) {
  86875. reflectionWeight = reflectionWeight * 2.0;
  86876. this.reflectionReflectance0 = BackgroundMaterial.StandardReflectance0 * reflectionWeight;
  86877. this.reflectionReflectance90 = BackgroundMaterial.StandardReflectance90 * reflectionWeight;
  86878. }
  86879. else {
  86880. reflectionWeight = reflectionWeight * 2.0 - 1.0;
  86881. this.reflectionReflectance0 = BackgroundMaterial.StandardReflectance0 + (1.0 - BackgroundMaterial.StandardReflectance0) * reflectionWeight;
  86882. this.reflectionReflectance90 = BackgroundMaterial.StandardReflectance90 + (1.0 - BackgroundMaterial.StandardReflectance90) * reflectionWeight;
  86883. }
  86884. },
  86885. enumerable: true,
  86886. configurable: true
  86887. });
  86888. Object.defineProperty(BackgroundMaterial.prototype, "fovMultiplier", {
  86889. /**
  86890. * The current fov(field of view) multiplier, 0.0 - 2.0. Defaults to 1.0. Lower values "zoom in" and higher values "zoom out".
  86891. * Best used when trying to implement visual zoom effects like fish-eye or binoculars while not adjusting camera fov.
  86892. * Recommended to be keep at 1.0 except for special cases.
  86893. */
  86894. get: function () {
  86895. return this._fovMultiplier;
  86896. },
  86897. set: function (value) {
  86898. if (isNaN(value)) {
  86899. value = 1.0;
  86900. }
  86901. this._fovMultiplier = Math.max(0.0, Math.min(2.0, value));
  86902. },
  86903. enumerable: true,
  86904. configurable: true
  86905. });
  86906. /**
  86907. * Attaches a new image processing configuration to the PBR Material.
  86908. * @param configuration (if null the scene configuration will be use)
  86909. */
  86910. BackgroundMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  86911. var _this = this;
  86912. if (configuration === this._imageProcessingConfiguration) {
  86913. return;
  86914. }
  86915. // Detaches observer.
  86916. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  86917. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  86918. }
  86919. // Pick the scene configuration if needed.
  86920. if (!configuration) {
  86921. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  86922. }
  86923. else {
  86924. this._imageProcessingConfiguration = configuration;
  86925. }
  86926. // Attaches observer.
  86927. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  86928. _this._markAllSubMeshesAsImageProcessingDirty();
  86929. });
  86930. };
  86931. Object.defineProperty(BackgroundMaterial.prototype, "imageProcessingConfiguration", {
  86932. /**
  86933. * Gets the image processing configuration used either in this material.
  86934. */
  86935. get: function () {
  86936. return this._imageProcessingConfiguration;
  86937. },
  86938. /**
  86939. * Sets the Default image processing configuration used either in the this material.
  86940. *
  86941. * If sets to null, the scene one is in use.
  86942. */
  86943. set: function (value) {
  86944. this._attachImageProcessingConfiguration(value);
  86945. // Ensure the effect will be rebuilt.
  86946. this._markAllSubMeshesAsTexturesDirty();
  86947. },
  86948. enumerable: true,
  86949. configurable: true
  86950. });
  86951. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorCurvesEnabled", {
  86952. /**
  86953. * Gets wether the color curves effect is enabled.
  86954. */
  86955. get: function () {
  86956. return this.imageProcessingConfiguration.colorCurvesEnabled;
  86957. },
  86958. /**
  86959. * Sets wether the color curves effect is enabled.
  86960. */
  86961. set: function (value) {
  86962. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  86963. },
  86964. enumerable: true,
  86965. configurable: true
  86966. });
  86967. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorGradingEnabled", {
  86968. /**
  86969. * Gets wether the color grading effect is enabled.
  86970. */
  86971. get: function () {
  86972. return this.imageProcessingConfiguration.colorGradingEnabled;
  86973. },
  86974. /**
  86975. * Gets wether the color grading effect is enabled.
  86976. */
  86977. set: function (value) {
  86978. this.imageProcessingConfiguration.colorGradingEnabled = value;
  86979. },
  86980. enumerable: true,
  86981. configurable: true
  86982. });
  86983. Object.defineProperty(BackgroundMaterial.prototype, "cameraToneMappingEnabled", {
  86984. /**
  86985. * Gets wether tonemapping is enabled or not.
  86986. */
  86987. get: function () {
  86988. return this._imageProcessingConfiguration.toneMappingEnabled;
  86989. },
  86990. /**
  86991. * Sets wether tonemapping is enabled or not
  86992. */
  86993. set: function (value) {
  86994. this._imageProcessingConfiguration.toneMappingEnabled = value;
  86995. },
  86996. enumerable: true,
  86997. configurable: true
  86998. });
  86999. ;
  87000. ;
  87001. Object.defineProperty(BackgroundMaterial.prototype, "cameraExposure", {
  87002. /**
  87003. * The camera exposure used on this material.
  87004. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  87005. * This corresponds to a photographic exposure.
  87006. */
  87007. get: function () {
  87008. return this._imageProcessingConfiguration.exposure;
  87009. },
  87010. /**
  87011. * The camera exposure used on this material.
  87012. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  87013. * This corresponds to a photographic exposure.
  87014. */
  87015. set: function (value) {
  87016. this._imageProcessingConfiguration.exposure = value;
  87017. },
  87018. enumerable: true,
  87019. configurable: true
  87020. });
  87021. ;
  87022. ;
  87023. Object.defineProperty(BackgroundMaterial.prototype, "cameraContrast", {
  87024. /**
  87025. * Gets The camera contrast used on this material.
  87026. */
  87027. get: function () {
  87028. return this._imageProcessingConfiguration.contrast;
  87029. },
  87030. /**
  87031. * Sets The camera contrast used on this material.
  87032. */
  87033. set: function (value) {
  87034. this._imageProcessingConfiguration.contrast = value;
  87035. },
  87036. enumerable: true,
  87037. configurable: true
  87038. });
  87039. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorGradingTexture", {
  87040. /**
  87041. * Gets the Color Grading 2D Lookup Texture.
  87042. */
  87043. get: function () {
  87044. return this._imageProcessingConfiguration.colorGradingTexture;
  87045. },
  87046. /**
  87047. * Sets the Color Grading 2D Lookup Texture.
  87048. */
  87049. set: function (value) {
  87050. this.imageProcessingConfiguration.colorGradingTexture = value;
  87051. },
  87052. enumerable: true,
  87053. configurable: true
  87054. });
  87055. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorCurves", {
  87056. /**
  87057. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  87058. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  87059. * 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;
  87060. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  87061. */
  87062. get: function () {
  87063. return this.imageProcessingConfiguration.colorCurves;
  87064. },
  87065. /**
  87066. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  87067. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  87068. * 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;
  87069. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  87070. */
  87071. set: function (value) {
  87072. this.imageProcessingConfiguration.colorCurves = value;
  87073. },
  87074. enumerable: true,
  87075. configurable: true
  87076. });
  87077. /**
  87078. * The entire material has been created in order to prevent overdraw.
  87079. * @returns false
  87080. */
  87081. BackgroundMaterial.prototype.needAlphaTesting = function () {
  87082. return true;
  87083. };
  87084. /**
  87085. * The entire material has been created in order to prevent overdraw.
  87086. * @returns true if blending is enable
  87087. */
  87088. BackgroundMaterial.prototype.needAlphaBlending = function () {
  87089. return ((this.alpha < 0) || (this._diffuseTexture != null && this._diffuseTexture.hasAlpha));
  87090. };
  87091. /**
  87092. * Checks wether the material is ready to be rendered for a given mesh.
  87093. * @param mesh The mesh to render
  87094. * @param subMesh The submesh to check against
  87095. * @param useInstances Specify wether or not the material is used with instances
  87096. * @returns true if all the dependencies are ready (Textures, Effects...)
  87097. */
  87098. BackgroundMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  87099. var _this = this;
  87100. if (useInstances === void 0) { useInstances = false; }
  87101. if (subMesh.effect && this.isFrozen) {
  87102. if (this._wasPreviouslyReady) {
  87103. return true;
  87104. }
  87105. }
  87106. if (!subMesh._materialDefines) {
  87107. subMesh._materialDefines = new BackgroundMaterialDefines();
  87108. }
  87109. var scene = this.getScene();
  87110. var defines = subMesh._materialDefines;
  87111. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  87112. if (defines._renderId === scene.getRenderId()) {
  87113. return true;
  87114. }
  87115. }
  87116. var engine = scene.getEngine();
  87117. // Lights
  87118. BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, false, this._maxSimultaneousLights);
  87119. defines._needNormals = true;
  87120. // Textures
  87121. if (defines._areTexturesDirty) {
  87122. defines._needUVs = false;
  87123. if (scene.texturesEnabled) {
  87124. if (scene.getEngine().getCaps().textureLOD) {
  87125. defines.TEXTURELODSUPPORT = true;
  87126. }
  87127. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  87128. if (!this._diffuseTexture.isReadyOrNotBlocking()) {
  87129. return false;
  87130. }
  87131. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._diffuseTexture, defines, "DIFFUSE");
  87132. defines.DIFFUSEHASALPHA = this._diffuseTexture.hasAlpha;
  87133. defines.GAMMADIFFUSE = this._diffuseTexture.gammaSpace;
  87134. defines.OPACITYFRESNEL = this._opacityFresnel;
  87135. }
  87136. else {
  87137. defines.DIFFUSE = false;
  87138. defines.DIFFUSEHASALPHA = false;
  87139. defines.GAMMADIFFUSE = false;
  87140. defines.OPACITYFRESNEL = false;
  87141. }
  87142. var reflectionTexture = this._reflectionTexture;
  87143. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  87144. if (!reflectionTexture.isReadyOrNotBlocking()) {
  87145. return false;
  87146. }
  87147. defines.REFLECTION = true;
  87148. defines.GAMMAREFLECTION = reflectionTexture.gammaSpace;
  87149. defines.REFLECTIONBLUR = this._reflectionBlur > 0;
  87150. defines.REFLECTIONMAP_OPPOSITEZ = this.getScene().useRightHandedSystem ? !reflectionTexture.invertZ : reflectionTexture.invertZ;
  87151. defines.LODINREFLECTIONALPHA = reflectionTexture.lodLevelInAlpha;
  87152. defines.EQUIRECTANGULAR_RELFECTION_FOV = this.useEquirectangularFOV;
  87153. if (reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  87154. defines.INVERTCUBICMAP = true;
  87155. }
  87156. defines.REFLECTIONMAP_3D = reflectionTexture.isCube;
  87157. switch (reflectionTexture.coordinatesMode) {
  87158. case BABYLON.Texture.CUBIC_MODE:
  87159. case BABYLON.Texture.INVCUBIC_MODE:
  87160. defines.REFLECTIONMAP_CUBIC = true;
  87161. break;
  87162. case BABYLON.Texture.EXPLICIT_MODE:
  87163. defines.REFLECTIONMAP_EXPLICIT = true;
  87164. break;
  87165. case BABYLON.Texture.PLANAR_MODE:
  87166. defines.REFLECTIONMAP_PLANAR = true;
  87167. break;
  87168. case BABYLON.Texture.PROJECTION_MODE:
  87169. defines.REFLECTIONMAP_PROJECTION = true;
  87170. break;
  87171. case BABYLON.Texture.SKYBOX_MODE:
  87172. defines.REFLECTIONMAP_SKYBOX = true;
  87173. break;
  87174. case BABYLON.Texture.SPHERICAL_MODE:
  87175. defines.REFLECTIONMAP_SPHERICAL = true;
  87176. break;
  87177. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  87178. defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  87179. break;
  87180. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  87181. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = true;
  87182. break;
  87183. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  87184. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = true;
  87185. break;
  87186. }
  87187. if (this.reflectionFresnel) {
  87188. defines.REFLECTIONFRESNEL = true;
  87189. defines.REFLECTIONFALLOFF = this.reflectionFalloffDistance > 0;
  87190. this._reflectionControls.x = this.reflectionAmount;
  87191. this._reflectionControls.y = this.reflectionReflectance0;
  87192. this._reflectionControls.z = this.reflectionReflectance90;
  87193. this._reflectionControls.w = 1 / this.reflectionFalloffDistance;
  87194. }
  87195. else {
  87196. defines.REFLECTIONFRESNEL = false;
  87197. defines.REFLECTIONFALLOFF = false;
  87198. }
  87199. }
  87200. else {
  87201. defines.REFLECTION = false;
  87202. defines.REFLECTIONFALLOFF = false;
  87203. defines.REFLECTIONBLUR = false;
  87204. defines.REFLECTIONMAP_3D = false;
  87205. defines.REFLECTIONMAP_SPHERICAL = false;
  87206. defines.REFLECTIONMAP_PLANAR = false;
  87207. defines.REFLECTIONMAP_CUBIC = false;
  87208. defines.REFLECTIONMAP_PROJECTION = false;
  87209. defines.REFLECTIONMAP_SKYBOX = false;
  87210. defines.REFLECTIONMAP_EXPLICIT = false;
  87211. defines.REFLECTIONMAP_EQUIRECTANGULAR = false;
  87212. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  87213. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  87214. defines.INVERTCUBICMAP = false;
  87215. defines.REFLECTIONMAP_OPPOSITEZ = false;
  87216. defines.LODINREFLECTIONALPHA = false;
  87217. defines.GAMMAREFLECTION = false;
  87218. }
  87219. }
  87220. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  87221. defines.USERGBCOLOR = this._useRGBColor;
  87222. defines.NOISE = this._enableNoise;
  87223. }
  87224. if (defines._areImageProcessingDirty) {
  87225. if (!this._imageProcessingConfiguration.isReady()) {
  87226. return false;
  87227. }
  87228. this._imageProcessingConfiguration.prepareDefines(defines);
  87229. }
  87230. // Misc.
  87231. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, false, this.pointsCloud, this.fogEnabled, this._shouldTurnAlphaTestOn(mesh), defines);
  87232. // Values that need to be evaluated on every frame
  87233. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances);
  87234. // Attribs
  87235. if (BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, false, true, false)) {
  87236. if (mesh) {
  87237. if (!scene.getEngine().getCaps().standardDerivatives && !mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  87238. mesh.createNormals(true);
  87239. BABYLON.Tools.Warn("BackgroundMaterial: Normals have been created for the mesh: " + mesh.name);
  87240. }
  87241. }
  87242. }
  87243. // Get correct effect
  87244. if (defines.isDirty) {
  87245. defines.markAsProcessed();
  87246. scene.resetCachedMaterial();
  87247. // Fallbacks
  87248. var fallbacks = new BABYLON.EffectFallbacks();
  87249. if (defines.FOG) {
  87250. fallbacks.addFallback(0, "FOG");
  87251. }
  87252. if (defines.POINTSIZE) {
  87253. fallbacks.addFallback(1, "POINTSIZE");
  87254. }
  87255. BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights);
  87256. if (defines.NUM_BONE_INFLUENCERS > 0) {
  87257. fallbacks.addCPUSkinningFallback(0, mesh);
  87258. }
  87259. //Attributes
  87260. var attribs = [BABYLON.VertexBuffer.PositionKind];
  87261. if (defines.NORMAL) {
  87262. attribs.push(BABYLON.VertexBuffer.NormalKind);
  87263. }
  87264. if (defines.UV1) {
  87265. attribs.push(BABYLON.VertexBuffer.UVKind);
  87266. }
  87267. if (defines.UV2) {
  87268. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  87269. }
  87270. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  87271. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  87272. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType",
  87273. "vFogInfos", "vFogColor", "pointSize",
  87274. "vClipPlane", "mBones",
  87275. "vPrimaryColor", "vSecondaryColor", "vTertiaryColor",
  87276. "vReflectionInfos", "reflectionMatrix", "vReflectionMicrosurfaceInfos", "fFovMultiplier",
  87277. "shadowLevel", "alpha",
  87278. "vBackgroundCenter", "vReflectionControl",
  87279. "vDiffuseInfos", "diffuseMatrix",
  87280. ];
  87281. var samplers = ["diffuseSampler", "reflectionSampler", "reflectionSamplerLow", "reflectionSamplerHigh"];
  87282. var uniformBuffers = ["Material", "Scene"];
  87283. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  87284. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  87285. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  87286. uniformsNames: uniforms,
  87287. uniformBuffersNames: uniformBuffers,
  87288. samplers: samplers,
  87289. defines: defines,
  87290. maxSimultaneousLights: this._maxSimultaneousLights
  87291. });
  87292. var onCompiled = function (effect) {
  87293. if (_this.onCompiled) {
  87294. _this.onCompiled(effect);
  87295. }
  87296. _this.bindSceneUniformBuffer(effect, scene.getSceneUniformBuffer());
  87297. };
  87298. var join = defines.toString();
  87299. subMesh.setEffect(scene.getEngine().createEffect("background", {
  87300. attributes: attribs,
  87301. uniformsNames: uniforms,
  87302. uniformBuffersNames: uniformBuffers,
  87303. samplers: samplers,
  87304. defines: join,
  87305. fallbacks: fallbacks,
  87306. onCompiled: onCompiled,
  87307. onError: this.onError,
  87308. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights }
  87309. }, engine), defines);
  87310. this.buildUniformLayout();
  87311. }
  87312. if (!subMesh.effect || !subMesh.effect.isReady()) {
  87313. return false;
  87314. }
  87315. defines._renderId = scene.getRenderId();
  87316. this._wasPreviouslyReady = true;
  87317. return true;
  87318. };
  87319. /**
  87320. * Build the uniform buffer used in the material.
  87321. */
  87322. BackgroundMaterial.prototype.buildUniformLayout = function () {
  87323. // Order is important !
  87324. this._uniformBuffer.addUniform("vPrimaryColor", 4);
  87325. this._uniformBuffer.addUniform("vSecondaryColor", 4);
  87326. this._uniformBuffer.addUniform("vTertiaryColor", 4);
  87327. this._uniformBuffer.addUniform("vDiffuseInfos", 2);
  87328. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  87329. this._uniformBuffer.addUniform("diffuseMatrix", 16);
  87330. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  87331. this._uniformBuffer.addUniform("vReflectionMicrosurfaceInfos", 3);
  87332. this._uniformBuffer.addUniform("fFovMultiplier", 1);
  87333. this._uniformBuffer.addUniform("pointSize", 1);
  87334. this._uniformBuffer.addUniform("shadowLevel", 1);
  87335. this._uniformBuffer.addUniform("alpha", 1);
  87336. this._uniformBuffer.addUniform("vBackgroundCenter", 3);
  87337. this._uniformBuffer.addUniform("vReflectionControl", 4);
  87338. this._uniformBuffer.create();
  87339. };
  87340. /**
  87341. * Unbind the material.
  87342. */
  87343. BackgroundMaterial.prototype.unbind = function () {
  87344. if (this._diffuseTexture && this._diffuseTexture.isRenderTarget) {
  87345. this._uniformBuffer.setTexture("diffuseSampler", null);
  87346. }
  87347. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  87348. this._uniformBuffer.setTexture("reflectionSampler", null);
  87349. }
  87350. _super.prototype.unbind.call(this);
  87351. };
  87352. /**
  87353. * Bind only the world matrix to the material.
  87354. * @param world The world matrix to bind.
  87355. */
  87356. BackgroundMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  87357. this._activeEffect.setMatrix("world", world);
  87358. };
  87359. /**
  87360. * Bind the material for a dedicated submeh (every used meshes will be considered opaque).
  87361. * @param world The world matrix to bind.
  87362. * @param subMesh The submesh to bind for.
  87363. */
  87364. BackgroundMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  87365. var scene = this.getScene();
  87366. var defines = subMesh._materialDefines;
  87367. if (!defines) {
  87368. return;
  87369. }
  87370. var effect = subMesh.effect;
  87371. if (!effect) {
  87372. return;
  87373. }
  87374. this._activeEffect = effect;
  87375. // Matrices
  87376. this.bindOnlyWorldMatrix(world);
  87377. // Bones
  87378. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._activeEffect);
  87379. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  87380. if (mustRebind) {
  87381. this._uniformBuffer.bindToEffect(effect, "Material");
  87382. this.bindViewProjection(effect);
  87383. var reflectionTexture = this._reflectionTexture;
  87384. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  87385. // Texture uniforms
  87386. if (scene.texturesEnabled) {
  87387. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  87388. this._uniformBuffer.updateFloat2("vDiffuseInfos", this._diffuseTexture.coordinatesIndex, this._diffuseTexture.level);
  87389. BABYLON.MaterialHelper.BindTextureMatrix(this._diffuseTexture, this._uniformBuffer, "diffuse");
  87390. }
  87391. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  87392. this._uniformBuffer.updateMatrix("reflectionMatrix", reflectionTexture.getReflectionTextureMatrix());
  87393. this._uniformBuffer.updateFloat2("vReflectionInfos", reflectionTexture.level, this._reflectionBlur);
  87394. this._uniformBuffer.updateFloat3("vReflectionMicrosurfaceInfos", reflectionTexture.getSize().width, reflectionTexture.lodGenerationScale, reflectionTexture.lodGenerationOffset);
  87395. }
  87396. }
  87397. if (this.shadowLevel > 0) {
  87398. this._uniformBuffer.updateFloat("shadowLevel", this.shadowLevel);
  87399. }
  87400. this._uniformBuffer.updateFloat("alpha", this.alpha);
  87401. // Point size
  87402. if (this.pointsCloud) {
  87403. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  87404. }
  87405. this._uniformBuffer.updateColor4("vPrimaryColor", this._primaryColor, this._primaryLevel);
  87406. this._uniformBuffer.updateColor4("vSecondaryColor", this._secondaryColor, this._secondaryLevel);
  87407. this._uniformBuffer.updateColor4("vTertiaryColor", this._tertiaryColor, this._tertiaryLevel);
  87408. }
  87409. this._uniformBuffer.updateFloat("fFovMultiplier", this._fovMultiplier);
  87410. // Textures
  87411. if (scene.texturesEnabled) {
  87412. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  87413. this._uniformBuffer.setTexture("diffuseSampler", this._diffuseTexture);
  87414. }
  87415. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  87416. if (defines.REFLECTIONBLUR && defines.TEXTURELODSUPPORT) {
  87417. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  87418. }
  87419. else if (!defines.REFLECTIONBLUR) {
  87420. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  87421. }
  87422. else {
  87423. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture._lodTextureMid || reflectionTexture);
  87424. this._uniformBuffer.setTexture("reflectionSamplerLow", reflectionTexture._lodTextureLow || reflectionTexture);
  87425. this._uniformBuffer.setTexture("reflectionSamplerHigh", reflectionTexture._lodTextureHigh || reflectionTexture);
  87426. }
  87427. if (defines.REFLECTIONFRESNEL) {
  87428. this._uniformBuffer.updateFloat3("vBackgroundCenter", this.sceneCenter.x, this.sceneCenter.y, this.sceneCenter.z);
  87429. this._uniformBuffer.updateFloat4("vReflectionControl", this._reflectionControls.x, this._reflectionControls.y, this._reflectionControls.z, this._reflectionControls.w);
  87430. }
  87431. }
  87432. }
  87433. // Clip plane
  87434. BABYLON.MaterialHelper.BindClipPlane(this._activeEffect, scene);
  87435. BABYLON.MaterialHelper.BindEyePosition(effect, scene);
  87436. }
  87437. if (mustRebind || !this.isFrozen) {
  87438. if (scene.lightsEnabled) {
  87439. BABYLON.MaterialHelper.BindLights(scene, mesh, this._activeEffect, defines, this._maxSimultaneousLights, false);
  87440. }
  87441. // View
  87442. this.bindView(effect);
  87443. // Fog
  87444. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, this._activeEffect);
  87445. // image processing
  87446. this._imageProcessingConfiguration.bind(this._activeEffect);
  87447. }
  87448. this._uniformBuffer.update();
  87449. this._afterBind(mesh);
  87450. };
  87451. /**
  87452. * Dispose the material.
  87453. * @param forceDisposeEffect Force disposal of the associated effect.
  87454. * @param forceDisposeTextures Force disposal of the associated textures.
  87455. */
  87456. BackgroundMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  87457. if (forceDisposeEffect === void 0) { forceDisposeEffect = false; }
  87458. if (forceDisposeTextures === void 0) { forceDisposeTextures = false; }
  87459. if (forceDisposeTextures) {
  87460. if (this.diffuseTexture) {
  87461. this.diffuseTexture.dispose();
  87462. }
  87463. if (this.reflectionTexture) {
  87464. this.reflectionTexture.dispose();
  87465. }
  87466. }
  87467. this._renderTargets.dispose();
  87468. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  87469. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  87470. }
  87471. _super.prototype.dispose.call(this, forceDisposeEffect);
  87472. };
  87473. /**
  87474. * Clones the material.
  87475. * @param name The cloned name.
  87476. * @returns The cloned material.
  87477. */
  87478. BackgroundMaterial.prototype.clone = function (name) {
  87479. var _this = this;
  87480. return BABYLON.SerializationHelper.Clone(function () { return new BackgroundMaterial(name, _this.getScene()); }, this);
  87481. };
  87482. /**
  87483. * Serializes the current material to its JSON representation.
  87484. * @returns The JSON representation.
  87485. */
  87486. BackgroundMaterial.prototype.serialize = function () {
  87487. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  87488. serializationObject.customType = "BABYLON.BackgroundMaterial";
  87489. return serializationObject;
  87490. };
  87491. /**
  87492. * Gets the class name of the material
  87493. * @returns "BackgroundMaterial"
  87494. */
  87495. BackgroundMaterial.prototype.getClassName = function () {
  87496. return "BackgroundMaterial";
  87497. };
  87498. /**
  87499. * Parse a JSON input to create back a background material.
  87500. * @param source The JSON data to parse
  87501. * @param scene The scene to create the parsed material in
  87502. * @param rootUrl The root url of the assets the material depends upon
  87503. * @returns the instantiated BackgroundMaterial.
  87504. */
  87505. BackgroundMaterial.Parse = function (source, scene, rootUrl) {
  87506. return BABYLON.SerializationHelper.Parse(function () { return new BackgroundMaterial(source.name, scene); }, source, scene, rootUrl);
  87507. };
  87508. /**
  87509. * Standard reflectance value at parallel view angle.
  87510. */
  87511. BackgroundMaterial.StandardReflectance0 = 0.05;
  87512. /**
  87513. * Standard reflectance value at grazing angle.
  87514. */
  87515. BackgroundMaterial.StandardReflectance90 = 0.5;
  87516. __decorate([
  87517. BABYLON.serializeAsColor3()
  87518. ], BackgroundMaterial.prototype, "_primaryColor", void 0);
  87519. __decorate([
  87520. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  87521. ], BackgroundMaterial.prototype, "primaryColor", void 0);
  87522. __decorate([
  87523. BABYLON.serialize()
  87524. ], BackgroundMaterial.prototype, "_primaryLevel", void 0);
  87525. __decorate([
  87526. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  87527. ], BackgroundMaterial.prototype, "primaryLevel", void 0);
  87528. __decorate([
  87529. BABYLON.serializeAsColor3()
  87530. ], BackgroundMaterial.prototype, "_secondaryColor", void 0);
  87531. __decorate([
  87532. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  87533. ], BackgroundMaterial.prototype, "secondaryColor", void 0);
  87534. __decorate([
  87535. BABYLON.serialize()
  87536. ], BackgroundMaterial.prototype, "_secondaryLevel", void 0);
  87537. __decorate([
  87538. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  87539. ], BackgroundMaterial.prototype, "secondaryLevel", void 0);
  87540. __decorate([
  87541. BABYLON.serializeAsColor3()
  87542. ], BackgroundMaterial.prototype, "_tertiaryColor", void 0);
  87543. __decorate([
  87544. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  87545. ], BackgroundMaterial.prototype, "tertiaryColor", void 0);
  87546. __decorate([
  87547. BABYLON.serialize()
  87548. ], BackgroundMaterial.prototype, "_tertiaryLevel", void 0);
  87549. __decorate([
  87550. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  87551. ], BackgroundMaterial.prototype, "tertiaryLevel", void 0);
  87552. __decorate([
  87553. BABYLON.serializeAsTexture()
  87554. ], BackgroundMaterial.prototype, "_reflectionTexture", void 0);
  87555. __decorate([
  87556. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  87557. ], BackgroundMaterial.prototype, "reflectionTexture", void 0);
  87558. __decorate([
  87559. BABYLON.serialize()
  87560. ], BackgroundMaterial.prototype, "_reflectionBlur", void 0);
  87561. __decorate([
  87562. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  87563. ], BackgroundMaterial.prototype, "reflectionBlur", void 0);
  87564. __decorate([
  87565. BABYLON.serializeAsTexture()
  87566. ], BackgroundMaterial.prototype, "_diffuseTexture", void 0);
  87567. __decorate([
  87568. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  87569. ], BackgroundMaterial.prototype, "diffuseTexture", void 0);
  87570. __decorate([
  87571. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  87572. ], BackgroundMaterial.prototype, "shadowLights", void 0);
  87573. __decorate([
  87574. BABYLON.serialize()
  87575. ], BackgroundMaterial.prototype, "_shadowBlurScale", void 0);
  87576. __decorate([
  87577. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  87578. ], BackgroundMaterial.prototype, "shadowBlurScale", void 0);
  87579. __decorate([
  87580. BABYLON.serialize()
  87581. ], BackgroundMaterial.prototype, "_shadowLevel", void 0);
  87582. __decorate([
  87583. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  87584. ], BackgroundMaterial.prototype, "shadowLevel", void 0);
  87585. __decorate([
  87586. BABYLON.serializeAsVector3()
  87587. ], BackgroundMaterial.prototype, "_sceneCenter", void 0);
  87588. __decorate([
  87589. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  87590. ], BackgroundMaterial.prototype, "sceneCenter", void 0);
  87591. __decorate([
  87592. BABYLON.serialize()
  87593. ], BackgroundMaterial.prototype, "_opacityFresnel", void 0);
  87594. __decorate([
  87595. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  87596. ], BackgroundMaterial.prototype, "opacityFresnel", void 0);
  87597. __decorate([
  87598. BABYLON.serialize()
  87599. ], BackgroundMaterial.prototype, "_reflectionFresnel", void 0);
  87600. __decorate([
  87601. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  87602. ], BackgroundMaterial.prototype, "reflectionFresnel", void 0);
  87603. __decorate([
  87604. BABYLON.serialize()
  87605. ], BackgroundMaterial.prototype, "_reflectionFalloffDistance", void 0);
  87606. __decorate([
  87607. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  87608. ], BackgroundMaterial.prototype, "reflectionFalloffDistance", void 0);
  87609. __decorate([
  87610. BABYLON.serialize()
  87611. ], BackgroundMaterial.prototype, "_reflectionAmount", void 0);
  87612. __decorate([
  87613. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  87614. ], BackgroundMaterial.prototype, "reflectionAmount", void 0);
  87615. __decorate([
  87616. BABYLON.serialize()
  87617. ], BackgroundMaterial.prototype, "_reflectionReflectance0", void 0);
  87618. __decorate([
  87619. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  87620. ], BackgroundMaterial.prototype, "reflectionReflectance0", void 0);
  87621. __decorate([
  87622. BABYLON.serialize()
  87623. ], BackgroundMaterial.prototype, "_reflectionReflectance90", void 0);
  87624. __decorate([
  87625. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  87626. ], BackgroundMaterial.prototype, "reflectionReflectance90", void 0);
  87627. __decorate([
  87628. BABYLON.serialize()
  87629. ], BackgroundMaterial.prototype, "_useRGBColor", void 0);
  87630. __decorate([
  87631. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  87632. ], BackgroundMaterial.prototype, "useRGBColor", void 0);
  87633. __decorate([
  87634. BABYLON.serialize()
  87635. ], BackgroundMaterial.prototype, "_enableNoise", void 0);
  87636. __decorate([
  87637. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  87638. ], BackgroundMaterial.prototype, "enableNoise", void 0);
  87639. __decorate([
  87640. BABYLON.serialize()
  87641. ], BackgroundMaterial.prototype, "_maxSimultaneousLights", void 0);
  87642. __decorate([
  87643. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  87644. ], BackgroundMaterial.prototype, "maxSimultaneousLights", void 0);
  87645. __decorate([
  87646. BABYLON.serializeAsImageProcessingConfiguration()
  87647. ], BackgroundMaterial.prototype, "_imageProcessingConfiguration", void 0);
  87648. return BackgroundMaterial;
  87649. }(BABYLON.PushMaterial));
  87650. BABYLON.BackgroundMaterial = BackgroundMaterial;
  87651. })(BABYLON || (BABYLON = {}));
  87652. //# sourceMappingURL=babylon.backgroundMaterial.js.map
  87653. var __assign = (this && this.__assign) || Object.assign || function(t) {
  87654. for (var s, i = 1, n = arguments.length; i < n; i++) {
  87655. s = arguments[i];
  87656. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  87657. t[p] = s[p];
  87658. }
  87659. return t;
  87660. };
  87661. var BABYLON;
  87662. (function (BABYLON) {
  87663. /**
  87664. * The Environment helper class can be used to add a fully featuread none expensive background to your scene.
  87665. * It includes by default a skybox and a ground relying on the BackgroundMaterial.
  87666. * It also helps with the default setup of your imageProcessing configuration.
  87667. */
  87668. var EnvironmentHelper = /** @class */ (function () {
  87669. /**
  87670. * constructor
  87671. * @param options
  87672. * @param scene The scene to add the material to
  87673. */
  87674. function EnvironmentHelper(options, scene) {
  87675. this._options = __assign({}, EnvironmentHelper._getDefaultOptions(), options);
  87676. this._scene = scene;
  87677. this._setupBackground();
  87678. this._setupImageProcessing();
  87679. }
  87680. /**
  87681. * Creates the default options for the helper.
  87682. */
  87683. EnvironmentHelper._getDefaultOptions = function () {
  87684. return {
  87685. createGround: true,
  87686. groundSize: 15,
  87687. groundTexture: this._groundTextureCDNUrl,
  87688. groundColor: new BABYLON.Color3(0.2, 0.2, 0.3).toLinearSpace().scale(3),
  87689. groundOpacity: 0.9,
  87690. enableGroundShadow: true,
  87691. groundShadowLevel: 0.5,
  87692. enableGroundMirror: false,
  87693. groundMirrorSizeRatio: 0.3,
  87694. groundMirrorBlurKernel: 64,
  87695. groundMirrorAmount: 1,
  87696. groundMirrorFresnelWeight: 1,
  87697. groundMirrorFallOffDistance: 0,
  87698. groundMirrorTextureType: BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT,
  87699. groundYBias: 0.00001,
  87700. createSkybox: true,
  87701. skyboxSize: 20,
  87702. skyboxTexture: this._skyboxTextureCDNUrl,
  87703. skyboxColor: new BABYLON.Color3(0.2, 0.2, 0.3).toLinearSpace().scale(3),
  87704. backgroundYRotation: 0,
  87705. sizeAuto: true,
  87706. rootPosition: BABYLON.Vector3.Zero(),
  87707. setupImageProcessing: true,
  87708. environmentTexture: this._environmentTextureCDNUrl,
  87709. cameraExposure: 0.8,
  87710. cameraContrast: 1.2,
  87711. toneMappingEnabled: true,
  87712. };
  87713. };
  87714. Object.defineProperty(EnvironmentHelper.prototype, "rootMesh", {
  87715. /**
  87716. * Gets the root mesh created by the helper.
  87717. */
  87718. get: function () {
  87719. return this._rootMesh;
  87720. },
  87721. enumerable: true,
  87722. configurable: true
  87723. });
  87724. Object.defineProperty(EnvironmentHelper.prototype, "skybox", {
  87725. /**
  87726. * Gets the skybox created by the helper.
  87727. */
  87728. get: function () {
  87729. return this._skybox;
  87730. },
  87731. enumerable: true,
  87732. configurable: true
  87733. });
  87734. Object.defineProperty(EnvironmentHelper.prototype, "skyboxTexture", {
  87735. /**
  87736. * Gets the skybox texture created by the helper.
  87737. */
  87738. get: function () {
  87739. return this._skyboxTexture;
  87740. },
  87741. enumerable: true,
  87742. configurable: true
  87743. });
  87744. Object.defineProperty(EnvironmentHelper.prototype, "skyboxMaterial", {
  87745. /**
  87746. * Gets the skybox material created by the helper.
  87747. */
  87748. get: function () {
  87749. return this._skyboxMaterial;
  87750. },
  87751. enumerable: true,
  87752. configurable: true
  87753. });
  87754. Object.defineProperty(EnvironmentHelper.prototype, "ground", {
  87755. /**
  87756. * Gets the ground mesh created by the helper.
  87757. */
  87758. get: function () {
  87759. return this._ground;
  87760. },
  87761. enumerable: true,
  87762. configurable: true
  87763. });
  87764. Object.defineProperty(EnvironmentHelper.prototype, "groundTexture", {
  87765. /**
  87766. * Gets the ground texture created by the helper.
  87767. */
  87768. get: function () {
  87769. return this._groundTexture;
  87770. },
  87771. enumerable: true,
  87772. configurable: true
  87773. });
  87774. Object.defineProperty(EnvironmentHelper.prototype, "groundMirror", {
  87775. /**
  87776. * Gets the ground mirror created by the helper.
  87777. */
  87778. get: function () {
  87779. return this._groundMirror;
  87780. },
  87781. enumerable: true,
  87782. configurable: true
  87783. });
  87784. Object.defineProperty(EnvironmentHelper.prototype, "groundMirrorRenderList", {
  87785. /**
  87786. * Gets the ground mirror render list to helps pushing the meshes
  87787. * you wish in the ground reflection.
  87788. */
  87789. get: function () {
  87790. if (this._groundMirror) {
  87791. return this._groundMirror.renderList;
  87792. }
  87793. return null;
  87794. },
  87795. enumerable: true,
  87796. configurable: true
  87797. });
  87798. Object.defineProperty(EnvironmentHelper.prototype, "groundMaterial", {
  87799. /**
  87800. * Gets the ground material created by the helper.
  87801. */
  87802. get: function () {
  87803. return this._groundMaterial;
  87804. },
  87805. enumerable: true,
  87806. configurable: true
  87807. });
  87808. /**
  87809. * Updates the background according to the new options
  87810. * @param options
  87811. */
  87812. EnvironmentHelper.prototype.updateOptions = function (options) {
  87813. var newOptions = __assign({}, this._options, options);
  87814. if (this._ground && !newOptions.createGround) {
  87815. this._ground.dispose();
  87816. this._ground = null;
  87817. }
  87818. if (this._groundMaterial && !newOptions.createGround) {
  87819. this._groundMaterial.dispose();
  87820. this._groundMaterial = null;
  87821. }
  87822. if (this._groundTexture) {
  87823. if (this._options.groundTexture != newOptions.groundTexture) {
  87824. this._groundTexture.dispose();
  87825. this._groundTexture = null;
  87826. }
  87827. }
  87828. if (this._skybox && !newOptions.createSkybox) {
  87829. this._skybox.dispose();
  87830. this._skybox = null;
  87831. }
  87832. if (this._skyboxMaterial && !newOptions.createSkybox) {
  87833. this._skyboxMaterial.dispose();
  87834. this._skyboxMaterial = null;
  87835. }
  87836. if (this._skyboxTexture) {
  87837. if (this._options.skyboxTexture != newOptions.skyboxTexture) {
  87838. this._skyboxTexture.dispose();
  87839. this._skyboxTexture = null;
  87840. }
  87841. }
  87842. if (this._groundMirror && !newOptions.enableGroundMirror) {
  87843. this._groundMirror.dispose();
  87844. this._groundMirror = null;
  87845. }
  87846. if (this._scene.environmentTexture) {
  87847. if (this._options.environmentTexture != newOptions.environmentTexture) {
  87848. this._scene.environmentTexture.dispose();
  87849. }
  87850. }
  87851. this._options = newOptions;
  87852. this._setupBackground();
  87853. this._setupImageProcessing();
  87854. };
  87855. /**
  87856. * Sets the primary color of all the available elements.
  87857. * @param color
  87858. */
  87859. EnvironmentHelper.prototype.setMainColor = function (color) {
  87860. if (this.groundMaterial) {
  87861. this.groundMaterial.primaryColor = color;
  87862. }
  87863. if (this.skyboxMaterial) {
  87864. this.skyboxMaterial.primaryColor = color;
  87865. }
  87866. if (this.groundMirror) {
  87867. this.groundMirror.clearColor = new BABYLON.Color4(color.r, color.g, color.b, 1.0);
  87868. }
  87869. };
  87870. /**
  87871. * Setup the image processing according to the specified options.
  87872. */
  87873. EnvironmentHelper.prototype._setupImageProcessing = function () {
  87874. if (this._options.setupImageProcessing) {
  87875. this._scene.imageProcessingConfiguration.contrast = this._options.cameraContrast;
  87876. this._scene.imageProcessingConfiguration.exposure = this._options.cameraExposure;
  87877. this._scene.imageProcessingConfiguration.toneMappingEnabled = this._options.toneMappingEnabled;
  87878. this._setupEnvironmentTexture();
  87879. }
  87880. };
  87881. /**
  87882. * Setup the environment texture according to the specified options.
  87883. */
  87884. EnvironmentHelper.prototype._setupEnvironmentTexture = function () {
  87885. if (this._scene.environmentTexture) {
  87886. return;
  87887. }
  87888. if (this._options.environmentTexture instanceof BABYLON.BaseTexture) {
  87889. this._scene.environmentTexture = this._options.environmentTexture;
  87890. return;
  87891. }
  87892. var environmentTexture = BABYLON.CubeTexture.CreateFromPrefilteredData(this._options.environmentTexture, this._scene);
  87893. this._scene.environmentTexture = environmentTexture;
  87894. };
  87895. /**
  87896. * Setup the background according to the specified options.
  87897. */
  87898. EnvironmentHelper.prototype._setupBackground = function () {
  87899. if (!this._rootMesh) {
  87900. this._rootMesh = new BABYLON.Mesh("BackgroundHelper", this._scene);
  87901. }
  87902. this._rootMesh.rotation.y = this._options.backgroundYRotation;
  87903. var sceneSize = this._getSceneSize();
  87904. if (this._options.createGround) {
  87905. this._setupGround(sceneSize);
  87906. this._setupGroundMaterial();
  87907. this._setupGroundDiffuseTexture();
  87908. if (this._options.enableGroundMirror) {
  87909. this._setupGroundMirrorTexture(sceneSize);
  87910. }
  87911. this._setupMirrorInGroundMaterial();
  87912. }
  87913. if (this._options.createSkybox) {
  87914. this._setupSkybox(sceneSize);
  87915. this._setupSkyboxMaterial();
  87916. this._setupSkyboxReflectionTexture();
  87917. }
  87918. this._rootMesh.position.x = sceneSize.rootPosition.x;
  87919. this._rootMesh.position.z = sceneSize.rootPosition.z;
  87920. this._rootMesh.position.y = sceneSize.rootPosition.y;
  87921. };
  87922. /**
  87923. * Get the scene sizes according to the setup.
  87924. */
  87925. EnvironmentHelper.prototype._getSceneSize = function () {
  87926. var groundSize = this._options.groundSize;
  87927. var skyboxSize = this._options.skyboxSize;
  87928. var rootPosition = this._options.rootPosition;
  87929. if (!this._scene.meshes || this._scene.meshes.length === 1) {
  87930. return { groundSize: groundSize, skyboxSize: skyboxSize, rootPosition: rootPosition };
  87931. }
  87932. var sceneExtends = this._scene.getWorldExtends();
  87933. var sceneDiagonal = sceneExtends.max.subtract(sceneExtends.min);
  87934. if (this._options.sizeAuto) {
  87935. if (this._scene.activeCamera instanceof BABYLON.ArcRotateCamera &&
  87936. this._scene.activeCamera.upperRadiusLimit) {
  87937. groundSize = this._scene.activeCamera.upperRadiusLimit * 2;
  87938. skyboxSize = groundSize;
  87939. }
  87940. var sceneDiagonalLenght = sceneDiagonal.length();
  87941. if (sceneDiagonalLenght > groundSize) {
  87942. groundSize = sceneDiagonalLenght * 2;
  87943. skyboxSize = groundSize;
  87944. }
  87945. // 10 % bigger.
  87946. groundSize *= 1.1;
  87947. skyboxSize *= 1.5;
  87948. rootPosition = sceneExtends.min.add(sceneDiagonal.scale(0.5));
  87949. rootPosition.y = sceneExtends.min.y - this._options.groundYBias;
  87950. }
  87951. return { groundSize: groundSize, skyboxSize: skyboxSize, rootPosition: rootPosition };
  87952. };
  87953. /**
  87954. * Setup the ground according to the specified options.
  87955. */
  87956. EnvironmentHelper.prototype._setupGround = function (sceneSize) {
  87957. var _this = this;
  87958. if (!this._ground) {
  87959. this._ground = BABYLON.Mesh.CreatePlane("BackgroundPlane", sceneSize.groundSize, this._scene);
  87960. this._ground.rotation.x = Math.PI / 2; // Face up by default.
  87961. this._ground.parent = this._rootMesh;
  87962. this._ground.onDisposeObservable.add(function () { _this._ground = null; });
  87963. }
  87964. this._ground.receiveShadows = this._options.enableGroundShadow;
  87965. };
  87966. /**
  87967. * Setup the ground material according to the specified options.
  87968. */
  87969. EnvironmentHelper.prototype._setupGroundMaterial = function () {
  87970. if (!this._groundMaterial) {
  87971. this._groundMaterial = new BABYLON.BackgroundMaterial("BackgroundPlaneMaterial", this._scene);
  87972. }
  87973. this._groundMaterial.alpha = this._options.groundOpacity;
  87974. this._groundMaterial.alphaMode = BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF;
  87975. this._groundMaterial.shadowLevel = this._options.groundShadowLevel;
  87976. this._groundMaterial.primaryLevel = 1;
  87977. this._groundMaterial.primaryColor = this._options.groundColor;
  87978. this._groundMaterial.secondaryLevel = 0;
  87979. this._groundMaterial.tertiaryLevel = 0;
  87980. this._groundMaterial.useRGBColor = false;
  87981. this._groundMaterial.enableNoise = true;
  87982. if (this._ground) {
  87983. this._ground.material = this._groundMaterial;
  87984. }
  87985. };
  87986. /**
  87987. * Setup the ground diffuse texture according to the specified options.
  87988. */
  87989. EnvironmentHelper.prototype._setupGroundDiffuseTexture = function () {
  87990. if (!this._groundMaterial) {
  87991. return;
  87992. }
  87993. if (this._groundTexture) {
  87994. return;
  87995. }
  87996. if (this._options.groundTexture instanceof BABYLON.BaseTexture) {
  87997. this._groundMaterial.diffuseTexture = this._options.groundTexture;
  87998. return;
  87999. }
  88000. var diffuseTexture = new BABYLON.Texture(this._options.groundTexture, this._scene);
  88001. diffuseTexture.gammaSpace = false;
  88002. diffuseTexture.hasAlpha = true;
  88003. this._groundMaterial.diffuseTexture = diffuseTexture;
  88004. };
  88005. /**
  88006. * Setup the ground mirror texture according to the specified options.
  88007. */
  88008. EnvironmentHelper.prototype._setupGroundMirrorTexture = function (sceneSize) {
  88009. var wrapping = BABYLON.Texture.CLAMP_ADDRESSMODE;
  88010. if (!this._groundMirror) {
  88011. this._groundMirror = new BABYLON.MirrorTexture("BackgroundPlaneMirrorTexture", { ratio: this._options.groundMirrorSizeRatio }, this._scene, false, this._options.groundMirrorTextureType, BABYLON.Texture.BILINEAR_SAMPLINGMODE, true);
  88012. this._groundMirror.mirrorPlane = new BABYLON.Plane(0, -1, 0, sceneSize.rootPosition.y);
  88013. this._groundMirror.anisotropicFilteringLevel = 1;
  88014. this._groundMirror.wrapU = wrapping;
  88015. this._groundMirror.wrapV = wrapping;
  88016. this._groundMirror.gammaSpace = false;
  88017. if (this._groundMirror.renderList) {
  88018. for (var i = 0; i < this._scene.meshes.length; i++) {
  88019. var mesh = this._scene.meshes[i];
  88020. if (mesh !== this._ground &&
  88021. mesh !== this._skybox &&
  88022. mesh !== this._rootMesh) {
  88023. this._groundMirror.renderList.push(mesh);
  88024. }
  88025. }
  88026. }
  88027. }
  88028. this._groundMirror.clearColor = new BABYLON.Color4(this._options.groundColor.r, this._options.groundColor.g, this._options.groundColor.b, 1);
  88029. this._groundMirror.adaptiveBlurKernel = this._options.groundMirrorBlurKernel;
  88030. };
  88031. /**
  88032. * Setup the ground to receive the mirror texture.
  88033. */
  88034. EnvironmentHelper.prototype._setupMirrorInGroundMaterial = function () {
  88035. if (this._groundMaterial) {
  88036. this._groundMaterial.reflectionTexture = this._groundMirror;
  88037. this._groundMaterial.reflectionFresnel = true;
  88038. this._groundMaterial.reflectionAmount = this._options.groundMirrorAmount;
  88039. this._groundMaterial.reflectionStandardFresnelWeight = this._options.groundMirrorFresnelWeight;
  88040. this._groundMaterial.reflectionFalloffDistance = this._options.groundMirrorFallOffDistance;
  88041. }
  88042. };
  88043. /**
  88044. * Setup the skybox according to the specified options.
  88045. */
  88046. EnvironmentHelper.prototype._setupSkybox = function (sceneSize) {
  88047. var _this = this;
  88048. if (!this._skybox) {
  88049. this._skybox = BABYLON.Mesh.CreateBox("BackgroundSkybox", sceneSize.skyboxSize, this._scene, undefined, BABYLON.Mesh.BACKSIDE);
  88050. this._skybox.onDisposeObservable.add(function () { _this._skybox = null; });
  88051. }
  88052. this._skybox.parent = this._rootMesh;
  88053. };
  88054. /**
  88055. * Setup the skybox material according to the specified options.
  88056. */
  88057. EnvironmentHelper.prototype._setupSkyboxMaterial = function () {
  88058. if (!this._skybox) {
  88059. return;
  88060. }
  88061. if (!this._skyboxMaterial) {
  88062. this._skyboxMaterial = new BABYLON.BackgroundMaterial("BackgroundSkyboxMaterial", this._scene);
  88063. }
  88064. this._skyboxMaterial.useRGBColor = false;
  88065. this._skyboxMaterial.primaryLevel = 1;
  88066. this._skyboxMaterial.primaryColor = this._options.skyboxColor;
  88067. this._skyboxMaterial.secondaryLevel = 0;
  88068. this._skyboxMaterial.tertiaryLevel = 0;
  88069. this._skyboxMaterial.enableNoise = true;
  88070. this._skybox.material = this._skyboxMaterial;
  88071. };
  88072. /**
  88073. * Setup the skybox reflection texture according to the specified options.
  88074. */
  88075. EnvironmentHelper.prototype._setupSkyboxReflectionTexture = function () {
  88076. if (!this._skyboxMaterial) {
  88077. return;
  88078. }
  88079. if (this._skyboxTexture) {
  88080. return;
  88081. }
  88082. if (this._options.skyboxTexture instanceof BABYLON.BaseTexture) {
  88083. this._skyboxMaterial.reflectionTexture = this._skyboxTexture;
  88084. return;
  88085. }
  88086. this._skyboxTexture = new BABYLON.CubeTexture(this._options.skyboxTexture, this._scene);
  88087. this._skyboxTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  88088. this._skyboxTexture.gammaSpace = false;
  88089. this._skyboxMaterial.reflectionTexture = this._skyboxTexture;
  88090. };
  88091. /**
  88092. * Dispose all the elements created by the Helper.
  88093. */
  88094. EnvironmentHelper.prototype.dispose = function () {
  88095. if (this._groundMaterial) {
  88096. this._groundMaterial.dispose(true, true);
  88097. }
  88098. if (this._skyboxMaterial) {
  88099. this._skyboxMaterial.dispose(true, true);
  88100. }
  88101. this._rootMesh.dispose(false);
  88102. };
  88103. /**
  88104. * Default ground texture URL.
  88105. */
  88106. EnvironmentHelper._groundTextureCDNUrl = "https://assets.babylonjs.com/environments/backgroundGround.png";
  88107. /**
  88108. * Default skybox texture URL.
  88109. */
  88110. EnvironmentHelper._skyboxTextureCDNUrl = "https://assets.babylonjs.com/environments/backgroundSkybox.dds";
  88111. /**
  88112. * Default environment texture URL.
  88113. */
  88114. EnvironmentHelper._environmentTextureCDNUrl = "https://assets.babylonjs.com/environments/environmentSpecular.dds";
  88115. return EnvironmentHelper;
  88116. }());
  88117. BABYLON.EnvironmentHelper = EnvironmentHelper;
  88118. })(BABYLON || (BABYLON = {}));
  88119. //# sourceMappingURL=babylon.environmentHelper.js.map
  88120. BABYLON.Effect.ShadersStore={"defaultVertexShader":"#include<__decl__defaultVertex>\n\nattribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\n#endif\n#ifdef TANGENT\nattribute vec4 tangent;\n#endif\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef VERTEXCOLOR\nattribute vec4 color;\n#endif\n#include<helperFunctions>\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif\n#ifdef MAINUV2\nvarying vec2 vMainUV2;\n#endif\n#if defined(DIFFUSE) && DIFFUSEDIRECTUV == 0\nvarying vec2 vDiffuseUV;\n#endif\n#if defined(AMBIENT) && AMBIENTDIRECTUV == 0\nvarying vec2 vAmbientUV;\n#endif\n#if defined(OPACITY) && OPACITYDIRECTUV == 0\nvarying vec2 vOpacityUV;\n#endif\n#if defined(EMISSIVE) && EMISSIVEDIRECTUV == 0\nvarying vec2 vEmissiveUV;\n#endif\n#if defined(LIGHTMAP) && LIGHTMAPDIRECTUV == 0\nvarying vec2 vLightmapUV;\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM) && SPECULARDIRECTUV == 0\nvarying vec2 vSpecularUV;\n#endif\n#if defined(BUMP) && BUMPDIRECTUV == 0\nvarying vec2 vBumpUV;\n#endif\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n#include<bumpVertexDeclaration>\n#include<clipPlaneVertexDeclaration>\n#include<fogVertexDeclaration>\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#include<morphTargetsVertexGlobalDeclaration>\n#include<morphTargetsVertexDeclaration>[0..maxSimultaneousMorphTargets]\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#include<logDepthDeclaration>\nvoid main(void) {\nvec3 positionUpdated=position;\n#ifdef NORMAL \nvec3 normalUpdated=normal;\n#endif\n#ifdef TANGENT\nvec4 tangentUpdated=tangent;\n#endif\n#include<morphTargetsVertex>[0..maxSimultaneousMorphTargets]\n#ifdef REFLECTIONMAP_SKYBOX\nvPositionUVW=positionUpdated;\n#endif \n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(positionUpdated,1.0);\nvec4 worldPos=finalWorld*vec4(positionUpdated,1.0);\nvPositionW=vec3(worldPos);\n#ifdef NORMAL\nmat3 normalWorld=mat3(finalWorld);\n#ifdef NONUNIFORMSCALING\nnormalWorld=transposeMat3(inverseMat3(normalWorld));\n#endif\nvNormalW=normalize(normalWorld*normalUpdated);\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvDirectionW=normalize(vec3(finalWorld*vec4(positionUpdated,0.0)));\n#endif\n\n#ifndef UV1\nvec2 uv=vec2(0.,0.);\n#endif\n#ifndef UV2\nvec2 uv2=vec2(0.,0.);\n#endif\n#ifdef MAINUV1\nvMainUV1=uv;\n#endif\n#ifdef MAINUV2\nvMainUV2=uv2;\n#endif\n#if defined(DIFFUSE) && DIFFUSEDIRECTUV == 0\nif (vDiffuseInfos.x == 0.)\n{\nvDiffuseUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvDiffuseUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(AMBIENT) && AMBIENTDIRECTUV == 0\nif (vAmbientInfos.x == 0.)\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(OPACITY) && OPACITYDIRECTUV == 0\nif (vOpacityInfos.x == 0.)\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(EMISSIVE) && EMISSIVEDIRECTUV == 0\nif (vEmissiveInfos.x == 0.)\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(LIGHTMAP) && LIGHTMAPDIRECTUV == 0\nif (vLightmapInfos.x == 0.)\n{\nvLightmapUV=vec2(lightmapMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvLightmapUV=vec2(lightmapMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM) && SPECULARDIRECTUV == 0\nif (vSpecularInfos.x == 0.)\n{\nvSpecularUV=vec2(specularMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvSpecularUV=vec2(specularMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(BUMP) && BUMPDIRECTUV == 0\nif (vBumpInfos.x == 0.)\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#include<bumpVertex>\n#include<clipPlaneVertex>\n#include<fogVertex>\n#include<shadowsVertex>[0..maxSimultaneousLights]\n#ifdef VERTEXCOLOR\n\nvColor=color;\n#endif\n#include<pointCloudVertex>\n#include<logDepthVertex>\n}","defaultPixelShader":"#include<__decl__defaultFragment>\n#if defined(BUMP) || !defined(NORMAL)\n#extension GL_OES_standard_derivatives : enable\n#endif\n#ifdef LOGARITHMICDEPTH\n#extension GL_EXT_frag_depth : enable\n#endif\n\n#define RECIPROCAL_PI2 0.15915494\nuniform vec3 vEyePosition;\nuniform vec3 vAmbientColor;\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif\n#ifdef MAINUV2\nvarying vec2 vMainUV2;\n#endif\n\n#include<helperFunctions>\n\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#include<lightsFragmentFunctions>\n#include<shadowsFragmentFunctions>\n\n#ifdef DIFFUSE\n#if DIFFUSEDIRECTUV == 1\n#define vDiffuseUV vMainUV1\n#elif DIFFUSEDIRECTUV == 2\n#define vDiffuseUV vMainUV2\n#else\nvarying vec2 vDiffuseUV;\n#endif\nuniform sampler2D diffuseSampler;\n#endif\n#ifdef AMBIENT\n#if AMBIENTDIRECTUV == 1\n#define vAmbientUV vMainUV1\n#elif AMBIENTDIRECTUV == 2\n#define vAmbientUV vMainUV2\n#else\nvarying vec2 vAmbientUV;\n#endif\nuniform sampler2D ambientSampler;\n#endif\n#ifdef OPACITY \n#if OPACITYDIRECTUV == 1\n#define vOpacityUV vMainUV1\n#elif OPACITYDIRECTUV == 2\n#define vOpacityUV vMainUV2\n#else\nvarying vec2 vOpacityUV;\n#endif\nuniform sampler2D opacitySampler;\n#endif\n#ifdef EMISSIVE\n#if EMISSIVEDIRECTUV == 1\n#define vEmissiveUV vMainUV1\n#elif EMISSIVEDIRECTUV == 2\n#define vEmissiveUV vMainUV2\n#else\nvarying vec2 vEmissiveUV;\n#endif\nuniform sampler2D emissiveSampler;\n#endif\n#ifdef LIGHTMAP\n#if LIGHTMAPDIRECTUV == 1\n#define vLightmapUV vMainUV1\n#elif LIGHTMAPDIRECTUV == 2\n#define vLightmapUV vMainUV2\n#else\nvarying vec2 vLightmapUV;\n#endif\nuniform sampler2D lightmapSampler;\n#endif\n#ifdef REFRACTION\n#ifdef REFRACTIONMAP_3D\nuniform samplerCube refractionCubeSampler;\n#else\nuniform sampler2D refraction2DSampler;\n#endif\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM)\n#if SPECULARDIRECTUV == 1\n#define vSpecularUV vMainUV1\n#elif SPECULARDIRECTUV == 2\n#define vSpecularUV vMainUV2\n#else\nvarying vec2 vSpecularUV;\n#endif\nuniform sampler2D specularSampler;\n#endif\n\n#include<fresnelFunction>\n\n#ifdef REFLECTION\n#ifdef REFLECTIONMAP_3D\nuniform samplerCube reflectionCubeSampler;\n#else\nuniform sampler2D reflection2DSampler;\n#endif\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#else\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#endif\n#include<reflectionFunction>\n#endif\n#include<imageProcessingDeclaration>\n#include<imageProcessingFunctions>\n#include<bumpFragmentFunctions>\n#include<clipPlaneFragmentDeclaration>\n#include<logDepthDeclaration>\n#include<fogFragmentDeclaration>\nvoid main(void) {\n#include<clipPlaneFragment>\nvec3 viewDirectionW=normalize(vEyePosition-vPositionW);\n\nvec4 baseColor=vec4(1.,1.,1.,1.);\nvec3 diffuseColor=vDiffuseColor.rgb;\n\nfloat alpha=vDiffuseColor.a;\n\n#ifdef NORMAL\nvec3 normalW=normalize(vNormalW);\n#else\nvec3 normalW=normalize(-cross(dFdx(vPositionW),dFdy(vPositionW)));\n#endif\n#include<bumpFragment>\n#ifdef TWOSIDEDLIGHTING\nnormalW=gl_FrontFacing ? normalW : -normalW;\n#endif\n#ifdef DIFFUSE\nbaseColor=texture2D(diffuseSampler,vDiffuseUV+uvOffset);\n#ifdef ALPHATEST\nif (baseColor.a<0.4)\ndiscard;\n#endif\n#ifdef ALPHAFROMDIFFUSE\nalpha*=baseColor.a;\n#endif\nbaseColor.rgb*=vDiffuseInfos.y;\n#endif\n#include<depthPrePass>\n#ifdef VERTEXCOLOR\nbaseColor.rgb*=vColor.rgb;\n#endif\n\nvec3 baseAmbientColor=vec3(1.,1.,1.);\n#ifdef AMBIENT\nbaseAmbientColor=texture2D(ambientSampler,vAmbientUV+uvOffset).rgb*vAmbientInfos.y;\n#endif\n\n#ifdef SPECULARTERM\nfloat glossiness=vSpecularColor.a;\nvec3 specularColor=vSpecularColor.rgb;\n#ifdef SPECULAR\nvec4 specularMapColor=texture2D(specularSampler,vSpecularUV+uvOffset);\nspecularColor=specularMapColor.rgb;\n#ifdef GLOSSINESS\nglossiness=glossiness*specularMapColor.a;\n#endif\n#endif\n#else\nfloat glossiness=0.;\n#endif\n\nvec3 diffuseBase=vec3(0.,0.,0.);\nlightingInfo info;\n#ifdef SPECULARTERM\nvec3 specularBase=vec3(0.,0.,0.);\n#endif\nfloat shadow=1.;\n#ifdef LIGHTMAP\nvec3 lightmapColor=texture2D(lightmapSampler,vLightmapUV+uvOffset).rgb*vLightmapInfos.y;\n#endif\n#include<lightFragment>[0..maxSimultaneousLights]\n\nvec3 refractionColor=vec3(0.,0.,0.);\n#ifdef REFRACTION\nvec3 refractionVector=normalize(refract(-viewDirectionW,normalW,vRefractionInfos.y));\n#ifdef REFRACTIONMAP_3D\nrefractionVector.y=refractionVector.y*vRefractionInfos.w;\nif (dot(refractionVector,viewDirectionW)<1.0)\n{\nrefractionColor=textureCube(refractionCubeSampler,refractionVector).rgb*vRefractionInfos.x;\n}\n#else\nvec3 vRefractionUVW=vec3(refractionMatrix*(view*vec4(vPositionW+refractionVector*vRefractionInfos.z,1.0)));\nvec2 refractionCoords=vRefractionUVW.xy/vRefractionUVW.z;\nrefractionCoords.y=1.0-refractionCoords.y;\nrefractionColor=texture2D(refraction2DSampler,refractionCoords).rgb*vRefractionInfos.x;\n#endif\n#endif\n\nvec3 reflectionColor=vec3(0.,0.,0.);\n#ifdef REFLECTION\nvec3 vReflectionUVW=computeReflectionCoords(vec4(vPositionW,1.0),normalW);\n#ifdef REFLECTIONMAP_3D\n#ifdef ROUGHNESS\nfloat bias=vReflectionInfos.y;\n#ifdef SPECULARTERM\n#ifdef SPECULAR\n#ifdef GLOSSINESS\nbias*=(1.0-specularMapColor.a);\n#endif\n#endif\n#endif\nreflectionColor=textureCube(reflectionCubeSampler,vReflectionUVW,bias).rgb*vReflectionInfos.x;\n#else\nreflectionColor=textureCube(reflectionCubeSampler,vReflectionUVW).rgb*vReflectionInfos.x;\n#endif\n#else\nvec2 coords=vReflectionUVW.xy;\n#ifdef REFLECTIONMAP_PROJECTION\ncoords/=vReflectionUVW.z;\n#endif\ncoords.y=1.0-coords.y;\nreflectionColor=texture2D(reflection2DSampler,coords).rgb*vReflectionInfos.x;\n#endif\n#ifdef REFLECTIONFRESNEL\nfloat reflectionFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,reflectionRightColor.a,reflectionLeftColor.a);\n#ifdef REFLECTIONFRESNELFROMSPECULAR\n#ifdef SPECULARTERM\nreflectionColor*=specularColor.rgb*(1.0-reflectionFresnelTerm)+reflectionFresnelTerm*reflectionRightColor.rgb;\n#else\nreflectionColor*=reflectionLeftColor.rgb*(1.0-reflectionFresnelTerm)+reflectionFresnelTerm*reflectionRightColor.rgb;\n#endif\n#else\nreflectionColor*=reflectionLeftColor.rgb*(1.0-reflectionFresnelTerm)+reflectionFresnelTerm*reflectionRightColor.rgb;\n#endif\n#endif\n#endif\n#ifdef REFRACTIONFRESNEL\nfloat refractionFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,refractionRightColor.a,refractionLeftColor.a);\nrefractionColor*=refractionLeftColor.rgb*(1.0-refractionFresnelTerm)+refractionFresnelTerm*refractionRightColor.rgb;\n#endif\n#ifdef OPACITY\nvec4 opacityMap=texture2D(opacitySampler,vOpacityUV+uvOffset);\n#ifdef OPACITYRGB\nopacityMap.rgb=opacityMap.rgb*vec3(0.3,0.59,0.11);\nalpha*=(opacityMap.x+opacityMap.y+opacityMap.z)* vOpacityInfos.y;\n#else\nalpha*=opacityMap.a*vOpacityInfos.y;\n#endif\n#endif\n#ifdef VERTEXALPHA\nalpha*=vColor.a;\n#endif\n#ifdef OPACITYFRESNEL\nfloat opacityFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,opacityParts.z,opacityParts.w);\nalpha+=opacityParts.x*(1.0-opacityFresnelTerm)+opacityFresnelTerm*opacityParts.y;\n#endif\n\nvec3 emissiveColor=vEmissiveColor;\n#ifdef EMISSIVE\nemissiveColor+=texture2D(emissiveSampler,vEmissiveUV+uvOffset).rgb*vEmissiveInfos.y;\n#endif\n#ifdef EMISSIVEFRESNEL\nfloat emissiveFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,emissiveRightColor.a,emissiveLeftColor.a);\nemissiveColor*=emissiveLeftColor.rgb*(1.0-emissiveFresnelTerm)+emissiveFresnelTerm*emissiveRightColor.rgb;\n#endif\n\n#ifdef DIFFUSEFRESNEL\nfloat diffuseFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,diffuseRightColor.a,diffuseLeftColor.a);\ndiffuseBase*=diffuseLeftColor.rgb*(1.0-diffuseFresnelTerm)+diffuseFresnelTerm*diffuseRightColor.rgb;\n#endif\n\n#ifdef EMISSIVEASILLUMINATION\nvec3 finalDiffuse=clamp(diffuseBase*diffuseColor+vAmbientColor,0.0,1.0)*baseColor.rgb;\n#else\n#ifdef LINKEMISSIVEWITHDIFFUSE\nvec3 finalDiffuse=clamp((diffuseBase+emissiveColor)*diffuseColor+vAmbientColor,0.0,1.0)*baseColor.rgb;\n#else\nvec3 finalDiffuse=clamp(diffuseBase*diffuseColor+emissiveColor+vAmbientColor,0.0,1.0)*baseColor.rgb;\n#endif\n#endif\n#ifdef SPECULARTERM\nvec3 finalSpecular=specularBase*specularColor;\n#ifdef SPECULAROVERALPHA\nalpha=clamp(alpha+dot(finalSpecular,vec3(0.3,0.59,0.11)),0.,1.);\n#endif\n#else\nvec3 finalSpecular=vec3(0.0);\n#endif\n#ifdef REFLECTIONOVERALPHA\nalpha=clamp(alpha+dot(reflectionColor,vec3(0.3,0.59,0.11)),0.,1.);\n#endif\n\n#ifdef EMISSIVEASILLUMINATION\nvec4 color=vec4(clamp(finalDiffuse*baseAmbientColor+finalSpecular+reflectionColor+emissiveColor+refractionColor,0.0,1.0),alpha);\n#else\nvec4 color=vec4(finalDiffuse*baseAmbientColor+finalSpecular+reflectionColor+refractionColor,alpha);\n#endif\n\n#ifdef LIGHTMAP\n#ifndef LIGHTMAPEXCLUDED\n#ifdef USELIGHTMAPASSHADOWMAP\ncolor.rgb*=lightmapColor;\n#else\ncolor.rgb+=lightmapColor;\n#endif\n#endif\n#endif\n#include<logDepthFragment>\n#include<fogFragment>\n\n\n#ifdef IMAGEPROCESSINGPOSTPROCESS\ncolor.rgb=toLinearSpace(color.rgb);\n#else\n#ifdef IMAGEPROCESSING\ncolor.rgb=toLinearSpace(color.rgb);\ncolor=applyImageProcessing(color);\n#endif\n#endif\n#ifdef PREMULTIPLYALPHA\n\ncolor.rgb*=color.a;\n#endif\ngl_FragColor=color;\n}","pbrVertexShader":"precision highp float;\n#include<__decl__pbrVertex>\n\nattribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\n#endif\n#ifdef TANGENT\nattribute vec4 tangent;\n#endif\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif\n#ifdef MAINUV2\nvarying vec2 vMainUV2; \n#endif \n#ifdef VERTEXCOLOR\nattribute vec4 color;\n#endif\n#include<helperFunctions>\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\n#if defined(ALBEDO) && ALBEDODIRECTUV == 0\nvarying vec2 vAlbedoUV;\n#endif\n#if defined(AMBIENT) && AMBIENTDIRECTUV == 0\nvarying vec2 vAmbientUV;\n#endif\n#if defined(OPACITY) && OPACITYDIRECTUV == 0\nvarying vec2 vOpacityUV;\n#endif\n#if defined(EMISSIVE) && EMISSIVEDIRECTUV == 0\nvarying vec2 vEmissiveUV;\n#endif\n#if defined(LIGHTMAP) && LIGHTMAPDIRECTUV == 0\nvarying vec2 vLightmapUV;\n#endif\n#if defined(REFLECTIVITY) && REFLECTIVITYDIRECTUV == 0\nvarying vec2 vReflectivityUV;\n#endif\n#if defined(MICROSURFACEMAP) && MICROSURFACEMAPDIRECTUV == 0\nvarying vec2 vMicroSurfaceSamplerUV;\n#endif\n#if defined(BUMP) && BUMPDIRECTUV == 0\nvarying vec2 vBumpUV;\n#endif\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#if defined(USESPHERICALFROMREFLECTIONMAP) && defined(USESPHERICALINVERTEX)\nvarying vec3 vEnvironmentIrradiance;\n#include<harmonicsFunctions>\n#endif\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n#include<bumpVertexDeclaration>\n#include<clipPlaneVertexDeclaration>\n#include<fogVertexDeclaration>\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#include<morphTargetsVertexGlobalDeclaration>\n#include<morphTargetsVertexDeclaration>[0..maxSimultaneousMorphTargets]\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#include<logDepthDeclaration>\nvoid main(void) {\nvec3 positionUpdated=position;\n#ifdef NORMAL\nvec3 normalUpdated=normal;\n#endif\n#ifdef TANGENT\nvec4 tangentUpdated=tangent;\n#endif\n#include<morphTargetsVertex>[0..maxSimultaneousMorphTargets]\n#ifdef REFLECTIONMAP_SKYBOX\nvPositionUVW=positionUpdated;\n#endif \n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(positionUpdated,1.0);\nvec4 worldPos=finalWorld*vec4(positionUpdated,1.0);\nvPositionW=vec3(worldPos);\n#ifdef NORMAL\nmat3 normalWorld=mat3(finalWorld);\n#ifdef NONUNIFORMSCALING\nnormalWorld=transposeMat3(inverseMat3(normalWorld));\n#endif\nvNormalW=normalize(normalWorld*normalUpdated);\n#if defined(USESPHERICALFROMREFLECTIONMAP) && defined(USESPHERICALINVERTEX)\nvec3 reflectionVector=vec3(reflectionMatrix*vec4(vNormalW,0)).xyz;\n#ifdef REFLECTIONMAP_OPPOSITEZ\nreflectionVector.z*=-1.0;\n#endif\nvEnvironmentIrradiance=environmentIrradianceJones(reflectionVector);\n#endif\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvDirectionW=normalize(vec3(finalWorld*vec4(positionUpdated,0.0)));\n#endif\n\n#ifndef UV1\nvec2 uv=vec2(0.,0.);\n#endif\n#ifndef UV2\nvec2 uv2=vec2(0.,0.);\n#endif\n#ifdef MAINUV1\nvMainUV1=uv;\n#endif \n#ifdef MAINUV2\nvMainUV2=uv2;\n#endif \n#if defined(ALBEDO) && ALBEDODIRECTUV == 0 \nif (vAlbedoInfos.x == 0.)\n{\nvAlbedoUV=vec2(albedoMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvAlbedoUV=vec2(albedoMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(AMBIENT) && AMBIENTDIRECTUV == 0 \nif (vAmbientInfos.x == 0.)\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(OPACITY) && OPACITYDIRECTUV == 0 \nif (vOpacityInfos.x == 0.)\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(EMISSIVE) && EMISSIVEDIRECTUV == 0 \nif (vEmissiveInfos.x == 0.)\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(LIGHTMAP) && LIGHTMAPDIRECTUV == 0 \nif (vLightmapInfos.x == 0.)\n{\nvLightmapUV=vec2(lightmapMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvLightmapUV=vec2(lightmapMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(REFLECTIVITY) && REFLECTIVITYDIRECTUV == 0 \nif (vReflectivityInfos.x == 0.)\n{\nvReflectivityUV=vec2(reflectivityMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvReflectivityUV=vec2(reflectivityMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(MICROSURFACEMAP) && MICROSURFACEMAPDIRECTUV == 0 \nif (vMicroSurfaceSamplerInfos.x == 0.)\n{\nvMicroSurfaceSamplerUV=vec2(microSurfaceSamplerMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvMicroSurfaceSamplerUV=vec2(microSurfaceSamplerMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(BUMP) && BUMPDIRECTUV == 0 \nif (vBumpInfos.x == 0.)\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n\n#include<bumpVertex>\n\n#include<clipPlaneVertex>\n\n#include<fogVertex>\n\n#include<shadowsVertex>[0..maxSimultaneousLights]\n\n#ifdef VERTEXCOLOR\nvColor=color;\n#endif\n\n#ifdef POINTSIZE\ngl_PointSize=pointSize;\n#endif\n\n#include<logDepthVertex>\n}","pbrPixelShader":"#if defined(BUMP) || !defined(NORMAL) || defined(FORCENORMALFORWARD)\n#extension GL_OES_standard_derivatives : enable\n#endif\n#ifdef LODBASEDMICROSFURACE\n#extension GL_EXT_shader_texture_lod : enable\n#endif\n#ifdef LOGARITHMICDEPTH\n#extension GL_EXT_frag_depth : enable\n#endif\nprecision highp float;\n#include<__decl__pbrFragment>\nuniform vec4 vEyePosition;\nuniform vec3 vAmbientColor;\nuniform vec4 vCameraInfos;\n\nvarying vec3 vPositionW;\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif \n#ifdef MAINUV2 \nvarying vec2 vMainUV2;\n#endif \n#ifdef NORMAL\nvarying vec3 vNormalW;\n#if defined(USESPHERICALFROMREFLECTIONMAP) && defined(USESPHERICALINVERTEX)\nvarying vec3 vEnvironmentIrradiance;\n#endif\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n\n#ifdef ALBEDO\n#if ALBEDODIRECTUV == 1\n#define vAlbedoUV vMainUV1\n#elif ALBEDODIRECTUV == 2\n#define vAlbedoUV vMainUV2\n#else\nvarying vec2 vAlbedoUV;\n#endif\nuniform sampler2D albedoSampler;\n#endif\n#ifdef AMBIENT\n#if AMBIENTDIRECTUV == 1\n#define vAmbientUV vMainUV1\n#elif AMBIENTDIRECTUV == 2\n#define vAmbientUV vMainUV2\n#else\nvarying vec2 vAmbientUV;\n#endif\nuniform sampler2D ambientSampler;\n#endif\n#ifdef OPACITY\n#if OPACITYDIRECTUV == 1\n#define vOpacityUV vMainUV1\n#elif OPACITYDIRECTUV == 2\n#define vOpacityUV vMainUV2\n#else\nvarying vec2 vOpacityUV;\n#endif\nuniform sampler2D opacitySampler;\n#endif\n#ifdef EMISSIVE\n#if EMISSIVEDIRECTUV == 1\n#define vEmissiveUV vMainUV1\n#elif EMISSIVEDIRECTUV == 2\n#define vEmissiveUV vMainUV2\n#else\nvarying vec2 vEmissiveUV;\n#endif\nuniform sampler2D emissiveSampler;\n#endif\n#ifdef LIGHTMAP\n#if LIGHTMAPDIRECTUV == 1\n#define vLightmapUV vMainUV1\n#elif LIGHTMAPDIRECTUV == 2\n#define vLightmapUV vMainUV2\n#else\nvarying vec2 vLightmapUV;\n#endif\nuniform sampler2D lightmapSampler;\n#endif\n#ifdef REFLECTIVITY\n#if REFLECTIVITYDIRECTUV == 1\n#define vReflectivityUV vMainUV1\n#elif REFLECTIVITYDIRECTUV == 2\n#define vReflectivityUV vMainUV2\n#else\nvarying vec2 vReflectivityUV;\n#endif\nuniform sampler2D reflectivitySampler;\n#endif\n#ifdef MICROSURFACEMAP\n#if MICROSURFACEMAPDIRECTUV == 1\n#define vMicroSurfaceSamplerUV vMainUV1\n#elif MICROSURFACEMAPDIRECTUV == 2\n#define vMicroSurfaceSamplerUV vMainUV2\n#else\nvarying vec2 vMicroSurfaceSamplerUV;\n#endif\nuniform sampler2D microSurfaceSampler;\n#endif\n\n#ifdef REFRACTION\n#ifdef REFRACTIONMAP_3D\n#define sampleRefraction(s,c) textureCube(s,c)\nuniform samplerCube refractionSampler;\n#ifdef LODBASEDMICROSFURACE\n#define sampleRefractionLod(s,c,l) textureCubeLodEXT(s,c,l)\n#else\nuniform samplerCube refractionSamplerLow;\nuniform samplerCube refractionSamplerHigh;\n#endif\n#else\n#define sampleRefraction(s,c) texture2D(s,c)\nuniform sampler2D refractionSampler;\n#ifdef LODBASEDMICROSFURACE\n#define sampleRefractionLod(s,c,l) texture2DLodEXT(s,c,l)\n#else\nuniform samplerCube refractionSamplerLow;\nuniform samplerCube refractionSamplerHigh;\n#endif\n#endif\n#endif\n\n#ifdef REFLECTION\n#ifdef REFLECTIONMAP_3D\n#define sampleReflection(s,c) textureCube(s,c)\nuniform samplerCube reflectionSampler;\n#ifdef LODBASEDMICROSFURACE\n#define sampleReflectionLod(s,c,l) textureCubeLodEXT(s,c,l)\n#else\nuniform samplerCube reflectionSamplerLow;\nuniform samplerCube reflectionSamplerHigh;\n#endif\n#else\n#define sampleReflection(s,c) texture2D(s,c)\nuniform sampler2D reflectionSampler;\n#ifdef LODBASEDMICROSFURACE\n#define sampleReflectionLod(s,c,l) texture2DLodEXT(s,c,l)\n#else\nuniform samplerCube reflectionSamplerLow;\nuniform samplerCube reflectionSamplerHigh;\n#endif\n#endif\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#else\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#endif\n#include<reflectionFunction>\n#endif\n#ifdef ENVIRONMENTBRDF\nuniform sampler2D environmentBrdfSampler;\n#endif\n\n#ifndef FROMLINEARSPACE\n#define FROMLINEARSPACE;\n#endif\n#include<imageProcessingDeclaration>\n#include<helperFunctions>\n#include<imageProcessingFunctions>\n\n#include<shadowsFragmentFunctions>\n#include<pbrFunctions>\n#include<harmonicsFunctions>\n#include<pbrLightFunctions>\n#include<bumpFragmentFunctions>\n#include<clipPlaneFragmentDeclaration>\n#include<logDepthDeclaration>\n\n#include<fogFragmentDeclaration>\nvoid main(void) {\n#include<clipPlaneFragment>\n\n\nvec3 viewDirectionW=normalize(vEyePosition.xyz-vPositionW);\n#ifdef NORMAL\nvec3 normalW=normalize(vNormalW);\n#else\nvec3 normalW=normalize(cross(dFdx(vPositionW),dFdy(vPositionW)))*vEyePosition.w;\n#endif\n#include<bumpFragment>\n#if defined(FORCENORMALFORWARD) && defined(NORMAL)\nvec3 faceNormal=normalize(cross(dFdx(vPositionW),dFdy(vPositionW)))*vEyePosition.w;\n#if defined(TWOSIDEDLIGHTING)\nfaceNormal=gl_FrontFacing ? faceNormal : -faceNormal;\n#endif\nnormalW*=sign(dot(normalW,faceNormal));\n#endif\n#if defined(TWOSIDEDLIGHTING) && defined(NORMAL)\nnormalW=gl_FrontFacing ? normalW : -normalW;\n#endif\n\n\nvec3 surfaceAlbedo=vAlbedoColor.rgb;\n\nfloat alpha=vAlbedoColor.a;\n#ifdef ALBEDO\nvec4 albedoTexture=texture2D(albedoSampler,vAlbedoUV+uvOffset);\n#if defined(ALPHAFROMALBEDO) || defined(ALPHATEST)\nalpha*=albedoTexture.a;\n#endif\nsurfaceAlbedo*=toLinearSpace(albedoTexture.rgb);\nsurfaceAlbedo*=vAlbedoInfos.y;\n#endif\n\n#ifdef OPACITY\nvec4 opacityMap=texture2D(opacitySampler,vOpacityUV+uvOffset);\n#ifdef OPACITYRGB\nalpha=getLuminance(opacityMap.rgb);\n#else\nalpha*=opacityMap.a;\n#endif\nalpha*=vOpacityInfos.y;\n#endif\n#ifdef VERTEXALPHA\nalpha*=vColor.a;\n#endif\n#if !defined(LINKREFRACTIONTOTRANSPARENCY) && !defined(ALPHAFRESNEL)\n#ifdef ALPHATEST\nif (alpha<=ALPHATESTVALUE)\ndiscard;\n#ifndef ALPHABLEND\n\nalpha=1.0;\n#endif\n#endif\n#endif\n#include<depthPrePass>\n#ifdef VERTEXCOLOR\nsurfaceAlbedo*=vColor.rgb;\n#endif\n\nvec3 ambientOcclusionColor=vec3(1.,1.,1.);\n#ifdef AMBIENT\nvec3 ambientOcclusionColorMap=texture2D(ambientSampler,vAmbientUV+uvOffset).rgb*vAmbientInfos.y;\n#ifdef AMBIENTINGRAYSCALE\nambientOcclusionColorMap=vec3(ambientOcclusionColorMap.r,ambientOcclusionColorMap.r,ambientOcclusionColorMap.r);\n#endif\nambientOcclusionColor=mix(ambientOcclusionColor,ambientOcclusionColorMap,vAmbientInfos.z);\n#endif\n\nfloat microSurface=vReflectivityColor.a;\nvec3 surfaceReflectivityColor=vReflectivityColor.rgb;\n#ifdef METALLICWORKFLOW\nvec2 metallicRoughness=surfaceReflectivityColor.rg;\n#ifdef REFLECTIVITY\nvec4 surfaceMetallicColorMap=texture2D(reflectivitySampler,vReflectivityUV+uvOffset);\n#ifdef AOSTOREINMETALMAPRED\nvec3 aoStoreInMetalMap=vec3(surfaceMetallicColorMap.r,surfaceMetallicColorMap.r,surfaceMetallicColorMap.r);\nambientOcclusionColor=mix(ambientOcclusionColor,aoStoreInMetalMap,vReflectivityInfos.z);\n#endif\n#ifdef METALLNESSSTOREINMETALMAPBLUE\nmetallicRoughness.r*=surfaceMetallicColorMap.b;\n#else\nmetallicRoughness.r*=surfaceMetallicColorMap.r;\n#endif\n#ifdef ROUGHNESSSTOREINMETALMAPALPHA\nmetallicRoughness.g*=surfaceMetallicColorMap.a;\n#else\n#ifdef ROUGHNESSSTOREINMETALMAPGREEN\nmetallicRoughness.g*=surfaceMetallicColorMap.g;\n#endif\n#endif\n#endif\n#ifdef MICROSURFACEMAP\nvec4 microSurfaceTexel=texture2D(microSurfaceSampler,vMicroSurfaceSamplerUV+uvOffset)*vMicroSurfaceSamplerInfos.y;\nmetallicRoughness.g*=microSurfaceTexel.r;\n#endif\n\nmicroSurface=1.0-metallicRoughness.g;\n\nvec3 baseColor=surfaceAlbedo;\n\n\nconst vec3 DefaultSpecularReflectanceDielectric=vec3(0.04,0.04,0.04);\n\nsurfaceAlbedo=mix(baseColor.rgb*(1.0-DefaultSpecularReflectanceDielectric.r),vec3(0.,0.,0.),metallicRoughness.r);\n\nsurfaceReflectivityColor=mix(DefaultSpecularReflectanceDielectric,baseColor,metallicRoughness.r);\n#else\n#ifdef REFLECTIVITY\nvec4 surfaceReflectivityColorMap=texture2D(reflectivitySampler,vReflectivityUV+uvOffset);\nsurfaceReflectivityColor*=toLinearSpace(surfaceReflectivityColorMap.rgb);\nsurfaceReflectivityColor*=vReflectivityInfos.y;\n#ifdef MICROSURFACEFROMREFLECTIVITYMAP\nmicroSurface*=surfaceReflectivityColorMap.a;\nmicroSurface*=vReflectivityInfos.z;\n#else\n#ifdef MICROSURFACEAUTOMATIC\nmicroSurface*=computeDefaultMicroSurface(microSurface,surfaceReflectivityColor);\n#endif\n#ifdef MICROSURFACEMAP\nvec4 microSurfaceTexel=texture2D(microSurfaceSampler,vMicroSurfaceSamplerUV+uvOffset)*vMicroSurfaceSamplerInfos.y;\nmicroSurface*=microSurfaceTexel.r;\n#endif\n#endif\n#endif\n#endif\n\nmicroSurface=clamp(microSurface,0.,1.);\n\nfloat roughness=1.-microSurface;\n\n#ifdef ALPHAFRESNEL\n#if defined(ALPHATEST) || defined(ALPHABLEND)\n\n\n\nfloat opacityPerceptual=alpha;\n#ifdef LINEARALPHAFRESNEL\nfloat opacity0=opacityPerceptual;\n#else\nfloat opacity0=opacityPerceptual*opacityPerceptual;\n#endif\nfloat opacity90=fresnelGrazingReflectance(opacity0);\nvec3 normalForward=faceforward(normalW,-viewDirectionW,normalW);\n\nalpha=fresnelSchlickEnvironmentGGX(clamp(dot(viewDirectionW,normalForward),0.0,1.0),vec3(opacity0),vec3(opacity90),sqrt(microSurface)).x;\n#ifdef ALPHATEST\nif (alpha<=ALPHATESTVALUE)\ndiscard;\n#ifndef ALPHABLEND\n\nalpha=1.0;\n#endif\n#endif\n#endif\n#endif\n\n\nfloat NdotVUnclamped=dot(normalW,viewDirectionW);\nfloat NdotV=clamp(NdotVUnclamped,0.,1.)+0.00001;\nfloat alphaG=convertRoughnessToAverageSlope(roughness);\n\n#ifdef REFRACTION\nvec3 environmentRefraction=vec3(0.,0.,0.);\nvec3 refractionVector=refract(-viewDirectionW,normalW,vRefractionInfos.y);\n#ifdef REFRACTIONMAP_OPPOSITEZ\nrefractionVector.z*=-1.0;\n#endif\n\n#ifdef REFRACTIONMAP_3D\nrefractionVector.y=refractionVector.y*vRefractionInfos.w;\nvec3 refractionCoords=refractionVector;\nrefractionCoords=vec3(refractionMatrix*vec4(refractionCoords,0));\n#else\nvec3 vRefractionUVW=vec3(refractionMatrix*(view*vec4(vPositionW+refractionVector*vRefractionInfos.z,1.0)));\nvec2 refractionCoords=vRefractionUVW.xy/vRefractionUVW.z;\nrefractionCoords.y=1.0-refractionCoords.y;\n#endif\n#ifdef LODINREFRACTIONALPHA\nfloat refractionLOD=getLodFromAlphaG(vRefractionMicrosurfaceInfos.x,alphaG,NdotVUnclamped);\n#else\nfloat refractionLOD=getLodFromAlphaG(vRefractionMicrosurfaceInfos.x,alphaG,1.0);\n#endif\n#ifdef LODBASEDMICROSFURACE\n\nrefractionLOD=refractionLOD*vRefractionMicrosurfaceInfos.y+vRefractionMicrosurfaceInfos.z;\n#ifdef LODINREFRACTIONALPHA\n\n\n\n\n\n\n\n\n\nfloat automaticRefractionLOD=UNPACK_LOD(sampleRefraction(refractionSampler,refractionCoords).a);\nfloat requestedRefractionLOD=max(automaticRefractionLOD,refractionLOD);\n#else\nfloat requestedRefractionLOD=refractionLOD;\n#endif\nenvironmentRefraction=sampleRefractionLod(refractionSampler,refractionCoords,requestedRefractionLOD).rgb;\n#else\nfloat lodRefractionNormalized=clamp(refractionLOD/log2(vRefractionMicrosurfaceInfos.x),0.,1.);\nfloat lodRefractionNormalizedDoubled=lodRefractionNormalized*2.0;\nvec3 environmentRefractionMid=sampleRefraction(refractionSampler,refractionCoords).rgb;\nif(lodRefractionNormalizedDoubled<1.0){\nenvironmentRefraction=mix(\nsampleRefraction(refractionSamplerHigh,refractionCoords).rgb,\nenvironmentRefractionMid,\nlodRefractionNormalizedDoubled\n);\n}else{\nenvironmentRefraction=mix(\nenvironmentRefractionMid,\nsampleRefraction(refractionSamplerLow,refractionCoords).rgb,\nlodRefractionNormalizedDoubled-1.0\n);\n}\n#endif\n#ifdef GAMMAREFRACTION\nenvironmentRefraction=toLinearSpace(environmentRefraction.rgb);\n#endif\n\nenvironmentRefraction*=vRefractionInfos.x;\n#endif\n\n#ifdef REFLECTION\nvec3 environmentRadiance=vec3(0.,0.,0.);\nvec3 environmentIrradiance=vec3(0.,0.,0.);\nvec3 reflectionVector=computeReflectionCoords(vec4(vPositionW,1.0),normalW);\n#ifdef REFLECTIONMAP_OPPOSITEZ\nreflectionVector.z*=-1.0;\n#endif\n\n#ifdef REFLECTIONMAP_3D\nvec3 reflectionCoords=reflectionVector;\n#else\nvec2 reflectionCoords=reflectionVector.xy;\n#ifdef REFLECTIONMAP_PROJECTION\nreflectionCoords/=reflectionVector.z;\n#endif\nreflectionCoords.y=1.0-reflectionCoords.y;\n#endif\n#if defined(LODINREFLECTIONALPHA) && !defined(REFLECTIONMAP_SKYBOX)\nfloat reflectionLOD=getLodFromAlphaG(vReflectionMicrosurfaceInfos.x,alphaG,NdotVUnclamped);\n#else\nfloat reflectionLOD=getLodFromAlphaG(vReflectionMicrosurfaceInfos.x,alphaG,1.);\n#endif\n#ifdef LODBASEDMICROSFURACE\n\nreflectionLOD=reflectionLOD*vReflectionMicrosurfaceInfos.y+vReflectionMicrosurfaceInfos.z;\n#ifdef LODINREFLECTIONALPHA\n\n\n\n\n\n\n\n\n\nfloat automaticReflectionLOD=UNPACK_LOD(sampleReflection(reflectionSampler,reflectionCoords).a);\nfloat requestedReflectionLOD=max(automaticReflectionLOD,reflectionLOD);\n#else\nfloat requestedReflectionLOD=reflectionLOD;\n#endif\nenvironmentRadiance=sampleReflectionLod(reflectionSampler,reflectionCoords,requestedReflectionLOD).rgb;\n#else\nfloat lodReflectionNormalized=clamp(reflectionLOD/log2(vReflectionMicrosurfaceInfos.x),0.,1.);\nfloat lodReflectionNormalizedDoubled=lodReflectionNormalized*2.0;\nvec3 environmentSpecularMid=sampleReflection(reflectionSampler,reflectionCoords).rgb;\nif(lodReflectionNormalizedDoubled<1.0){\nenvironmentRadiance=mix(\nsampleReflection(reflectionSamplerHigh,reflectionCoords).rgb,\nenvironmentSpecularMid,\nlodReflectionNormalizedDoubled\n);\n}else{\nenvironmentRadiance=mix(\nenvironmentSpecularMid,\nsampleReflection(reflectionSamplerLow,reflectionCoords).rgb,\nlodReflectionNormalizedDoubled-1.0\n);\n}\n#endif\n#ifdef GAMMAREFLECTION\nenvironmentRadiance=toLinearSpace(environmentRadiance.rgb);\n#endif\n\n#ifdef USESPHERICALFROMREFLECTIONMAP\n#if defined(NORMAL) && defined(USESPHERICALINVERTEX)\nenvironmentIrradiance=vEnvironmentIrradiance;\n#else\nvec3 irradianceVector=vec3(reflectionMatrix*vec4(normalW,0)).xyz;\n#ifdef REFLECTIONMAP_OPPOSITEZ\nirradianceVector.z*=-1.0;\n#endif\nenvironmentIrradiance=environmentIrradianceJones(irradianceVector);\n#endif\n#endif\n\nenvironmentRadiance*=vReflectionInfos.x;\nenvironmentRadiance*=vReflectionColor.rgb;\nenvironmentIrradiance*=vReflectionColor.rgb;\n#endif\n\n\n\nfloat reflectance=max(max(surfaceReflectivityColor.r,surfaceReflectivityColor.g),surfaceReflectivityColor.b);\nfloat reflectance90=fresnelGrazingReflectance(reflectance);\nvec3 specularEnvironmentR0=surfaceReflectivityColor.rgb;\nvec3 specularEnvironmentR90=vec3(1.0,1.0,1.0)*reflectance90;\n\nvec3 diffuseBase=vec3(0.,0.,0.);\n#ifdef SPECULARTERM\nvec3 specularBase=vec3(0.,0.,0.);\n#endif\n#ifdef LIGHTMAP\nvec3 lightmapColor=toLinearSpace(texture2D(lightmapSampler,vLightmapUV+uvOffset).rgb)*vLightmapInfos.y;\n#endif\nlightingInfo info;\nfloat shadow=1.; \nfloat NdotL=-1.;\n#include<lightFragment>[0..maxSimultaneousLights]\n\n#if defined(ENVIRONMENTBRDF) && !defined(REFLECTIONMAP_SKYBOX)\n\nvec2 brdfSamplerUV=vec2(NdotV,roughness);\n\nvec4 environmentBrdf=texture2D(environmentBrdfSampler,brdfSamplerUV);\nvec3 specularEnvironmentReflectance=specularEnvironmentR0*environmentBrdf.x+environmentBrdf.y;\n#ifdef RADIANCEOCCLUSION\n#ifdef AMBIENTINGRAYSCALE\nfloat ambientMonochrome=ambientOcclusionColor.r;\n#else\nfloat ambientMonochrome=getLuminance(ambientOcclusionColor);\n#endif\nfloat seo=environmentRadianceOcclusion(ambientMonochrome,NdotVUnclamped);\nspecularEnvironmentReflectance*=seo;\n#endif\n#ifdef HORIZONOCCLUSION\n#ifdef BUMP\n#ifdef REFLECTIONMAP_3D\nfloat eho=environmentHorizonOcclusion(reflectionCoords,normalW);\nspecularEnvironmentReflectance*=eho;\n#endif\n#endif\n#endif\n#else\n\nvec3 specularEnvironmentReflectance=fresnelSchlickEnvironmentGGX(NdotV,specularEnvironmentR0,specularEnvironmentR90,sqrt(microSurface));\n#endif\n\n#ifdef REFRACTION\nvec3 refractance=vec3(0.0,0.0,0.0);\nvec3 transmission=vec3(1.0,1.0,1.0);\n#ifdef LINKREFRACTIONTOTRANSPARENCY\n\ntransmission*=(1.0-alpha);\n\n\nvec3 mixedAlbedo=surfaceAlbedo;\nfloat maxChannel=max(max(mixedAlbedo.r,mixedAlbedo.g),mixedAlbedo.b);\nvec3 tint=clamp(maxChannel*mixedAlbedo,0.0,1.0);\n\nsurfaceAlbedo*=alpha;\n\nenvironmentIrradiance*=alpha;\n\nenvironmentRefraction*=tint;\n\nalpha=1.0;\n#endif\n\nvec3 bounceSpecularEnvironmentReflectance=(2.0*specularEnvironmentReflectance)/(1.0+specularEnvironmentReflectance);\nspecularEnvironmentReflectance=mix(bounceSpecularEnvironmentReflectance,specularEnvironmentReflectance,alpha);\n\ntransmission*=1.0-specularEnvironmentReflectance;\n\nrefractance=transmission;\n#endif\n\n\n\n\nsurfaceAlbedo.rgb=(1.-reflectance)*surfaceAlbedo.rgb;\n\nvec3 finalDiffuse=diffuseBase;\nfinalDiffuse.rgb+=vAmbientColor;\nfinalDiffuse*=surfaceAlbedo.rgb;\nfinalDiffuse=max(finalDiffuse,0.0);\n\n#ifdef REFLECTION\nvec3 finalIrradiance=environmentIrradiance;\nfinalIrradiance*=surfaceAlbedo.rgb;\n#endif\n\n#ifdef SPECULARTERM\nvec3 finalSpecular=specularBase;\nfinalSpecular=max(finalSpecular,0.0);\n\nvec3 finalSpecularScaled=finalSpecular*vLightingIntensity.x*vLightingIntensity.w;\n#endif\n\n#ifdef REFLECTION\nvec3 finalRadiance=environmentRadiance;\nfinalRadiance*=specularEnvironmentReflectance;\n\nvec3 finalRadianceScaled=finalRadiance*vLightingIntensity.z;\n#endif\n\n#ifdef REFRACTION\nvec3 finalRefraction=environmentRefraction;\nfinalRefraction*=refractance;\n#endif\n\nvec3 finalEmissive=vEmissiveColor;\n#ifdef EMISSIVE\nvec3 emissiveColorTex=texture2D(emissiveSampler,vEmissiveUV+uvOffset).rgb;\nfinalEmissive*=toLinearSpace(emissiveColorTex.rgb);\nfinalEmissive*=vEmissiveInfos.y;\n#endif\n\n#ifdef ALPHABLEND\nfloat luminanceOverAlpha=0.0;\n#if defined(REFLECTION) && defined(RADIANCEOVERALPHA)\nluminanceOverAlpha+=getLuminance(finalRadianceScaled);\n#endif\n#if defined(SPECULARTERM) && defined(SPECULAROVERALPHA)\nluminanceOverAlpha+=getLuminance(finalSpecularScaled);\n#endif\n#if defined(RADIANCEOVERALPHA) || defined(SPECULAROVERALPHA)\nalpha=clamp(alpha+luminanceOverAlpha*luminanceOverAlpha,0.,1.);\n#endif\n#endif\n\n\n\nvec4 finalColor=vec4(finalDiffuse*ambientOcclusionColor*vLightingIntensity.x +\n#ifdef REFLECTION\nfinalIrradiance*ambientOcclusionColor*vLightingIntensity.z +\n#endif\n#ifdef SPECULARTERM\n\n\nfinalSpecularScaled +\n#endif\n#ifdef REFLECTION\n\n\nfinalRadianceScaled +\n#endif\n#ifdef REFRACTION\nfinalRefraction*vLightingIntensity.z +\n#endif\nfinalEmissive*vLightingIntensity.y,\nalpha);\n\n#ifdef LIGHTMAP\n#ifndef LIGHTMAPEXCLUDED\n#ifdef USELIGHTMAPASSHADOWMAP\nfinalColor.rgb*=lightmapColor;\n#else\nfinalColor.rgb+=lightmapColor;\n#endif\n#endif\n#endif\n\nfinalColor=max(finalColor,0.0);\n#include<logDepthFragment>\n#include<fogFragment>(color,finalColor)\n#ifdef IMAGEPROCESSINGPOSTPROCESS\n\n\nfinalColor.rgb=clamp(finalColor.rgb,0.,30.0);\n#else\n\nfinalColor=applyImageProcessing(finalColor);\n#endif\n#ifdef PREMULTIPLYALPHA\n\nfinalColor.rgb*=finalColor.a;\n#endif\ngl_FragColor=finalColor;\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n}","spritesVertexShader":"\nattribute vec4 position;\nattribute vec4 options;\nattribute vec4 cellInfo;\nattribute vec4 color;\n\nuniform vec2 textureInfos;\nuniform mat4 view;\nuniform mat4 projection;\n\nvarying vec2 vUV;\nvarying vec4 vColor;\n#include<fogVertexDeclaration>\nvoid main(void) { \nvec3 viewPos=(view*vec4(position.xyz,1.0)).xyz; \nvec2 cornerPos;\nfloat angle=position.w;\nvec2 size=vec2(options.x,options.y);\nvec2 offset=options.zw;\nvec2 uvScale=textureInfos.xy;\ncornerPos=vec2(offset.x-0.5,offset.y-0.5)*size;\n\nvec3 rotatedCorner;\nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);\nrotatedCorner.y=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);\nrotatedCorner.z=0.;\n\nviewPos+=rotatedCorner;\ngl_Position=projection*vec4(viewPos,1.0); \n\nvColor=color;\n\nvec2 uvOffset=vec2(abs(offset.x-cellInfo.x),1.0-abs(offset.y-cellInfo.y));\nvUV=(uvOffset+cellInfo.zw)*uvScale;\n\n#ifdef FOG\nvFogDistance=viewPos;\n#endif\n}","spritesPixelShader":"uniform bool alphaTest;\nvarying vec4 vColor;\n\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n\n#include<fogFragmentDeclaration>\nvoid main(void) {\nvec4 color=texture2D(diffuseSampler,vUV);\nif (alphaTest) \n{\nif (color.a<0.95)\ndiscard;\n}\ncolor*=vColor;\n#include<fogFragment>\ngl_FragColor=color;\n}","particlesVertexShader":"\nattribute vec3 position;\nattribute vec4 color;\nattribute vec4 options;\nattribute float cellIndex;\n\nuniform mat4 view;\nuniform mat4 projection;\nuniform vec3 particlesInfos; \n\nvarying vec2 vUV;\nvarying vec4 vColor;\n#ifdef CLIPPLANE\nuniform vec4 vClipPlane;\nuniform mat4 invView;\nvarying float fClipDistance;\n#endif\nvoid main(void) { \nvec3 viewPos=(view*vec4(position,1.0)).xyz; \nvec3 cornerPos;\nfloat size=options.y;\nfloat angle=options.x;\nvec2 offset=options.zw;\ncornerPos=vec3(offset.x-0.5,offset.y-0.5,0.)*size;\n\nvec3 rotatedCorner;\nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);\nrotatedCorner.y=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);\nrotatedCorner.z=0.;\n\nviewPos+=rotatedCorner;\ngl_Position=projection*vec4(viewPos,1.0); \nvColor=color;\n#ifdef ANIMATESHEET\nfloat rowOffset=floor(cellIndex/particlesInfos.z);\nfloat columnOffset=cellIndex-rowOffset*particlesInfos.z;\nvec2 uvScale=particlesInfos.xy;\nvec2 uvOffset=vec2(offset.x ,1.0-offset.y);\nvUV=(uvOffset+vec2(columnOffset,rowOffset))*uvScale;\n#else\nvUV=offset;\n#endif\n\n#ifdef CLIPPLANE\nvec4 worldPos=invView*vec4(viewPos,1.0);\nfClipDistance=dot(worldPos,vClipPlane);\n#endif\n}","particlesPixelShader":"\nvarying vec2 vUV;\nvarying vec4 vColor;\nuniform vec4 textureMask;\nuniform sampler2D diffuseSampler;\n#ifdef CLIPPLANE\nvarying float fClipDistance;\n#endif\nvoid main(void) {\n#ifdef CLIPPLANE\nif (fClipDistance>0.0)\ndiscard;\n#endif\nvec4 baseColor=texture2D(diffuseSampler,vUV);\ngl_FragColor=(baseColor*textureMask+(vec4(1.,1.,1.,1.)-textureMask))*vColor;\n}","colorVertexShader":"\nattribute vec3 position;\n#ifdef VERTEXCOLOR\nattribute vec4 color;\n#endif\n#include<bonesDeclaration>\n\nuniform mat4 viewProjection;\nuniform mat4 world;\n\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\nvoid main(void) {\nmat4 finalWorld=world;\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\n#ifdef VERTEXCOLOR\n\nvColor=color;\n#endif\n}","colorPixelShader":"#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#else\nuniform vec4 color;\n#endif\nvoid main(void) {\n#ifdef VERTEXCOLOR\ngl_FragColor=vColor;\n#else\ngl_FragColor=color;\n#endif\n}","postprocessVertexShader":"\nattribute vec2 position;\nuniform vec2 scale;\n\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvUV=(position*madd+madd)*scale;\ngl_Position=vec4(position,0.0,1.0);\n}","passPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nvoid main(void) \n{\ngl_FragColor=texture2D(textureSampler,vUV);\n}","shadowMapVertexShader":"\nattribute vec3 position;\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\nuniform mat4 viewProjection;\nuniform vec2 biasAndScale;\nuniform vec2 depthValues;\nvarying float vDepthMetric;\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform mat4 diffuseMatrix;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#endif\nvoid main(void)\n{\n#include<instancesVertex>\n#include<bonesVertex>\nvec4 worldPos=finalWorld*vec4(position,1.0);\ngl_Position=viewProjection*worldPos;\nvDepthMetric=((gl_Position.z+depthValues.x)/(depthValues.y))+biasAndScale.x;\n#ifdef ALPHATEST\n#ifdef UV1\nvUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef UV2\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n}","shadowMapPixelShader":"#ifndef FLOAT\nvec4 pack(float depth)\n{\nconst vec4 bit_shift=vec4(255.0*255.0*255.0,255.0*255.0,255.0,1.0);\nconst vec4 bit_mask=vec4(0.0,1.0/255.0,1.0/255.0,1.0/255.0);\nvec4 res=fract(depth*bit_shift);\nres-=res.xxyz*bit_mask;\nreturn res;\n}\n#endif\nvarying float vDepthMetric;\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\nuniform vec2 biasAndScale;\nuniform vec2 depthValues;\nvoid main(void)\n{\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\nfloat depth=vDepthMetric;\n#ifdef ESM\ndepth=clamp(exp(-min(87.,biasAndScale.y*depth)),0.,1.);\n#endif\n#ifdef FLOAT\ngl_FragColor=vec4(depth,1.0,1.0,1.0);\n#else\ngl_FragColor=pack(depth);\n#endif\n}","depthBoxBlurPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec2 screenSize;\nvoid main(void)\n{\nvec4 colorDepth=vec4(0.0);\nfor (int x=-OFFSET; x<=OFFSET; x++)\nfor (int y=-OFFSET; y<=OFFSET; y++)\ncolorDepth+=texture2D(textureSampler,vUV+vec2(x,y)/screenSize);\ngl_FragColor=(colorDepth/float((OFFSET*2+1)*(OFFSET*2+1)));\n}","proceduralVertexShader":"\nattribute vec2 position;\n\nvarying vec2 vPosition;\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvPosition=position;\nvUV=position*madd+madd;\ngl_Position=vec4(position,0.0,1.0);\n}","depthVertexShader":"\nattribute vec3 position;\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\nuniform mat4 viewProjection;\nuniform vec2 depthValues;\n#if defined(ALPHATEST) || defined(NEED_UV)\nvarying vec2 vUV;\nuniform mat4 diffuseMatrix;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#endif\nvarying float vDepthMetric;\nvoid main(void)\n{\n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\nvDepthMetric=((gl_Position.z+depthValues.x)/(depthValues.y));\n#if defined(ALPHATEST) || defined(BASIC_RENDER)\n#ifdef UV1\nvUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef UV2\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n}","depthPixelShader":"#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\nvarying float vDepthMetric;\nvoid main(void)\n{\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\ngl_FragColor=vec4(vDepthMetric,vDepthMetric*vDepthMetric,0.0,1.0);\n}","ssaoPixelShader":"\nuniform sampler2D textureSampler;\nvarying vec2 vUV;\n#ifdef SSAO\nuniform sampler2D randomSampler;\nuniform float randTextureTiles;\nuniform float samplesFactor;\nuniform vec3 sampleSphere[SAMPLES];\nuniform float totalStrength;\nuniform float radius;\nuniform float area;\nuniform float fallOff;\nuniform float base;\nvec3 normalFromDepth(float depth,vec2 coords)\n{\nvec2 offset1=vec2(0.0,radius);\nvec2 offset2=vec2(radius,0.0);\nfloat depth1=texture2D(textureSampler,coords+offset1).r;\nfloat depth2=texture2D(textureSampler,coords+offset2).r;\nvec3 p1=vec3(offset1,depth1-depth);\nvec3 p2=vec3(offset2,depth2-depth);\nvec3 normal=cross(p1,p2);\nnormal.z=-normal.z;\nreturn normalize(normal);\n}\nvoid main()\n{\nvec3 random=normalize(texture2D(randomSampler,vUV*randTextureTiles).rgb);\nfloat depth=texture2D(textureSampler,vUV).r;\nvec3 position=vec3(vUV,depth);\nvec3 normal=normalFromDepth(depth,vUV);\nfloat radiusDepth=radius/depth;\nfloat occlusion=0.0;\nvec3 ray;\nvec3 hemiRay;\nfloat occlusionDepth;\nfloat difference;\nfor (int i=0; i<SAMPLES; i++)\n{\nray=radiusDepth*reflect(sampleSphere[i],random);\nhemiRay=position+sign(dot(ray,normal))*ray;\nocclusionDepth=texture2D(textureSampler,clamp(hemiRay.xy,vec2(0.001,0.001),vec2(0.999,0.999))).r;\ndifference=depth-occlusionDepth;\nocclusion+=step(fallOff,difference)*(1.0-smoothstep(fallOff,area,difference));\n}\nfloat ao=1.0-totalStrength*occlusion*samplesFactor;\nfloat result=clamp(ao+base,0.0,1.0);\ngl_FragColor.r=result;\ngl_FragColor.g=result;\ngl_FragColor.b=result;\ngl_FragColor.a=1.0;\n}\n#endif\n","ssao2PixelShader":"\nprecision highp float;\nuniform sampler2D textureSampler;\nuniform float near;\nuniform float far;\nuniform float radius;\nvarying vec2 vUV;\nfloat perspectiveDepthToViewZ( const in float invClipZ,const in float near,const in float far ) {\nreturn ( near*far )/( ( far-near )*invClipZ-far );\n}\nfloat viewZToPerspectiveDepth( const in float viewZ,const in float near,const in float far ) {\nreturn ( near*far/viewZ+far)/( far-near );\n}\nfloat viewZToOrthographicDepth( const in float viewZ,const in float near,const in float far ) {\nreturn ( viewZ+near )/( near-far );\n}\n#ifdef SSAO\nuniform sampler2D randomSampler;\nuniform sampler2D normalSampler;\nuniform float randTextureTiles;\nuniform float samplesFactor;\nuniform vec3 sampleSphere[SAMPLES];\nuniform float totalStrength;\nuniform float base;\nuniform float xViewport;\nuniform float yViewport;\nuniform float maxZ;\nuniform float minZAspect;\nuniform vec2 texelSize;\nuniform mat4 projection;\nvoid main()\n{\nvec3 random=texture2D(randomSampler,vUV*randTextureTiles).rgb;\nfloat depth=texture2D(textureSampler,vUV).r;\nfloat depthSign=depth/abs(depth);\ndepth=depth*depthSign;\nvec3 normal=texture2D(normalSampler,vUV).rgb; \nfloat occlusion=0.0;\nfloat correctedRadius=min(radius,minZAspect*depth/near);\nvec3 vViewRay=vec3((vUV.x*2.0-1.0)*xViewport,(vUV.y*2.0-1.0)*yViewport,depthSign);\nvec3 origin=vViewRay*depth;\nvec3 rvec=random*2.0-1.0;\nrvec.z=0.0;\nvec3 tangent=normalize(rvec-normal*dot(rvec,normal));\nvec3 bitangent=cross(normal,tangent);\nmat3 tbn=mat3(tangent,bitangent,normal);\nfloat difference;\nif (depth>maxZ) {\ngl_FragColor=vec4(1.0,1.0,1.0,1.0);\nreturn;\n}\nfor (int i=0; i<SAMPLES; ++i) {\n\nvec3 samplePosition=tbn*sampleSphere[i];\nsamplePosition=samplePosition*correctedRadius+origin;\n\nvec4 offset=vec4(samplePosition,1.0);\noffset=projection*offset;\noffset.xyz/=offset.w;\noffset.xy=offset.xy*0.5+0.5;\nif (offset.x<0.0 || offset.y<0.0 || offset.x>1.0 || offset.y>1.0) {\ncontinue;\n}\n\nfloat sampleDepth=abs(texture2D(textureSampler,offset.xy).r);\n\nfloat rangeCheck=abs(depth-sampleDepth)<correctedRadius ? 1.0 : 0.0;\ndifference=depthSign*samplePosition.z-sampleDepth;\n\nocclusion+=(difference>=1e-5 ? 1.0 : 0.0)*rangeCheck;\n}\n\nfloat ao=1.0-totalStrength*occlusion*samplesFactor;\nfloat result=clamp(ao+base,0.0,1.0);\ngl_FragColor=vec4(vec3(result),1.0);\n}\n#endif\n#ifdef BILATERAL_BLUR\nuniform sampler2D depthSampler;\nuniform float outSize;\nuniform float samplerOffsets[SAMPLES];\nvec4 blur9(sampler2D image,vec2 uv,float resolution,vec2 direction) {\nvec4 color=vec4(0.0);\nvec2 off1=vec2(1.3846153846)*direction;\nvec2 off2=vec2(3.2307692308)*direction;\ncolor+=texture2D(image,uv)*0.2270270270;\ncolor+=texture2D(image,uv+(off1/resolution))*0.3162162162;\ncolor+=texture2D(image,uv-(off1/resolution))*0.3162162162;\ncolor+=texture2D(image,uv+(off2/resolution))*0.0702702703;\ncolor+=texture2D(image,uv-(off2/resolution))*0.0702702703;\nreturn color;\n}\nvec4 blur13(sampler2D image,vec2 uv,float resolution,vec2 direction) {\nvec4 color=vec4(0.0);\nvec2 off1=vec2(1.411764705882353)*direction;\nvec2 off2=vec2(3.2941176470588234)*direction;\nvec2 off3=vec2(5.176470588235294)*direction;\ncolor+=texture2D(image,uv)*0.1964825501511404;\ncolor+=texture2D(image,uv+(off1/resolution))*0.2969069646728344;\ncolor+=texture2D(image,uv-(off1/resolution))*0.2969069646728344;\ncolor+=texture2D(image,uv+(off2/resolution))*0.09447039785044732;\ncolor+=texture2D(image,uv-(off2/resolution))*0.09447039785044732;\ncolor+=texture2D(image,uv+(off3/resolution))*0.010381362401148057;\ncolor+=texture2D(image,uv-(off3/resolution))*0.010381362401148057;\nreturn color;\n}\nvec4 blur13Bilateral(sampler2D image,vec2 uv,float resolution,vec2 direction) {\nvec4 color=vec4(0.0);\nvec2 off1=vec2(1.411764705882353)*direction;\nvec2 off2=vec2(3.2941176470588234)*direction;\nvec2 off3=vec2(5.176470588235294)*direction;\nfloat compareDepth=abs(texture2D(depthSampler,uv).r);\nfloat sampleDepth;\nfloat weight;\nfloat weightSum=30.0;\ncolor+=texture2D(image,uv)*30.0;\nsampleDepth=abs(texture2D(depthSampler,uv+(off1/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv+(off1/resolution))*weight;\nsampleDepth=abs(texture2D(depthSampler,uv-(off1/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv-(off1/resolution))*weight;\nsampleDepth=abs(texture2D(depthSampler,uv+(off2/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv+(off2/resolution))*weight;\nsampleDepth=abs(texture2D(depthSampler,uv-(off2/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv-(off2/resolution))*weight;\nsampleDepth=abs(texture2D(depthSampler,uv+(off3/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv+(off3/resolution))*weight;\nsampleDepth=abs(texture2D(depthSampler,uv-(off3/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv-(off3/resolution))*weight;\nreturn color/weightSum;\n}\nvoid main()\n{\n#if EXPENSIVE\nfloat compareDepth=abs(texture2D(depthSampler,vUV).r);\nfloat texelsize=1.0/outSize;\nfloat result=0.0;\nfloat weightSum=0.0;\nfor (int i=0; i<SAMPLES; ++i)\n{\n#ifdef BILATERAL_BLUR_H\nvec2 direction=vec2(1.0,0.0);\nvec2 sampleOffset=vec2(texelsize*samplerOffsets[i],0.0);\n#else\nvec2 direction=vec2(0.0,1.0);\nvec2 sampleOffset=vec2(0.0,texelsize*samplerOffsets[i]);\n#endif\nvec2 samplePos=vUV+sampleOffset;\nfloat sampleDepth=abs(texture2D(depthSampler,samplePos).r);\nfloat weight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30000.0);\nresult+=texture2D(textureSampler,samplePos).r*weight;\nweightSum+=weight;\n}\nresult/=weightSum;\ngl_FragColor.rgb=vec3(result);\ngl_FragColor.a=1.0;\n#else\nvec4 color;\n#ifdef BILATERAL_BLUR_H\nvec2 direction=vec2(1.0,0.0);\ncolor=blur13Bilateral(textureSampler,vUV,outSize,direction);\n#else\nvec2 direction=vec2(0.0,1.0);\ncolor=blur13Bilateral(textureSampler,vUV,outSize,direction);\n#endif\ngl_FragColor.rgb=vec3(color.r);\ngl_FragColor.a=1.0;\n#endif\n}\n#endif\n","ssaoCombinePixelShader":"uniform sampler2D textureSampler;\nuniform sampler2D originalColor;\nvarying vec2 vUV;\nvoid main(void) {\nvec4 ssaoColor=texture2D(textureSampler,vUV);\nvec4 sceneColor=texture2D(originalColor,vUV);\ngl_FragColor=sceneColor*ssaoColor;\n}\n","chromaticAberrationPixelShader":"\nuniform sampler2D textureSampler; \n\nuniform float chromatic_aberration;\nuniform float screen_width;\nuniform float screen_height;\n\nvarying vec2 vUV;\nvoid main(void)\n{\nvec2 centered_screen_pos=vec2(vUV.x-0.5,vUV.y-0.5);\nfloat radius2=centered_screen_pos.x*centered_screen_pos.x\n+centered_screen_pos.y*centered_screen_pos.y;\nfloat radius=sqrt(radius2);\nvec4 original=texture2D(textureSampler,vUV);\nif (chromatic_aberration>0.0) {\n\nvec3 ref_indices=vec3(-0.3,0.0,0.3);\nfloat ref_shiftX=chromatic_aberration*radius*17.0/screen_width;\nfloat ref_shiftY=chromatic_aberration*radius*17.0/screen_height;\n\nvec2 ref_coords_r=vec2(vUV.x+ref_indices.r*ref_shiftX,vUV.y+ref_indices.r*ref_shiftY*0.5);\nvec2 ref_coords_g=vec2(vUV.x+ref_indices.g*ref_shiftX,vUV.y+ref_indices.g*ref_shiftY*0.5);\nvec2 ref_coords_b=vec2(vUV.x+ref_indices.b*ref_shiftX,vUV.y+ref_indices.b*ref_shiftY*0.5);\noriginal.r=texture2D(textureSampler,ref_coords_r).r;\noriginal.g=texture2D(textureSampler,ref_coords_g).g;\noriginal.b=texture2D(textureSampler,ref_coords_b).b;\n}\ngl_FragColor=original;\n}","lensHighlightsPixelShader":"\nuniform sampler2D textureSampler; \n\nuniform float gain;\nuniform float threshold;\nuniform float screen_width;\nuniform float screen_height;\n\nvarying vec2 vUV;\n\nvec4 highlightColor(vec4 color) {\nvec4 highlight=color;\nfloat luminance=dot(highlight.rgb,vec3(0.2125,0.7154,0.0721));\nfloat lum_threshold;\nif (threshold>1.0) { lum_threshold=0.94+0.01*threshold; }\nelse { lum_threshold=0.5+0.44*threshold; }\nluminance=clamp((luminance-lum_threshold)*(1.0/(1.0-lum_threshold)),0.0,1.0);\nhighlight*=luminance*gain;\nhighlight.a=1.0;\nreturn highlight;\n}\nvoid main(void)\n{\nvec4 original=texture2D(textureSampler,vUV);\n\nif (gain == -1.0) {\ngl_FragColor=vec4(0.0,0.0,0.0,1.0);\nreturn;\n}\nfloat w=2.0/screen_width;\nfloat h=2.0/screen_height;\nfloat weight=1.0;\n\nvec4 blurred=vec4(0.0,0.0,0.0,0.0);\n#ifdef PENTAGON\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.84*w,0.43*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.48*w,-1.29*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.61*w,1.51*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.55*w,-0.74*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.71*w,-0.52*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.94*w,1.59*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.40*w,-1.87*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.62*w,1.16*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.09*w,0.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.46*w,-1.71*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.08*w,2.42*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.85*w,-1.89*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.89*w,0.16*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.29*w,1.88*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.40*w,-2.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.54*w,2.26*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.60*w,-0.61*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.31*w,-1.30*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.83*w,2.53*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.12*w,-2.48*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.60*w,1.11*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.82*w,0.99*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.50*w,-2.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.85*w,3.33*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.94*w,-1.92*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.27*w,-0.53*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.95*w,2.48*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.23*w,-3.04*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.17*w,2.05*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.97*w,-0.04*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.25*w,-2.00*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.31*w,3.08*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.94*w,-2.59*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.37*w,0.64*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-3.13*w,1.93*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.03*w,-3.65*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.60*w,3.17*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-3.14*w,-1.19*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.00*w,-1.19*h)));\n#else\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.85*w,0.36*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.52*w,-1.14*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.46*w,1.42*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.46*w,-0.83*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.79*w,-0.42*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.11*w,1.62*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.29*w,-2.07*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.69*w,1.39*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.28*w,0.12*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.65*w,-1.69*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.08*w,2.44*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.63*w,-1.90*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.55*w,0.31*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.13*w,1.52*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.56*w,-2.61*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.38*w,2.34*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.64*w,-0.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.53*w,-1.21*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.06*w,2.63*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.00*w,-2.69*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.59*w,1.32*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.82*w,0.78*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.57*w,-2.50*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.54*w,2.93*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.39*w,-1.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.01*w,-0.28*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.04*w,2.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.02*w,-3.05*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.09*w,2.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-3.07*w,-0.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.44*w,-1.90*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.52*w,3.05*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.68*w,-2.61*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.01*w,0.79*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.76*w,1.46*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.05*w,-2.94*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.21*w,2.88*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.84*w,-1.30*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.98*w,-0.96*h)));\n#endif\nblurred/=39.0;\ngl_FragColor=blurred;\n\n}","depthOfFieldPixelShader":"\n\n\n\n\nuniform sampler2D textureSampler;\nuniform sampler2D highlightsSampler;\nuniform sampler2D depthSampler;\nuniform sampler2D grainSampler;\n\nuniform float grain_amount;\nuniform bool blur_noise;\nuniform float screen_width;\nuniform float screen_height;\nuniform float distortion;\nuniform bool dof_enabled;\n\nuniform float screen_distance; \nuniform float aperture;\nuniform float darken;\nuniform float edge_blur;\nuniform bool highlights;\n\nuniform float near;\nuniform float far;\n\nvarying vec2 vUV;\n\n#define PI 3.14159265\n#define TWOPI 6.28318530\n#define inverse_focal_length 0.1 \n\nvec2 centered_screen_pos;\nvec2 distorted_coords;\nfloat radius2;\nfloat radius;\n\nvec2 rand(vec2 co)\n{\nfloat noise1=(fract(sin(dot(co,vec2(12.9898,78.233)))*43758.5453));\nfloat noise2=(fract(sin(dot(co,vec2(12.9898,78.233)*2.0))*43758.5453));\nreturn clamp(vec2(noise1,noise2),0.0,1.0);\n}\n\nvec2 getDistortedCoords(vec2 coords) {\nif (distortion == 0.0) { return coords; }\nvec2 direction=1.0*normalize(centered_screen_pos);\nvec2 dist_coords=vec2(0.5,0.5);\ndist_coords.x=0.5+direction.x*radius2*1.0;\ndist_coords.y=0.5+direction.y*radius2*1.0;\nfloat dist_amount=clamp(distortion*0.23,0.0,1.0);\ndist_coords=mix(coords,dist_coords,dist_amount);\nreturn dist_coords;\n}\n\nfloat sampleScreen(inout vec4 color,const in vec2 offset,const in float weight) {\n\nvec2 coords=distorted_coords;\nfloat angle=rand(coords*100.0).x*TWOPI;\ncoords+=vec2(offset.x*cos(angle)-offset.y*sin(angle),offset.x*sin(angle)+offset.y*cos(angle));\ncolor+=texture2D(textureSampler,coords)*weight;\nreturn weight;\n}\n\nfloat getBlurLevel(float size) {\nreturn min(3.0,ceil(size/1.0));\n}\n\nvec4 getBlurColor(float size) {\nvec4 col=texture2D(textureSampler,distorted_coords);\nif (size == 0.0) { return col; }\n\n\nfloat blur_level=getBlurLevel(size);\nfloat w=(size/screen_width);\nfloat h=(size/screen_height);\nfloat total_weight=1.0;\nvec2 sample_coords;\ntotal_weight+=sampleScreen(col,vec2(-0.50*w,0.24*h),0.93);\ntotal_weight+=sampleScreen(col,vec2(0.30*w,-0.75*h),0.90);\ntotal_weight+=sampleScreen(col,vec2(0.36*w,0.96*h),0.87);\ntotal_weight+=sampleScreen(col,vec2(-1.08*w,-0.55*h),0.85);\ntotal_weight+=sampleScreen(col,vec2(1.33*w,-0.37*h),0.83);\ntotal_weight+=sampleScreen(col,vec2(-0.82*w,1.31*h),0.80);\ntotal_weight+=sampleScreen(col,vec2(-0.31*w,-1.67*h),0.78);\ntotal_weight+=sampleScreen(col,vec2(1.47*w,1.11*h),0.76);\ntotal_weight+=sampleScreen(col,vec2(-1.97*w,0.19*h),0.74);\ntotal_weight+=sampleScreen(col,vec2(1.42*w,-1.57*h),0.72);\nif (blur_level>1.0) {\ntotal_weight+=sampleScreen(col,vec2(0.01*w,2.25*h),0.70);\ntotal_weight+=sampleScreen(col,vec2(-1.62*w,-1.74*h),0.67);\ntotal_weight+=sampleScreen(col,vec2(2.49*w,0.20*h),0.65);\ntotal_weight+=sampleScreen(col,vec2(-2.07*w,1.61*h),0.63);\ntotal_weight+=sampleScreen(col,vec2(0.46*w,-2.70*h),0.61);\ntotal_weight+=sampleScreen(col,vec2(1.55*w,2.40*h),0.59);\ntotal_weight+=sampleScreen(col,vec2(-2.88*w,-0.75*h),0.56);\ntotal_weight+=sampleScreen(col,vec2(2.73*w,-1.44*h),0.54);\ntotal_weight+=sampleScreen(col,vec2(-1.08*w,3.02*h),0.52);\ntotal_weight+=sampleScreen(col,vec2(-1.28*w,-3.05*h),0.49);\n}\nif (blur_level>2.0) {\ntotal_weight+=sampleScreen(col,vec2(3.11*w,1.43*h),0.46);\ntotal_weight+=sampleScreen(col,vec2(-3.36*w,1.08*h),0.44);\ntotal_weight+=sampleScreen(col,vec2(1.80*w,-3.16*h),0.41);\ntotal_weight+=sampleScreen(col,vec2(0.83*w,3.65*h),0.38);\ntotal_weight+=sampleScreen(col,vec2(-3.16*w,-2.19*h),0.34);\ntotal_weight+=sampleScreen(col,vec2(3.92*w,-0.53*h),0.31);\ntotal_weight+=sampleScreen(col,vec2(-2.59*w,3.12*h),0.26);\ntotal_weight+=sampleScreen(col,vec2(-0.20*w,-4.15*h),0.22);\ntotal_weight+=sampleScreen(col,vec2(3.02*w,3.00*h),0.15);\n}\ncol/=total_weight; \n\nif (darken>0.0) {\ncol.rgb*=clamp(0.3,1.0,1.05-size*0.5*darken);\n}\n\n\n\n\nreturn col;\n}\nvoid main(void)\n{\n\ncentered_screen_pos=vec2(vUV.x-0.5,vUV.y-0.5);\nradius2=centered_screen_pos.x*centered_screen_pos.x+centered_screen_pos.y*centered_screen_pos.y;\nradius=sqrt(radius2);\ndistorted_coords=getDistortedCoords(vUV); \nvec2 texels_coords=vec2(vUV.x*screen_width,vUV.y*screen_height); \nfloat depth=texture2D(depthSampler,distorted_coords).r; \nfloat distance=near+(far-near)*depth; \nvec4 color=texture2D(textureSampler,vUV); \n\n\nfloat coc=abs(aperture*(screen_distance*(inverse_focal_length-1.0/distance)-1.0));\n\nif (dof_enabled == false || coc<0.07) { coc=0.0; }\n\nfloat edge_blur_amount=0.0;\nif (edge_blur>0.0) {\nedge_blur_amount=clamp((radius*2.0-1.0+0.15*edge_blur)*1.5,0.0,1.0)*1.3;\n}\n\nfloat blur_amount=max(edge_blur_amount,coc);\n\nif (blur_amount == 0.0) {\ngl_FragColor=texture2D(textureSampler,distorted_coords);\n}\nelse {\n\ngl_FragColor=getBlurColor(blur_amount*1.7);\n\nif (highlights) {\ngl_FragColor.rgb+=clamp(coc,0.0,1.0)*texture2D(highlightsSampler,distorted_coords).rgb;\n}\nif (blur_noise) {\n\nvec2 noise=rand(distorted_coords)*0.01*blur_amount;\nvec2 blurred_coord=vec2(distorted_coords.x+noise.x,distorted_coords.y+noise.y);\ngl_FragColor=0.04*texture2D(textureSampler,blurred_coord)+0.96*gl_FragColor;\n}\n}\n\nif (grain_amount>0.0) {\nvec4 grain_color=texture2D(grainSampler,texels_coords*0.003);\ngl_FragColor.rgb+=(-0.5+grain_color.rgb)*0.30*grain_amount;\n}\n}\n","standardPixelShader":"uniform sampler2D textureSampler;\nvarying vec2 vUV;\n#if defined(PASS_POST_PROCESS)\nvoid main(void)\n{\nvec4 color=texture2D(textureSampler,vUV);\ngl_FragColor=color;\n}\n#endif\n#if defined(DOWN_SAMPLE_X4)\nuniform vec2 dsOffsets[16];\nvoid main(void)\n{\nvec4 average=vec4(0.0,0.0,0.0,0.0);\naverage=texture2D(textureSampler,vUV+dsOffsets[0]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[1]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[2]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[3]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[4]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[5]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[6]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[7]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[8]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[9]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[10]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[11]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[12]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[13]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[14]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[15]);\naverage/=16.0;\ngl_FragColor=average;\n}\n#endif\n#if defined(BRIGHT_PASS)\nuniform vec2 dsOffsets[4];\nuniform float brightThreshold;\nvoid main(void)\n{\nvec4 average=vec4(0.0,0.0,0.0,0.0);\naverage=texture2D(textureSampler,vUV+vec2(dsOffsets[0].x,dsOffsets[0].y));\naverage+=texture2D(textureSampler,vUV+vec2(dsOffsets[1].x,dsOffsets[1].y));\naverage+=texture2D(textureSampler,vUV+vec2(dsOffsets[2].x,dsOffsets[2].y));\naverage+=texture2D(textureSampler,vUV+vec2(dsOffsets[3].x,dsOffsets[3].y));\naverage*=0.25;\nfloat luminance=length(average.rgb);\nif (luminance<brightThreshold) {\naverage=vec4(0.0,0.0,0.0,1.0);\n}\ngl_FragColor=average;\n}\n#endif\n#if defined(TEXTURE_ADDER)\nuniform sampler2D otherSampler;\nuniform sampler2D lensSampler;\nuniform float exposure;\nvoid main(void)\n{\nvec3 colour=texture2D(textureSampler,vUV).rgb;\ncolour*=exposure;\nvec3 X=max(vec3(0.0,0.0,0.0),colour-0.004);\nvec3 retColor=(X*(6.2*X+0.5))/(X*(6.2*X+1.7)+0.06);\ncolour=retColor*retColor;\ncolour+=colour*texture2D(lensSampler,vUV).rgb;\nvec4 finalColor=vec4(colour.rgb,1.0)+texture2D(otherSampler,vUV);\ngl_FragColor=finalColor;\n}\n#endif\n#if defined(VLS)\n#define PI 3.1415926535897932384626433832795\nuniform mat4 shadowViewProjection;\nuniform mat4 lightWorld;\nuniform vec3 cameraPosition;\nuniform vec3 sunDirection;\nuniform vec3 sunColor;\nuniform vec2 depthValues;\nuniform float scatteringCoefficient;\nuniform float scatteringPower;\nuniform sampler2D shadowMapSampler;\nuniform sampler2D positionSampler;\nfloat computeScattering(float lightDotView)\n{\nfloat result=1.0-scatteringCoefficient*scatteringCoefficient;\nresult/=(4.0*PI*pow(1.0+scatteringCoefficient*scatteringCoefficient-(2.0*scatteringCoefficient)*lightDotView,1.5));\nreturn result;\n}\nvoid main(void)\n{\n\nvec3 worldPos=texture2D(positionSampler,vUV).rgb;\nvec3 startPosition=cameraPosition;\nvec3 rayVector=worldPos-startPosition;\nfloat rayLength=length(rayVector);\nvec3 rayDirection=rayVector/rayLength;\nfloat stepLength=rayLength/NB_STEPS;\nvec3 stepL=rayDirection*stepLength;\nvec3 currentPosition=startPosition;\nvec3 accumFog=vec3(0.0);\nfor (int i=0; i<int(NB_STEPS); i++)\n{\nvec4 worldInShadowCameraSpace=shadowViewProjection*vec4(currentPosition,1.0);\nfloat depthMetric=(worldInShadowCameraSpace.z+depthValues.x)/(depthValues.y);\nfloat shadowPixelDepth=clamp(depthMetric,0.0,1.0);\nworldInShadowCameraSpace.xyz/=worldInShadowCameraSpace.w;\nworldInShadowCameraSpace.xyz=0.5*worldInShadowCameraSpace.xyz+vec3(0.5);\nfloat shadowMapValue=texture2D(shadowMapSampler,worldInShadowCameraSpace.xy).r;\nif (shadowMapValue>shadowPixelDepth)\naccumFog+=sunColor*computeScattering(dot(rayDirection,sunDirection));\ncurrentPosition+=stepL;\n}\naccumFog/=NB_STEPS;\nvec3 color=accumFog*scatteringPower;\ngl_FragColor=vec4(color*exp(color) ,1.0);\n}\n#endif\n#if defined(VLSMERGE)\nuniform sampler2D originalSampler;\nvoid main(void)\n{\ngl_FragColor=texture2D(originalSampler,vUV)+texture2D(textureSampler,vUV);\n}\n#endif\n#if defined(LUMINANCE)\nuniform vec2 lumOffsets[4];\nvoid main()\n{\nfloat average=0.0;\nvec4 color=vec4(0.0);\nfloat maximum=-1e20;\nvec3 weight=vec3(0.299,0.587,0.114);\nfor (int i=0; i<4; i++)\n{\ncolor=texture2D(textureSampler,vUV+ lumOffsets[i]);\n\nfloat GreyValue=dot(color.rgb,vec3(0.33,0.33,0.33));\n\n#ifdef WEIGHTED_AVERAGE\nfloat GreyValue=dot(color.rgb,weight);\n#endif\n#ifdef BRIGHTNESS\nfloat GreyValue=max(color.r,max(color.g,color.b));\n#endif\n#ifdef HSL_COMPONENT\nfloat GreyValue=0.5*(max(color.r,max(color.g,color.b))+min(color.r,min(color.g,color.b)));\n#endif\n#ifdef MAGNITUDE\nfloat GreyValue=length(color.rgb);\n#endif\nmaximum=max(maximum,GreyValue);\naverage+=(0.25*log(1e-5+GreyValue));\n}\naverage=exp(average);\ngl_FragColor=vec4(average,maximum,0.0,1.0);\n}\n#endif\n#if defined(LUMINANCE_DOWN_SAMPLE)\nuniform vec2 dsOffsets[9];\nuniform float halfDestPixelSize;\n#ifdef FINAL_DOWN_SAMPLER\nvec4 pack(float value) {\nconst vec4 bit_shift=vec4(255.0*255.0*255.0,255.0*255.0,255.0,1.0);\nconst vec4 bit_mask=vec4(0.0,1.0/255.0,1.0/255.0,1.0/255.0);\nvec4 res=fract(value*bit_shift);\nres-=res.xxyz*bit_mask;\nreturn res;\n}\n#endif\nvoid main()\n{\nvec4 color=vec4(0.0);\nfloat average=0.0;\nfor (int i=0; i<9; i++)\n{\ncolor=texture2D(textureSampler,vUV+vec2(halfDestPixelSize,halfDestPixelSize)+dsOffsets[i]);\naverage+=color.r;\n}\naverage/=9.0;\n#ifdef FINAL_DOWN_SAMPLER\ngl_FragColor=pack(average);\n#else\ngl_FragColor=vec4(average,average,0.0,1.0);\n#endif\n}\n#endif\n#if defined(HDR)\nuniform sampler2D textureAdderSampler;\nuniform float averageLuminance;\nvoid main()\n{\nvec4 color=texture2D(textureAdderSampler,vUV);\nvec4 adjustedColor=color/averageLuminance;\ncolor=adjustedColor;\ncolor.a=1.0;\ngl_FragColor=color;\n}\n#endif\n#if defined(LENS_FLARE)\n#define GHOSTS 3\nuniform sampler2D lensColorSampler;\nuniform float strength;\nuniform float ghostDispersal;\nuniform float haloWidth;\nuniform vec2 resolution;\nuniform float distortionStrength;\nfloat hash(vec2 p)\n{\nfloat h=dot(p,vec2(127.1,311.7));\nreturn -1.0+2.0*fract(sin(h)*43758.5453123);\n}\nfloat noise(in vec2 p)\n{\nvec2 i=floor(p);\nvec2 f=fract(p);\nvec2 u=f*f*(3.0-2.0*f);\nreturn mix(mix(hash(i+vec2(0.0,0.0)),\nhash(i+vec2(1.0,0.0)),u.x),\nmix(hash(i+vec2(0.0,1.0)),\nhash(i+vec2(1.0,1.0)),u.x),u.y);\n}\nfloat fbm(vec2 p)\n{\nfloat f=0.0;\nf+=0.5000*noise(p); p*=2.02;\nf+=0.2500*noise(p); p*=2.03;\nf+=0.1250*noise(p); p*=2.01;\nf+=0.0625*noise(p); p*=2.04;\nf/=0.9375;\nreturn f;\n}\nvec3 pattern(vec2 uv)\n{\nvec2 p=-1.0+2.0*uv;\nfloat p2=dot(p,p);\nfloat f=fbm(vec2(15.0*p2))/2.0;\nfloat r=0.2+0.6*sin(12.5*length(uv-vec2(0.5)));\nfloat g=0.2+0.6*sin(20.5*length(uv-vec2(0.5)));\nfloat b=0.2+0.6*sin(17.2*length(uv-vec2(0.5)));\nreturn (1.0-f)*vec3(r,g,b);\n}\nfloat luminance(vec3 color)\n{\nreturn dot(color.rgb,vec3(0.2126,0.7152,0.0722));\n}\nvec4 textureDistorted(sampler2D tex,vec2 texcoord,vec2 direction,vec3 distortion)\n{\nreturn vec4(\ntexture2D(tex,texcoord+direction*distortion.r).r,\ntexture2D(tex,texcoord+direction*distortion.g).g,\ntexture2D(tex,texcoord+direction*distortion.b).b,\n1.0\n);\n}\nvoid main(void)\n{\nvec2 uv=-vUV+vec2(1.0);\nvec2 ghostDir=(vec2(0.5)-uv)*ghostDispersal;\nvec2 texelSize=1.0/resolution;\nvec3 distortion=vec3(-texelSize.x*distortionStrength,0.0,texelSize.x*distortionStrength);\nvec4 result=vec4(0.0);\nfloat ghostIndice=1.0;\nfor (int i=0; i<GHOSTS; ++i)\n{\nvec2 offset=fract(uv+ghostDir*ghostIndice);\nfloat weight=length(vec2(0.5)-offset)/length(vec2(0.5));\nweight=pow(1.0-weight,10.0);\nresult+=textureDistorted(textureSampler,offset,normalize(ghostDir),distortion)*weight*strength;\nghostIndice+=1.0;\n}\nvec2 haloVec=normalize(ghostDir)*haloWidth;\nfloat weight=length(vec2(0.5)-fract(uv+haloVec))/length(vec2(0.5));\nweight=pow(1.0-weight,10.0);\nresult+=textureDistorted(textureSampler,fract(uv+haloVec),normalize(ghostDir),distortion)*weight*strength;\nresult*=texture2D(lensColorSampler,vec2(length(vec2(0.5)-uv)/length(vec2(0.5))));\ngl_FragColor=result;\n}\n#endif\n#if defined(LENS_FLARE_COMPOSE)\nuniform sampler2D otherSampler;\nuniform sampler2D lensDirtSampler;\nuniform sampler2D lensStarSampler;\nuniform mat4 lensStarMatrix;\nvoid main(void)\n{\nvec2 lensFlareCoords=(lensStarMatrix*vec4(vUV,1.0,1.0)).xy;\nvec4 lensMod=texture2D(lensDirtSampler,vUV);\nlensMod+=texture2D(lensStarSampler,vUV);\nvec4 result=texture2D(textureSampler,vUV)*lensMod;\ngl_FragColor=texture2D(otherSampler,vUV)+result;\n}\n#endif\n#if defined(DEPTH_OF_FIELD)\nuniform sampler2D otherSampler;\nuniform sampler2D depthSampler;\nuniform float distance;\nvoid main(void)\n{\nvec4 sharp=texture2D(otherSampler,vUV);\nvec4 blur=texture2D(textureSampler,vUV);\nfloat dist=clamp(texture2D(depthSampler,vUV).r*distance,0.0,1.0);\nfloat factor=0.0;\nif (dist<0.05)\nfactor=1.0;\nelse if (dist<0.1)\nfactor=20.0*(0.1-dist);\nelse if (dist<0.5)\nfactor=0.0;\nelse\nfactor=2.0*(dist-0.5);\nfactor=clamp(factor,0.0,0.90);\ngl_FragColor=mix(sharp,blur,factor);\n}\n#endif\n#if defined(MOTION_BLUR)\nuniform mat4 inverseViewProjection;\nuniform mat4 prevViewProjection;\nuniform vec2 screenSize;\nuniform float motionScale;\nuniform float motionStrength;\nuniform sampler2D depthSampler;\nvoid main(void)\n{\nvec2 texelSize=1.0/screenSize;\nfloat depth=texture2D(depthSampler,vUV).r;\nvec4 cpos=vec4(vUV*2.0-1.0,depth,1.0);\ncpos=cpos*inverseViewProjection;\nvec4 ppos=cpos*prevViewProjection;\nppos.xyz/=ppos.w;\nppos.xy=ppos.xy*0.5+0.5;\nvec2 velocity=(ppos.xy-vUV)*motionScale*motionStrength;\nfloat speed=length(velocity/texelSize);\nint nSamples=int(clamp(speed,1.0,MAX_MOTION_SAMPLES));\nvec4 result=texture2D(textureSampler,vUV);\nfor (int i=1; i<int(MAX_MOTION_SAMPLES); ++i) {\nif (i>=nSamples)\nbreak;\nvec2 offset1=vUV+velocity*(float(i)/float(nSamples-1)-0.5);\nresult+=texture2D(textureSampler,offset1);\n}\ngl_FragColor=result/float(nSamples);\n}\n#endif\n","fxaaVertexShader":"\nattribute vec2 position;\nuniform vec2 texelSize;\n\nvarying vec2 vUV;\nvarying vec2 sampleCoordS;\nvarying vec2 sampleCoordE;\nvarying vec2 sampleCoordN;\nvarying vec2 sampleCoordW;\nvarying vec2 sampleCoordNW;\nvarying vec2 sampleCoordSE;\nvarying vec2 sampleCoordNE;\nvarying vec2 sampleCoordSW;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvUV=(position*madd+madd);\nsampleCoordS=vUV+vec2( 0.0,1.0)*texelSize;\nsampleCoordE=vUV+vec2( 1.0,0.0)*texelSize;\nsampleCoordN=vUV+vec2( 0.0,-1.0)*texelSize;\nsampleCoordW=vUV+vec2(-1.0,0.0)*texelSize;\nsampleCoordNW=vUV+vec2(-1.0,-1.0)*texelSize;\nsampleCoordSE=vUV+vec2( 1.0,1.0)*texelSize;\nsampleCoordNE=vUV+vec2( 1.0,-1.0)*texelSize;\nsampleCoordSW=vUV+vec2(-1.0,1.0)*texelSize;\ngl_Position=vec4(position,0.0,1.0);\n}","fxaaPixelShader":"uniform sampler2D textureSampler;\nuniform vec2 texelSize;\nvarying vec2 vUV;\nvarying vec2 sampleCoordS;\nvarying vec2 sampleCoordE;\nvarying vec2 sampleCoordN;\nvarying vec2 sampleCoordW;\nvarying vec2 sampleCoordNW;\nvarying vec2 sampleCoordSE;\nvarying vec2 sampleCoordNE;\nvarying vec2 sampleCoordSW;\nconst float fxaaQualitySubpix=1.0;\nconst float fxaaQualityEdgeThreshold=0.166;\nconst float fxaaQualityEdgeThresholdMin=0.0833;\nconst vec3 kLumaCoefficients=vec3(0.2126,0.7152,0.0722);\n#define FxaaLuma(rgba) dot(rgba.rgb,kLumaCoefficients)\nvoid main(){\nvec2 posM;\nposM.x=vUV.x;\nposM.y=vUV.y;\nvec4 rgbyM=texture2D(textureSampler,vUV,0.0);\nfloat lumaM=FxaaLuma(rgbyM);\nfloat lumaS=FxaaLuma(texture2D(textureSampler,sampleCoordS,0.0));\nfloat lumaE=FxaaLuma(texture2D(textureSampler,sampleCoordE,0.0));\nfloat lumaN=FxaaLuma(texture2D(textureSampler,sampleCoordN,0.0));\nfloat lumaW=FxaaLuma(texture2D(textureSampler,sampleCoordW,0.0));\nfloat maxSM=max(lumaS,lumaM);\nfloat minSM=min(lumaS,lumaM);\nfloat maxESM=max(lumaE,maxSM);\nfloat minESM=min(lumaE,minSM);\nfloat maxWN=max(lumaN,lumaW);\nfloat minWN=min(lumaN,lumaW);\nfloat rangeMax=max(maxWN,maxESM);\nfloat rangeMin=min(minWN,minESM);\nfloat rangeMaxScaled=rangeMax*fxaaQualityEdgeThreshold;\nfloat range=rangeMax-rangeMin;\nfloat rangeMaxClamped=max(fxaaQualityEdgeThresholdMin,rangeMaxScaled);\nif(range<rangeMaxClamped) \n{\ngl_FragColor=rgbyM;\nreturn;\n}\nfloat lumaNW=FxaaLuma(texture2D(textureSampler,sampleCoordNW,0.0));\nfloat lumaSE=FxaaLuma(texture2D(textureSampler,sampleCoordSE,0.0));\nfloat lumaNE=FxaaLuma(texture2D(textureSampler,sampleCoordNE,0.0));\nfloat lumaSW=FxaaLuma(texture2D(textureSampler,sampleCoordSW,0.0));\nfloat lumaNS=lumaN+lumaS;\nfloat lumaWE=lumaW+lumaE;\nfloat subpixRcpRange=1.0/range;\nfloat subpixNSWE=lumaNS+lumaWE;\nfloat edgeHorz1=(-2.0*lumaM)+lumaNS;\nfloat edgeVert1=(-2.0*lumaM)+lumaWE;\nfloat lumaNESE=lumaNE+lumaSE;\nfloat lumaNWNE=lumaNW+lumaNE;\nfloat edgeHorz2=(-2.0*lumaE)+lumaNESE;\nfloat edgeVert2=(-2.0*lumaN)+lumaNWNE;\nfloat lumaNWSW=lumaNW+lumaSW;\nfloat lumaSWSE=lumaSW+lumaSE;\nfloat edgeHorz4=(abs(edgeHorz1)*2.0)+abs(edgeHorz2);\nfloat edgeVert4=(abs(edgeVert1)*2.0)+abs(edgeVert2);\nfloat edgeHorz3=(-2.0*lumaW)+lumaNWSW;\nfloat edgeVert3=(-2.0*lumaS)+lumaSWSE;\nfloat edgeHorz=abs(edgeHorz3)+edgeHorz4;\nfloat edgeVert=abs(edgeVert3)+edgeVert4;\nfloat subpixNWSWNESE=lumaNWSW+lumaNESE;\nfloat lengthSign=texelSize.x;\nbool horzSpan=edgeHorz>=edgeVert;\nfloat subpixA=subpixNSWE*2.0+subpixNWSWNESE;\nif (!horzSpan)\n{\nlumaN=lumaW;\n}\nif (!horzSpan) \n{\nlumaS=lumaE;\n}\nif (horzSpan) \n{\nlengthSign=texelSize.y;\n}\nfloat subpixB=(subpixA*(1.0/12.0))-lumaM;\nfloat gradientN=lumaN-lumaM;\nfloat gradientS=lumaS-lumaM;\nfloat lumaNN=lumaN+lumaM;\nfloat lumaSS=lumaS+lumaM;\nbool pairN=abs(gradientN)>=abs(gradientS);\nfloat gradient=max(abs(gradientN),abs(gradientS));\nif (pairN)\n{\nlengthSign=-lengthSign;\n}\nfloat subpixC=clamp(abs(subpixB)*subpixRcpRange,0.0,1.0);\nvec2 posB;\nposB.x=posM.x;\nposB.y=posM.y;\nvec2 offNP;\noffNP.x=(!horzSpan) ? 0.0 : texelSize.x;\noffNP.y=(horzSpan) ? 0.0 : texelSize.y;\nif (!horzSpan) \n{\nposB.x+=lengthSign*0.5;\n}\nif (horzSpan)\n{\nposB.y+=lengthSign*0.5;\n}\nvec2 posN;\nposN.x=posB.x-offNP.x*1.5;\nposN.y=posB.y-offNP.y*1.5;\nvec2 posP;\nposP.x=posB.x+offNP.x*1.5;\nposP.y=posB.y+offNP.y*1.5;\nfloat subpixD=((-2.0)*subpixC)+3.0;\nfloat lumaEndN=FxaaLuma(texture2D(textureSampler,posN,0.0));\nfloat subpixE=subpixC*subpixC;\nfloat lumaEndP=FxaaLuma(texture2D(textureSampler,posP,0.0));\nif (!pairN) \n{\nlumaNN=lumaSS;\n}\nfloat gradientScaled=gradient*1.0/4.0;\nfloat lumaMM=lumaM-lumaNN*0.5;\nfloat subpixF=subpixD*subpixE;\nbool lumaMLTZero=lumaMM<0.0;\nlumaEndN-=lumaNN*0.5;\nlumaEndP-=lumaNN*0.5;\nbool doneN=abs(lumaEndN)>=gradientScaled;\nbool doneP=abs(lumaEndP)>=gradientScaled;\nif (!doneN) \n{\nposN.x-=offNP.x*3.0;\n}\nif (!doneN) \n{\nposN.y-=offNP.y*3.0;\n}\nbool doneNP=(!doneN) || (!doneP);\nif (!doneP) \n{\nposP.x+=offNP.x*3.0;\n}\nif (!doneP)\n{\nposP.y+=offNP.y*3.0;\n}\nif (doneNP)\n{\nif (!doneN) lumaEndN=FxaaLuma(texture2D(textureSampler,posN.xy,0.0));\nif (!doneP) lumaEndP=FxaaLuma(texture2D(textureSampler,posP.xy,0.0));\nif (!doneN) lumaEndN=lumaEndN-lumaNN*0.5;\nif (!doneP) lumaEndP=lumaEndP-lumaNN*0.5;\ndoneN=abs(lumaEndN)>=gradientScaled;\ndoneP=abs(lumaEndP)>=gradientScaled;\nif (!doneN) posN.x-=offNP.x*12.0;\nif (!doneN) posN.y-=offNP.y*12.0;\ndoneNP=(!doneN) || (!doneP);\nif (!doneP) posP.x+=offNP.x*12.0;\nif (!doneP) posP.y+=offNP.y*12.0;\n}\nfloat dstN=posM.x-posN.x;\nfloat dstP=posP.x-posM.x;\nif (!horzSpan)\n{\ndstN=posM.y-posN.y;\n}\nif (!horzSpan) \n{\ndstP=posP.y-posM.y;\n}\nbool goodSpanN=(lumaEndN<0.0) != lumaMLTZero;\nfloat spanLength=(dstP+dstN);\nbool goodSpanP=(lumaEndP<0.0) != lumaMLTZero;\nfloat spanLengthRcp=1.0/spanLength;\nbool directionN=dstN<dstP;\nfloat dst=min(dstN,dstP);\nbool goodSpan=directionN ? goodSpanN : goodSpanP;\nfloat subpixG=subpixF*subpixF;\nfloat pixelOffset=(dst*(-spanLengthRcp))+0.5;\nfloat subpixH=subpixG*fxaaQualitySubpix;\nfloat pixelOffsetGood=goodSpan ? pixelOffset : 0.0;\nfloat pixelOffsetSubpix=max(pixelOffsetGood,subpixH);\nif (!horzSpan)\n{\nposM.x+=pixelOffsetSubpix*lengthSign;\n}\nif (horzSpan)\n{\nposM.y+=pixelOffsetSubpix*lengthSign;\n}\ngl_FragColor=texture2D(textureSampler,posM,0.0);\n}","circleOfConfusionPixelShader":"\nuniform sampler2D depthSampler;\n\nvarying vec2 vUV;\n\nuniform vec2 cameraMinMaxZ;\n\nuniform float focusDistance;\nuniform float cocPrecalculation;\nfloat sampleDistance(const in vec2 offset) {\nfloat depth=texture2D(depthSampler,offset).r; \nreturn (cameraMinMaxZ.x+(cameraMinMaxZ.y-cameraMinMaxZ.x)*depth)*1000.0; \n}\nvoid main(void)\n{\nfloat pixelDistance=sampleDistance(vUV);\nfloat coc=abs(cocPrecalculation* ((focusDistance-pixelDistance)/pixelDistance));\ncoc=clamp(coc,0.0,1.0);\ngl_FragColor=vec4(coc,texture2D(depthSampler,vUV).r,coc,1.0);\n}\n","depthOfFieldMergePixelShader":"\nuniform sampler2D textureSampler;\nuniform sampler2D originalSampler;\nuniform sampler2D circleOfConfusionSampler;\n#if BLUR_LEVEL>0\nuniform sampler2D blurStep1;\n#endif\n#if BLUR_LEVEL>1\nuniform sampler2D blurStep2;\n#endif\n\nvarying vec2 vUV;\nvoid main(void)\n{\nfloat coc=texture2D(circleOfConfusionSampler,vUV).r;\nvec4 original=texture2D(originalSampler,vUV);\n#if BLUR_LEVEL == 0\nvec4 blurred1=texture2D(textureSampler,vUV);\ngl_FragColor=mix(original,blurred1,coc);\n#endif\n#if BLUR_LEVEL == 1\nvec4 blurred1=texture2D(blurStep1,vUV);\nvec4 blurred2=texture2D(textureSampler,vUV); \nif(coc<0.5){\ngl_FragColor=mix(original,blurred1,coc/0.5);\n}else{\ngl_FragColor=mix(blurred1,blurred2,(coc-0.5)/0.5);\n}\n#endif\n#if BLUR_LEVEL == 2\nvec4 blurred1=texture2D(blurStep1,vUV);\nvec4 blurred2=texture2D(blurStep2,vUV);\nvec4 blurred3=texture2D(textureSampler,vUV);\nif(coc<0.33){\ngl_FragColor=mix(original,blurred1,coc/0.33);\n}else if(coc<0.66){\ngl_FragColor=mix(blurred1,blurred2,(coc-0.33)/0.33);\n}else{\ngl_FragColor=mix(blurred2,blurred3,(coc-0.66)/0.34);\n}\n#endif\n}\n","geometryVertexShader":"precision highp float;\nprecision highp int;\n#include<bonesDeclaration>\n#include<instancesDeclaration>\nattribute vec3 position;\nattribute vec3 normal;\n#if defined(ALPHATEST) || defined(NEED_UV)\nvarying vec2 vUV;\nuniform mat4 diffuseMatrix;\n#ifdef UV1\nvarying vec2 uv;\n#endif\n#ifdef UV2\nvarying vec2 uv2;\n#endif\n#endif\n\nuniform mat4 viewProjection;\nuniform mat4 view;\nvarying vec3 vNormalV;\nvarying vec4 vViewPos;\n#ifdef POSITION\nvarying vec3 vPosition;\n#endif\nvoid main(void)\n{\n#include<instancesVertex>\n#include<bonesVertex>\nvec4 pos=vec4(finalWorld*vec4(position,1.0));\nvNormalV=normalize(vec3((view*finalWorld)*vec4(normal,0.0)));\nvViewPos=view*pos;\n#ifdef POSITION\nvPosition=pos.xyz/pos.w;\n#endif\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\n#if defined(ALPHATEST) || defined(BASIC_RENDER)\n#ifdef UV1\nvUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef UV2\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n}","geometryPixelShader":"#extension GL_EXT_draw_buffers : require\nprecision highp float;\nprecision highp int;\nvarying vec3 vNormalV;\nvarying vec4 vViewPos;\n#ifdef POSITION\nvarying vec3 vPosition;\n#endif\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\n#ifdef POSITION\n#include<mrtFragmentDeclaration>[3]\n#else\n#include<mrtFragmentDeclaration>[2]\n#endif\nvoid main() {\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\ngl_FragData[0]=vec4(vViewPos.z/vViewPos.w,0.0,0.0,1.0);\n\ngl_FragData[1]=vec4(normalize(vNormalV),1.0);\n\n#ifdef POSITION\ngl_FragData[2]=vec4(vPosition,1.0);\n#endif\n}","refractionPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform sampler2D refractionSampler;\n\nuniform vec3 baseColor;\nuniform float depth;\nuniform float colorLevel;\nvoid main() {\nfloat ref=1.0-texture2D(refractionSampler,vUV).r;\nvec2 uv=vUV-vec2(0.5);\nvec2 offset=uv*depth*ref;\nvec3 sourceColor=texture2D(textureSampler,vUV-offset).rgb;\ngl_FragColor=vec4(sourceColor+sourceColor*ref*colorLevel,1.0);\n}","blackAndWhitePixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform float degree;\nvoid main(void) \n{\nvec3 color=texture2D(textureSampler,vUV).rgb;\nfloat luminance=dot(color,vec3(0.3,0.59,0.11)); \nvec3 blackAndWhite=vec3(luminance,luminance,luminance);\ngl_FragColor=vec4(color-((color-blackAndWhite)*degree),1.0);\n}","convolutionPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform vec2 screenSize;\nuniform float kernel[9];\nvoid main(void)\n{\nvec2 onePixel=vec2(1.0,1.0)/screenSize;\nvec4 colorSum =\ntexture2D(textureSampler,vUV+onePixel*vec2(-1,-1))*kernel[0] +\ntexture2D(textureSampler,vUV+onePixel*vec2(0,-1))*kernel[1] +\ntexture2D(textureSampler,vUV+onePixel*vec2(1,-1))*kernel[2] +\ntexture2D(textureSampler,vUV+onePixel*vec2(-1,0))*kernel[3] +\ntexture2D(textureSampler,vUV+onePixel*vec2(0,0))*kernel[4] +\ntexture2D(textureSampler,vUV+onePixel*vec2(1,0))*kernel[5] +\ntexture2D(textureSampler,vUV+onePixel*vec2(-1,1))*kernel[6] +\ntexture2D(textureSampler,vUV+onePixel*vec2(0,1))*kernel[7] +\ntexture2D(textureSampler,vUV+onePixel*vec2(1,1))*kernel[8];\nfloat kernelWeight =\nkernel[0] +\nkernel[1] +\nkernel[2] +\nkernel[3] +\nkernel[4] +\nkernel[5] +\nkernel[6] +\nkernel[7] +\nkernel[8];\nif (kernelWeight<=0.0) {\nkernelWeight=1.0;\n}\ngl_FragColor=vec4((colorSum/kernelWeight).rgb,1);\n}","filterPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform mat4 kernelMatrix;\nvoid main(void)\n{\nvec3 baseColor=texture2D(textureSampler,vUV).rgb;\nvec3 updatedColor=(kernelMatrix*vec4(baseColor,1.0)).rgb;\ngl_FragColor=vec4(updatedColor,1.0);\n}","volumetricLightScatteringPixelShader":"uniform sampler2D textureSampler;\nuniform sampler2D lightScatteringSampler;\nuniform float decay;\nuniform float exposure;\nuniform float weight;\nuniform float density;\nuniform vec2 meshPositionOnScreen;\nvarying vec2 vUV;\nvoid main(void) {\nvec2 tc=vUV;\nvec2 deltaTexCoord=(tc-meshPositionOnScreen.xy);\ndeltaTexCoord*=1.0/float(NUM_SAMPLES)*density;\nfloat illuminationDecay=1.0;\nvec4 color=texture2D(lightScatteringSampler,tc)*0.4;\nfor(int i=0; i<NUM_SAMPLES; i++) {\ntc-=deltaTexCoord;\nvec4 dataSample=texture2D(lightScatteringSampler,tc)*0.4;\ndataSample*=illuminationDecay*weight;\ncolor+=dataSample;\nilluminationDecay*=decay;\n}\nvec4 realColor=texture2D(textureSampler,vUV);\ngl_FragColor=((vec4((vec3(color.r,color.g,color.b)*exposure),1))+(realColor*(1.5-0.4)));\n}\n","volumetricLightScatteringPassPixelShader":"#if defined(ALPHATEST) || defined(NEED_UV)\nvarying vec2 vUV;\n#endif\n#if defined(ALPHATEST)\nuniform sampler2D diffuseSampler;\n#endif\nvoid main(void)\n{\n#if defined(ALPHATEST)\nvec4 diffuseColor=texture2D(diffuseSampler,vUV);\nif (diffuseColor.a<0.4)\ndiscard;\n#endif\ngl_FragColor=vec4(0.0,0.0,0.0,1.0);\n}\n","colorCorrectionPixelShader":"\nuniform sampler2D textureSampler; \nuniform sampler2D colorTable; \n\nvarying vec2 vUV;\n\nconst float SLICE_COUNT=16.0; \n\nvec4 sampleAs3DTexture(sampler2D textureSampler,vec3 uv,float width) {\nfloat sliceSize=1.0/width; \nfloat slicePixelSize=sliceSize/width; \nfloat sliceInnerSize=slicePixelSize*(width-1.0); \nfloat zSlice0=min(floor(uv.z*width),width-1.0);\nfloat zSlice1=min(zSlice0+1.0,width-1.0);\nfloat xOffset=slicePixelSize*0.5+uv.x*sliceInnerSize;\nfloat s0=xOffset+(zSlice0*sliceSize);\nfloat s1=xOffset+(zSlice1*sliceSize);\nvec4 slice0Color=texture2D(textureSampler,vec2(s0,uv.y));\nvec4 slice1Color=texture2D(textureSampler,vec2(s1,uv.y));\nfloat zOffset=mod(uv.z*width,1.0);\nvec4 result=mix(slice0Color,slice1Color,zOffset);\nreturn result;\n}\nvoid main(void)\n{\nvec4 screen_color=texture2D(textureSampler,vUV);\ngl_FragColor=sampleAs3DTexture(colorTable,screen_color.rgb,SLICE_COUNT);\n}","tonemapPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform float _ExposureAdjustment;\n#if defined(HABLE_TONEMAPPING)\nconst float A=0.15;\nconst float B=0.50;\nconst float C=0.10;\nconst float D=0.20;\nconst float E=0.02;\nconst float F=0.30;\nconst float W=11.2;\n#endif\nfloat Luminance(vec3 c)\n{\nreturn dot(c,vec3(0.22,0.707,0.071));\n}\nvoid main(void) \n{\nvec3 colour=texture2D(textureSampler,vUV).rgb;\n#if defined(REINHARD_TONEMAPPING)\nfloat lum=Luminance(colour.rgb); \nfloat lumTm=lum*_ExposureAdjustment;\nfloat scale=lumTm/(1.0+lumTm); \ncolour*=scale/lum;\n#elif defined(HABLE_TONEMAPPING)\ncolour*=_ExposureAdjustment;\nconst float ExposureBias=2.0;\nvec3 x=ExposureBias*colour;\nvec3 curr=((x*(A*x+C*B)+D*E)/(x*(A*x+B)+D*F))-E/F;\nx=vec3(W,W,W);\nvec3 whiteScale=1.0/(((x*(A*x+C*B)+D*E)/(x*(A*x+B)+D*F))-E/F);\ncolour=curr*whiteScale;\n#elif defined(OPTIMIZED_HEJIDAWSON_TONEMAPPING)\ncolour*=_ExposureAdjustment;\nvec3 X=max(vec3(0.0,0.0,0.0),colour-0.004);\nvec3 retColor=(X*(6.2*X+0.5))/(X*(6.2*X+1.7)+0.06);\ncolour=retColor*retColor;\n#elif defined(PHOTOGRAPHIC_TONEMAPPING)\ncolour=vec3(1.0,1.0,1.0)-exp2(-_ExposureAdjustment*colour);\n#endif\ngl_FragColor=vec4(colour.rgb,1.0);\n}","displayPassPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform sampler2D passSampler;\nvoid main(void)\n{\ngl_FragColor=texture2D(passSampler,vUV);\n}","highlightsPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nconst vec3 RGBLuminanceCoefficients=vec3(0.2126,0.7152,0.0722);\nvoid main(void) \n{\nvec4 tex=texture2D(textureSampler,vUV);\nvec3 c=tex.rgb;\nfloat luma=dot(c.rgb,RGBLuminanceCoefficients);\n\n\ngl_FragColor=vec4(pow(c,vec3(25.0-luma*15.0)),tex.a); \n}","imageProcessingPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n#include<imageProcessingDeclaration>\n#include<helperFunctions>\n#include<imageProcessingFunctions>\nvoid main(void)\n{\nvec4 result=texture2D(textureSampler,vUV);\n#ifdef IMAGEPROCESSING\n#ifndef FROMLINEARSPACE\n\nresult.rgb=toLinearSpace(result.rgb);\n#endif\nresult=applyImageProcessing(result);\n#else\n\n#ifdef FROMLINEARSPACE\nresult=applyImageProcessing(result);\n#endif\n#endif\ngl_FragColor=result;\n}","kernelBlurVertexShader":"\nattribute vec2 position;\n\nuniform vec2 delta;\n\nvarying vec2 sampleCenter;\n#include<kernelBlurVaryingDeclaration>[0..varyingCount]\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nsampleCenter=(position*madd+madd);\n#include<kernelBlurVertex>[0..varyingCount]\ngl_Position=vec4(position,0.0,1.0);\n}","kernelBlurPixelShader":"\nuniform sampler2D textureSampler;\nuniform vec2 delta;\n\nvarying vec2 sampleCenter;\n#ifdef DOF\nuniform sampler2D circleOfConfusionSampler;\nuniform vec2 cameraMinMaxZ;\nfloat sampleDistance(const in vec2 offset) {\nfloat depth=texture2D(circleOfConfusionSampler,offset).g; \nreturn cameraMinMaxZ.x+(cameraMinMaxZ.y-cameraMinMaxZ.x)*depth; \n}\n#endif\n#include<kernelBlurVaryingDeclaration>[0..varyingCount]\n#ifdef PACKEDFLOAT\nvec4 pack(float depth)\n{\nconst vec4 bit_shift=vec4(255.0*255.0*255.0,255.0*255.0,255.0,1.0);\nconst vec4 bit_mask=vec4(0.0,1.0/255.0,1.0/255.0,1.0/255.0);\nvec4 res=fract(depth*bit_shift);\nres-=res.xxyz*bit_mask;\nreturn res;\n}\nfloat unpack(vec4 color)\n{\nconst vec4 bit_shift=vec4(1.0/(255.0*255.0*255.0),1.0/(255.0*255.0),1.0/255.0,1.0);\nreturn dot(color,bit_shift);\n}\n#endif\nvoid main(void)\n{\n#ifdef DOF\nfloat sumOfWeights=0.0; \nfloat sampleDepth=0.0;\nfloat factor=0.0;\nfloat centerSampleDepth=sampleDistance(sampleCenter);\n#endif\nfloat computedWeight=0.0;\n#ifdef PACKEDFLOAT \nfloat blend=0.;\n#else\nvec4 blend=vec4(0.);\n#endif\n#include<kernelBlurFragment>[0..varyingCount]\n#include<kernelBlurFragment2>[0..depCount]\n#ifdef PACKEDFLOAT\ngl_FragColor=pack(blend);\n#else\ngl_FragColor=blend;\n#endif\n#ifdef DOF\n\nif(sumOfWeights == 0.0){\ngl_FragColor=vec4(0.0,0.0,0.0,1.0);\n}\ngl_FragColor/=sumOfWeights;\n#endif\n}","lensFlareVertexShader":"\nattribute vec2 position;\n\nuniform mat4 viewportMatrix;\n\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvUV=position*madd+madd;\ngl_Position=viewportMatrix*vec4(position,0.0,1.0);\n}","lensFlarePixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec4 color;\nvoid main(void) {\nvec4 baseColor=texture2D(textureSampler,vUV);\ngl_FragColor=baseColor*color;\n}","anaglyphPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform sampler2D leftSampler;\nvoid main(void)\n{\nvec4 leftFrag=texture2D(leftSampler,vUV);\nleftFrag=vec4(1.0,leftFrag.g,leftFrag.b,1.0);\nvec4 rightFrag=texture2D(textureSampler,vUV);\nrightFrag=vec4(rightFrag.r,1.0,1.0,1.0);\ngl_FragColor=vec4(rightFrag.rgb*leftFrag.rgb,1.0);\n}","stereoscopicInterlacePixelShader":"const vec3 TWO=vec3(2.0,2.0,2.0);\nvarying vec2 vUV;\nuniform sampler2D camASampler;\nuniform sampler2D textureSampler;\nuniform vec2 stepSize;\nvoid main(void)\n{\nbool useCamB;\nvec2 texCoord1;\nvec2 texCoord2;\nvec3 frag1;\nvec3 frag2;\n#ifdef IS_STEREOSCOPIC_HORIZ\nuseCamB=vUV.x>0.5;\ntexCoord1=vec2(useCamB ? (vUV.x-0.5)*2.0 : vUV.x*2.0,vUV.y);\ntexCoord2=vec2(texCoord1.x+stepSize.x,vUV.y);\n#else\nuseCamB=vUV.y>0.5;\ntexCoord1=vec2(vUV.x,useCamB ? (vUV.y-0.5)*2.0 : vUV.y*2.0);\ntexCoord2=vec2(vUV.x,texCoord1.y+stepSize.y);\n#endif\n\nif (useCamB){\nfrag1=texture2D(textureSampler,texCoord1).rgb;\nfrag2=texture2D(textureSampler,texCoord2).rgb;\n}else{\nfrag1=texture2D(camASampler ,texCoord1).rgb;\nfrag2=texture2D(camASampler ,texCoord2).rgb;\n}\ngl_FragColor=vec4((frag1+frag2)/TWO,1.0);\n}","vrDistortionCorrectionPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform vec2 LensCenter;\nuniform vec2 Scale;\nuniform vec2 ScaleIn;\nuniform vec4 HmdWarpParam;\nvec2 HmdWarp(vec2 in01) {\nvec2 theta=(in01-LensCenter)*ScaleIn; \nfloat rSq=theta.x*theta.x+theta.y*theta.y;\nvec2 rvector=theta*(HmdWarpParam.x+HmdWarpParam.y*rSq+HmdWarpParam.z*rSq*rSq+HmdWarpParam.w*rSq*rSq*rSq);\nreturn LensCenter+Scale*rvector;\n}\nvoid main(void)\n{\nvec2 tc=HmdWarp(vUV);\nif (tc.x <0.0 || tc.x>1.0 || tc.y<0.0 || tc.y>1.0)\ngl_FragColor=vec4(0.0,0.0,0.0,0.0);\nelse{\ngl_FragColor=texture2D(textureSampler,tc);\n}\n}","glowBlurPostProcessPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec2 screenSize;\nuniform vec2 direction;\nuniform float blurWidth;\n\nfloat getLuminance(vec3 color)\n{\nreturn dot(color,vec3(0.2126,0.7152,0.0722));\n}\nvoid main(void)\n{\nfloat weights[7];\nweights[0]=0.05;\nweights[1]=0.1;\nweights[2]=0.2;\nweights[3]=0.3;\nweights[4]=0.2;\nweights[5]=0.1;\nweights[6]=0.05;\nvec2 texelSize=vec2(1.0/screenSize.x,1.0/screenSize.y);\nvec2 texelStep=texelSize*direction*blurWidth;\nvec2 start=vUV-3.0*texelStep;\nvec4 baseColor=vec4(0.,0.,0.,0.);\nvec2 texelOffset=vec2(0.,0.);\nfor (int i=0; i<7; i++)\n{\n\nvec4 texel=texture2D(textureSampler,start+texelOffset);\nbaseColor.a+=texel.a*weights[i];\n\nfloat luminance=getLuminance(baseColor.rgb);\nfloat luminanceTexel=getLuminance(texel.rgb);\nfloat choice=step(luminanceTexel,luminance);\nbaseColor.rgb=choice*baseColor.rgb+(1.0-choice)*texel.rgb;\ntexelOffset+=texelStep;\n}\ngl_FragColor=baseColor;\n}","glowMapGenerationPixelShader":"#ifdef ALPHATEST\nvarying vec2 vUVDiffuse;\nuniform sampler2D diffuseSampler;\n#endif\n#ifdef EMISSIVE\nvarying vec2 vUVEmissive;\nuniform sampler2D emissiveSampler;\n#endif\nuniform vec4 color;\nvoid main(void)\n{\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUVDiffuse).a<0.4)\ndiscard;\n#endif\n#ifdef EMISSIVE\ngl_FragColor=texture2D(emissiveSampler,vUVEmissive)*color;\n#else\ngl_FragColor=color;\n#endif\n}","glowMapGenerationVertexShader":"\nattribute vec3 position;\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\nuniform mat4 viewProjection;\nvarying vec4 vPosition;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef ALPHATEST\nvarying vec2 vUVDiffuse;\nuniform mat4 diffuseMatrix;\n#endif\n#ifdef EMISSIVE\nvarying vec2 vUVEmissive;\nuniform mat4 emissiveMatrix;\n#endif\nvoid main(void)\n{\n#include<instancesVertex>\n#include<bonesVertex>\n#ifdef CUBEMAP\nvPosition=finalWorld*vec4(position,1.0);\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\n#else\nvPosition=viewProjection*finalWorld*vec4(position,1.0);\ngl_Position=vPosition;\n#endif\n#ifdef ALPHATEST\n#ifdef DIFFUSEUV1\nvUVDiffuse=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef DIFFUSEUV2\nvUVDiffuse=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n#ifdef EMISSIVE\n#ifdef EMISSIVEUV1\nvUVEmissive=vec2(emissiveMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef EMISSIVEUV2\nvUVEmissive=vec2(emissiveMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n}","glowMapMergePixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n#ifdef EMISSIVE\nuniform sampler2D textureSampler2;\n#endif\n\nuniform float offset;\nvoid main(void) {\nvec4 baseColor=texture2D(textureSampler,vUV);\n#ifdef EMISSIVE\nbaseColor+=texture2D(textureSampler2,vUV);\nbaseColor*=offset;\n#else\nbaseColor.a=abs(offset-baseColor.a);\n#ifdef STROKE\nfloat alpha=smoothstep(.0,.1,baseColor.a);\nbaseColor.a=alpha;\nbaseColor.rgb=baseColor.rgb*alpha;\n#endif\n#endif\ngl_FragColor=baseColor;\n}","glowMapMergeVertexShader":"\nattribute vec2 position;\n\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) {\nvUV=position*madd+madd;\ngl_Position=vec4(position,0.0,1.0);\n}","lineVertexShader":"\nattribute vec3 position;\nattribute vec4 normal;\n\nuniform mat4 worldViewProjection;\nuniform float width;\nuniform float aspectRatio;\nvoid main(void) {\nvec4 viewPosition=worldViewProjection*vec4(position,1.0);\nvec4 viewPositionNext=worldViewProjection*vec4(normal.xyz,1.0);\nvec2 currentScreen=viewPosition.xy/viewPosition.w;\nvec2 nextScreen=viewPositionNext.xy/viewPositionNext.w;\ncurrentScreen.x*=aspectRatio;\nnextScreen.x*=aspectRatio;\nvec2 dir=normalize(nextScreen-currentScreen);\nvec2 normalDir=vec2(-dir.y,dir.x);\nnormalDir*=width/2.0;\nnormalDir.x/=aspectRatio;\nvec4 offset=vec4(normalDir*normal.w,0.0,0.0);\ngl_Position=viewPosition+offset;\n}","linePixelShader":"uniform vec4 color;\nvoid main(void) {\ngl_FragColor=color;\n}","outlineVertexShader":"\nattribute vec3 position;\nattribute vec3 normal;\n#include<bonesDeclaration>\n\nuniform float offset;\n#include<instancesDeclaration>\nuniform mat4 viewProjection;\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform mat4 diffuseMatrix;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#endif\n#include<logDepthDeclaration>\nvoid main(void)\n{\nvec3 offsetPosition=position+normal*offset;\n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(offsetPosition,1.0);\n#ifdef ALPHATEST\n#ifdef UV1\nvUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef UV2\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n#include<logDepthVertex>\n}\n","outlinePixelShader":"#ifdef LOGARITHMICDEPTH\n#extension GL_EXT_frag_depth : enable\n#endif\nuniform vec4 color;\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\n#include<logDepthDeclaration>\nvoid main(void) {\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\n#include<logDepthFragment>\ngl_FragColor=color;\n}","layerVertexShader":"\nattribute vec2 position;\n\nuniform vec2 scale;\nuniform vec2 offset;\nuniform mat4 textureMatrix;\n\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvec2 shiftedPosition=position*scale+offset;\nvUV=vec2(textureMatrix*vec4(shiftedPosition*madd+madd,1.0,0.0));\ngl_Position=vec4(shiftedPosition,0.0,1.0);\n}","layerPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec4 color;\nvoid main(void) {\nvec4 baseColor=texture2D(textureSampler,vUV);\n#ifdef ALPHATEST\nif (baseColor.a<0.4)\ndiscard;\n#endif\ngl_FragColor=baseColor*color;\n}","backgroundVertexShader":"precision highp float;\n#include<__decl__backgroundVertex>\n#include<helperFunctions>\n\nattribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\n#endif\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif\n#ifdef MAINUV2\nvarying vec2 vMainUV2; \n#endif\n#if defined(DIFFUSE) && DIFFUSEDIRECTUV == 0\nvarying vec2 vDiffuseUV;\n#endif\n#include<clipPlaneVertexDeclaration>\n#include<fogVertexDeclaration>\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\nvoid main(void) {\n#ifdef REFLECTIONMAP_SKYBOX\nvPositionUVW=position;\n#endif \n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\nvec4 worldPos=finalWorld*vec4(position,1.0);\nvPositionW=vec3(worldPos);\n#ifdef NORMAL\nmat3 normalWorld=mat3(finalWorld);\n#ifdef NONUNIFORMSCALING\nnormalWorld=transposeMat3(inverseMat3(normalWorld));\n#endif\nvNormalW=normalize(normalWorld*normal);\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvDirectionW=normalize(vec3(finalWorld*vec4(position,0.0)));\n#ifdef EQUIRECTANGULAR_RELFECTION_FOV\nmat3 screenToWorld=inverseMat3(mat3(finalWorld*viewProjection));\nvec3 segment=mix(vDirectionW,screenToWorld*vec3(0.0,0.0,1.0),abs(fFovMultiplier-1.0));\nif (fFovMultiplier<=1.0) {\nvDirectionW=normalize(segment);\n} else {\nvDirectionW=normalize(vDirectionW+(vDirectionW-segment));\n}\n#endif\n#endif\n#ifndef UV1\nvec2 uv=vec2(0.,0.);\n#endif\n#ifndef UV2\nvec2 uv2=vec2(0.,0.);\n#endif\n#ifdef MAINUV1\nvMainUV1=uv;\n#endif \n#ifdef MAINUV2\nvMainUV2=uv2;\n#endif\n#if defined(DIFFUSE) && DIFFUSEDIRECTUV == 0 \nif (vDiffuseInfos.x == 0.)\n{\nvDiffuseUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvDiffuseUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n\n#include<clipPlaneVertex>\n\n#include<fogVertex>\n\n#include<shadowsVertex>[0..maxSimultaneousLights]\n\n#ifdef VERTEXCOLOR\nvColor=color;\n#endif\n\n#ifdef POINTSIZE\ngl_PointSize=pointSize;\n#endif\n}\n","backgroundPixelShader":"#ifdef TEXTURELODSUPPORT\n#extension GL_EXT_shader_texture_lod : enable\n#endif\nprecision highp float;\n#include<__decl__backgroundFragment>\n#define RECIPROCAL_PI2 0.15915494\n\nuniform vec3 vEyePosition;\n\nvarying vec3 vPositionW;\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif \n#ifdef MAINUV2 \nvarying vec2 vMainUV2; \n#endif \n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef DIFFUSE\n#if DIFFUSEDIRECTUV == 1\n#define vDiffuseUV vMainUV1\n#elif DIFFUSEDIRECTUV == 2\n#define vDiffuseUV vMainUV2\n#else\nvarying vec2 vDiffuseUV;\n#endif\nuniform sampler2D diffuseSampler;\n#endif\n\n#ifdef REFLECTION\n#ifdef REFLECTIONMAP_3D\n#define sampleReflection(s,c) textureCube(s,c)\nuniform samplerCube reflectionSampler;\n#ifdef TEXTURELODSUPPORT\n#define sampleReflectionLod(s,c,l) textureCubeLodEXT(s,c,l)\n#else\nuniform samplerCube reflectionSamplerLow;\nuniform samplerCube reflectionSamplerHigh;\n#endif\n#else\n#define sampleReflection(s,c) texture2D(s,c)\nuniform sampler2D reflectionSampler;\n#ifdef TEXTURELODSUPPORT\n#define sampleReflectionLod(s,c,l) texture2DLodEXT(s,c,l)\n#else\nuniform samplerCube reflectionSamplerLow;\nuniform samplerCube reflectionSamplerHigh;\n#endif\n#endif\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#else\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#endif\n#include<reflectionFunction>\n#endif\n\n#ifndef FROMLINEARSPACE\n#define FROMLINEARSPACE;\n#endif\n\n#ifndef SHADOWONLY\n#define SHADOWONLY;\n#endif\n#include<imageProcessingDeclaration>\n\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#include<helperFunctions>\n#include<lightsFragmentFunctions>\n#include<shadowsFragmentFunctions>\n#include<imageProcessingFunctions>\n#include<clipPlaneFragmentDeclaration>\n\n#include<fogFragmentDeclaration>\n#ifdef REFLECTIONFRESNEL\n#define FRESNEL_MAXIMUM_ON_ROUGH 0.25\nvec3 fresnelSchlickEnvironmentGGX(float VdotN,vec3 reflectance0,vec3 reflectance90,float smoothness)\n{\n\nfloat weight=mix(FRESNEL_MAXIMUM_ON_ROUGH,1.0,smoothness);\nreturn reflectance0+weight*(reflectance90-reflectance0)*pow(clamp(1.0-VdotN,0.,1.),5.0);\n}\n#endif\nvoid main(void) {\n#include<clipPlaneFragment>\nvec3 viewDirectionW=normalize(vEyePosition-vPositionW);\n\n#ifdef NORMAL\nvec3 normalW=normalize(vNormalW);\n#else\nvec3 normalW=vec3(0.0,1.0,0.0);\n#endif\n\nfloat shadow=1.;\nfloat globalShadow=0.;\nfloat shadowLightCount=0.;\n#include<lightFragment>[0..maxSimultaneousLights]\n#ifdef SHADOWINUSE\nglobalShadow/=shadowLightCount;\n#else\nglobalShadow=1.0;\n#endif\n\nvec3 reflectionColor=vec3(1.,1.,1.);\n#ifdef REFLECTION\nvec3 reflectionVector=computeReflectionCoords(vec4(vPositionW,1.0),normalW);\n#ifdef REFLECTIONMAP_OPPOSITEZ\nreflectionVector.z*=-1.0;\n#endif\n\n#ifdef REFLECTIONMAP_3D\nvec3 reflectionCoords=reflectionVector;\n#else\nvec2 reflectionCoords=reflectionVector.xy;\n#ifdef REFLECTIONMAP_PROJECTION\nreflectionCoords/=reflectionVector.z;\n#endif\nreflectionCoords.y=1.0-reflectionCoords.y;\n#endif\n#ifdef REFLECTIONBLUR\nfloat reflectionLOD=vReflectionInfos.y;\n#ifdef TEXTURELODSUPPORT\n\nreflectionLOD=reflectionLOD*log2(vReflectionMicrosurfaceInfos.x)*vReflectionMicrosurfaceInfos.y+vReflectionMicrosurfaceInfos.z;\nreflectionColor=sampleReflectionLod(reflectionSampler,reflectionCoords,reflectionLOD).rgb;\n#else\nfloat lodReflectionNormalized=clamp(reflectionLOD,0.,1.);\nfloat lodReflectionNormalizedDoubled=lodReflectionNormalized*2.0;\nvec3 reflectionSpecularMid=sampleReflection(reflectionSampler,reflectionCoords).rgb;\nif(lodReflectionNormalizedDoubled<1.0){\nreflectionColor=mix(\nsampleReflection(reflectionSamplerHigh,reflectionCoords).rgb,\nreflectionSpecularMid,\nlodReflectionNormalizedDoubled\n);\n} else {\nreflectionColor=mix(\nreflectionSpecularMid,\nsampleReflection(reflectionSamplerLow,reflectionCoords).rgb,\nlodReflectionNormalizedDoubled-1.0\n);\n}\n#endif\n#else\nvec4 reflectionSample=sampleReflection(reflectionSampler,reflectionCoords);\nreflectionColor=reflectionSample.rgb;\n#endif\n#ifdef GAMMAREFLECTION\nreflectionColor=toLinearSpace(reflectionColor.rgb);\n#endif\n\nreflectionColor*=vReflectionInfos.x;\n#endif\n\nvec3 diffuseColor=vec3(1.,1.,1.);\nfloat finalAlpha=alpha;\n#ifdef DIFFUSE\nvec4 diffuseMap=texture2D(diffuseSampler,vDiffuseUV);\n#ifdef GAMMADIFFUSE\ndiffuseMap.rgb=toLinearSpace(diffuseMap.rgb);\n#endif\n\ndiffuseMap.rgb*=vDiffuseInfos.y;\n#ifdef DIFFUSEHASALPHA\nfinalAlpha*=diffuseMap.a;\n#endif\ndiffuseColor=diffuseMap.rgb;\n#endif\n\n#ifdef REFLECTIONFRESNEL\nvec3 colorBase=diffuseColor;\n#else\nvec3 colorBase=reflectionColor*diffuseColor;\n#endif\ncolorBase=max(colorBase,0.0);\n\n#ifdef USERGBCOLOR\nvec3 finalColor=colorBase;\n#else\nvec3 finalColor=colorBase.r*vPrimaryColor.rgb*vPrimaryColor.a;\nfinalColor+=colorBase.g*vSecondaryColor.rgb*vSecondaryColor.a;\nfinalColor+=colorBase.b*vTertiaryColor.rgb*vTertiaryColor.a;\n#endif\n\n#ifdef REFLECTIONFRESNEL\nvec3 reflectionAmount=vReflectionControl.xxx;\nvec3 reflectionReflectance0=vReflectionControl.yyy;\nvec3 reflectionReflectance90=vReflectionControl.zzz;\nfloat VdotN=dot(normalize(vEyePosition),normalW);\nvec3 planarReflectionFresnel=fresnelSchlickEnvironmentGGX(clamp(VdotN,0.0,1.0),reflectionReflectance0,reflectionReflectance90,1.0);\nreflectionAmount*=planarReflectionFresnel;\n#ifdef REFLECTIONFALLOFF\nfloat reflectionDistanceFalloff=1.0-clamp(length(vPositionW.xyz-vBackgroundCenter)*vReflectionControl.w,0.0,1.0);\nreflectionDistanceFalloff*=reflectionDistanceFalloff;\nreflectionAmount*=reflectionDistanceFalloff;\n#endif\nfinalColor=mix(finalColor,reflectionColor,clamp(reflectionAmount,0.,1.));\n#endif\n#ifdef OPACITYFRESNEL\nfloat viewAngleToFloor=dot(normalW,normalize(vEyePosition-vBackgroundCenter));\n\nconst float startAngle=0.1;\nfloat fadeFactor=clamp(viewAngleToFloor/startAngle,0.0,1.0);\nfinalAlpha*=fadeFactor*fadeFactor;\n#endif\n\n#ifdef SHADOWINUSE\nfinalColor=mix(finalColor*shadowLevel,finalColor,globalShadow);\n#endif\n\nvec4 color=vec4(finalColor,finalAlpha);\n#include<fogFragment>\n#ifdef IMAGEPROCESSINGPOSTPROCESS\n\n\ncolor.rgb=clamp(color.rgb,0.,30.0);\n#else\n\ncolor=applyImageProcessing(color);\n#endif\n#ifdef PREMULTIPLYALPHA\n\ncolor.rgb*=color.a;\n#endif\n#ifdef NOISE\ncolor.rgb=dither(vPositionW.xy,color.rgb);\n#endif\ngl_FragColor=color;\n}\n"};
  88121. BABYLON.Effect.IncludesShadersStore={"depthPrePass":"#ifdef DEPTHPREPASS\ngl_FragColor=vec4(0.,0.,0.,1.0);\nreturn;\n#endif","bonesDeclaration":"#if NUM_BONE_INFLUENCERS>0\nuniform mat4 mBones[BonesPerMesh];\nattribute vec4 matricesIndices;\nattribute vec4 matricesWeights;\n#if NUM_BONE_INFLUENCERS>4\nattribute vec4 matricesIndicesExtra;\nattribute vec4 matricesWeightsExtra;\n#endif\n#endif","instancesDeclaration":"#ifdef INSTANCES\nattribute vec4 world0;\nattribute vec4 world1;\nattribute vec4 world2;\nattribute vec4 world3;\n#else\nuniform mat4 world;\n#endif","pointCloudVertexDeclaration":"#ifdef POINTSIZE\nuniform float pointSize;\n#endif","bumpVertexDeclaration":"#if defined(BUMP) || defined(PARALLAX)\n#if defined(TANGENT) && defined(NORMAL) \nvarying mat3 vTBN;\n#endif\n#endif\n","clipPlaneVertexDeclaration":"#ifdef CLIPPLANE\nuniform vec4 vClipPlane;\nvarying float fClipDistance;\n#endif","fogVertexDeclaration":"#ifdef FOG\nvarying vec3 vFogDistance;\n#endif","morphTargetsVertexGlobalDeclaration":"#ifdef MORPHTARGETS\nuniform float morphTargetInfluences[NUM_MORPH_INFLUENCERS];\n#endif","morphTargetsVertexDeclaration":"#ifdef MORPHTARGETS\nattribute vec3 position{X};\n#ifdef MORPHTARGETS_NORMAL\nattribute vec3 normal{X};\n#endif\n#ifdef MORPHTARGETS_TANGENT\nattribute vec3 tangent{X};\n#endif\n#endif","logDepthDeclaration":"#ifdef LOGARITHMICDEPTH\nuniform float logarithmicDepthConstant;\nvarying float vFragmentDepth;\n#endif","morphTargetsVertex":"#ifdef MORPHTARGETS\npositionUpdated+=(position{X}-position)*morphTargetInfluences[{X}];\n#ifdef MORPHTARGETS_NORMAL\nnormalUpdated+=(normal{X}-normal)*morphTargetInfluences[{X}];\n#endif\n#ifdef MORPHTARGETS_TANGENT\ntangentUpdated.xyz+=(tangent{X}-tangent.xyz)*morphTargetInfluences[{X}];\n#endif\n#endif","instancesVertex":"#ifdef INSTANCES\nmat4 finalWorld=mat4(world0,world1,world2,world3);\n#else\nmat4 finalWorld=world;\n#endif","bonesVertex":"#if NUM_BONE_INFLUENCERS>0\nmat4 influence;\ninfluence=mBones[int(matricesIndices[0])]*matricesWeights[0];\n#if NUM_BONE_INFLUENCERS>1\ninfluence+=mBones[int(matricesIndices[1])]*matricesWeights[1];\n#endif \n#if NUM_BONE_INFLUENCERS>2\ninfluence+=mBones[int(matricesIndices[2])]*matricesWeights[2];\n#endif \n#if NUM_BONE_INFLUENCERS>3\ninfluence+=mBones[int(matricesIndices[3])]*matricesWeights[3];\n#endif \n#if NUM_BONE_INFLUENCERS>4\ninfluence+=mBones[int(matricesIndicesExtra[0])]*matricesWeightsExtra[0];\n#endif \n#if NUM_BONE_INFLUENCERS>5\ninfluence+=mBones[int(matricesIndicesExtra[1])]*matricesWeightsExtra[1];\n#endif \n#if NUM_BONE_INFLUENCERS>6\ninfluence+=mBones[int(matricesIndicesExtra[2])]*matricesWeightsExtra[2];\n#endif \n#if NUM_BONE_INFLUENCERS>7\ninfluence+=mBones[int(matricesIndicesExtra[3])]*matricesWeightsExtra[3];\n#endif \nfinalWorld=finalWorld*influence;\n#endif","bumpVertex":"#if defined(BUMP) || defined(PARALLAX)\n#if defined(TANGENT) && defined(NORMAL)\nvec3 tbnNormal=normalize(normalUpdated);\nvec3 tbnTangent=normalize(tangentUpdated.xyz);\nvec3 tbnBitangent=cross(tbnNormal,tbnTangent)*tangentUpdated.w;\nvTBN=mat3(finalWorld)*mat3(tbnTangent,tbnBitangent,tbnNormal);\n#endif\n#endif","clipPlaneVertex":"#ifdef CLIPPLANE\nfClipDistance=dot(worldPos,vClipPlane);\n#endif","fogVertex":"#ifdef FOG\nvFogDistance=(view*worldPos).xyz;\n#endif","shadowsVertex":"#ifdef SHADOWS\n#if defined(SHADOW{X}) && !defined(SHADOWCUBE{X})\nvPositionFromLight{X}=lightMatrix{X}*worldPos;\nvDepthMetric{X}=((vPositionFromLight{X}.z+light{X}.depthValues.x)/(light{X}.depthValues.y));\n#endif\n#endif","pointCloudVertex":"#ifdef POINTSIZE\ngl_PointSize=pointSize;\n#endif","logDepthVertex":"#ifdef LOGARITHMICDEPTH\nvFragmentDepth=1.0+gl_Position.w;\ngl_Position.z=log2(max(0.000001,vFragmentDepth))*logarithmicDepthConstant;\n#endif","helperFunctions":"const float PI=3.1415926535897932384626433832795;\nconst float LinearEncodePowerApprox=2.2;\nconst float GammaEncodePowerApprox=1.0/LinearEncodePowerApprox;\nconst vec3 LuminanceEncodeApprox=vec3(0.2126,0.7152,0.0722);\nmat3 transposeMat3(mat3 inMatrix) {\nvec3 i0=inMatrix[0];\nvec3 i1=inMatrix[1];\nvec3 i2=inMatrix[2];\nmat3 outMatrix=mat3(\nvec3(i0.x,i1.x,i2.x),\nvec3(i0.y,i1.y,i2.y),\nvec3(i0.z,i1.z,i2.z)\n);\nreturn outMatrix;\n}\n\nmat3 inverseMat3(mat3 inMatrix) {\nfloat a00=inMatrix[0][0],a01=inMatrix[0][1],a02=inMatrix[0][2];\nfloat a10=inMatrix[1][0],a11=inMatrix[1][1],a12=inMatrix[1][2];\nfloat a20=inMatrix[2][0],a21=inMatrix[2][1],a22=inMatrix[2][2];\nfloat b01=a22*a11-a12*a21;\nfloat b11=-a22*a10+a12*a20;\nfloat b21=a21*a10-a11*a20;\nfloat det=a00*b01+a01*b11+a02*b21;\nreturn mat3(b01,(-a22*a01+a02*a21),(a12*a01-a02*a11),\nb11,(a22*a00-a02*a20),(-a12*a00+a02*a10),\nb21,(-a21*a00+a01*a20),(a11*a00-a01*a10))/det;\n}\nfloat computeFallOff(float value,vec2 clipSpace,float frustumEdgeFalloff)\n{\nfloat mask=smoothstep(1.0-frustumEdgeFalloff,1.0,clamp(dot(clipSpace,clipSpace),0.,1.));\nreturn mix(value,1.0,mask);\n}\nvec3 applyEaseInOut(vec3 x){\nreturn x*x*(3.0-2.0*x);\n}\nvec3 toLinearSpace(vec3 color)\n{\nreturn pow(color,vec3(LinearEncodePowerApprox));\n}\nvec3 toGammaSpace(vec3 color)\n{\nreturn pow(color,vec3(GammaEncodePowerApprox));\n}\nfloat square(float value)\n{\nreturn value*value;\n}\nfloat getLuminance(vec3 color)\n{\nreturn clamp(dot(color,LuminanceEncodeApprox),0.,1.);\n}\n\nfloat getRand(vec2 seed) {\nreturn fract(sin(dot(seed.xy ,vec2(12.9898,78.233)))*43758.5453);\n}\nvec3 dither(vec2 seed,vec3 color) {\nfloat rand=getRand(seed);\ncolor+=mix(-0.5/255.0,0.5/255.0,rand);\ncolor=max(color,0.0);\nreturn color;\n}","lightFragmentDeclaration":"#ifdef LIGHT{X}\nuniform vec4 vLightData{X};\nuniform vec4 vLightDiffuse{X};\n#ifdef SPECULARTERM\nuniform vec3 vLightSpecular{X};\n#else\nvec3 vLightSpecular{X}=vec3(0.);\n#endif\n#ifdef SHADOW{X}\n#if defined(SHADOWCUBE{X})\nuniform samplerCube shadowSampler{X};\n#else\nvarying vec4 vPositionFromLight{X};\nvarying float vDepthMetric{X};\nuniform sampler2D shadowSampler{X};\nuniform mat4 lightMatrix{X};\n#endif\nuniform vec4 shadowsInfo{X};\nuniform vec2 depthValues{X};\n#endif\n#ifdef SPOTLIGHT{X}\nuniform vec4 vLightDirection{X};\n#endif\n#ifdef HEMILIGHT{X}\nuniform vec3 vLightGround{X};\n#endif\n#ifdef PROJECTEDLIGHTTEXTURE{X}\nuniform mat4 textureProjectionMatrix{X};\nuniform sampler2D projectionLightSampler{X};\n#endif\n#endif","lightsFragmentFunctions":"\nstruct lightingInfo\n{\nvec3 diffuse;\n#ifdef SPECULARTERM\nvec3 specular;\n#endif\n#ifdef NDOTL\nfloat ndl;\n#endif\n};\nlightingInfo computeLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec3 diffuseColor,vec3 specularColor,float range,float glossiness) {\nlightingInfo result;\nvec3 lightVectorW;\nfloat attenuation=1.0;\nif (lightData.w == 0.)\n{\nvec3 direction=lightData.xyz-vPositionW;\nattenuation=max(0.,1.0-length(direction)/range);\nlightVectorW=normalize(direction);\n}\nelse\n{\nlightVectorW=normalize(-lightData.xyz);\n}\n\nfloat ndl=max(0.,dot(vNormal,lightVectorW));\n#ifdef NDOTL\nresult.ndl=ndl;\n#endif\nresult.diffuse=ndl*diffuseColor*attenuation;\n#ifdef SPECULARTERM\n\nvec3 angleW=normalize(viewDirectionW+lightVectorW);\nfloat specComp=max(0.,dot(vNormal,angleW));\nspecComp=pow(specComp,max(1.,glossiness));\nresult.specular=specComp*specularColor*attenuation;\n#endif\nreturn result;\n}\nlightingInfo computeSpotLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec4 lightDirection,vec3 diffuseColor,vec3 specularColor,float range,float glossiness) {\nlightingInfo result;\nvec3 direction=lightData.xyz-vPositionW;\nvec3 lightVectorW=normalize(direction);\nfloat attenuation=max(0.,1.0-length(direction)/range);\n\nfloat cosAngle=max(0.,dot(lightDirection.xyz,-lightVectorW));\nif (cosAngle>=lightDirection.w)\n{\ncosAngle=max(0.,pow(cosAngle,lightData.w));\nattenuation*=cosAngle;\n\nfloat ndl=max(0.,dot(vNormal,lightVectorW));\n#ifdef NDOTL\nresult.ndl=ndl;\n#endif\nresult.diffuse=ndl*diffuseColor*attenuation;\n#ifdef SPECULARTERM\n\nvec3 angleW=normalize(viewDirectionW+lightVectorW);\nfloat specComp=max(0.,dot(vNormal,angleW));\nspecComp=pow(specComp,max(1.,glossiness));\nresult.specular=specComp*specularColor*attenuation;\n#endif\nreturn result;\n}\nresult.diffuse=vec3(0.);\n#ifdef SPECULARTERM\nresult.specular=vec3(0.);\n#endif\n#ifdef NDOTL\nresult.ndl=0.;\n#endif\nreturn result;\n}\nlightingInfo computeHemisphericLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec3 diffuseColor,vec3 specularColor,vec3 groundColor,float glossiness) {\nlightingInfo result;\n\nfloat ndl=dot(vNormal,lightData.xyz)*0.5+0.5;\n#ifdef NDOTL\nresult.ndl=ndl;\n#endif\nresult.diffuse=mix(groundColor,diffuseColor,ndl);\n#ifdef SPECULARTERM\n\nvec3 angleW=normalize(viewDirectionW+lightData.xyz);\nfloat specComp=max(0.,dot(vNormal,angleW));\nspecComp=pow(specComp,max(1.,glossiness));\nresult.specular=specComp*specularColor;\n#endif\nreturn result;\n}\nvec3 computeProjectionTextureDiffuseLighting(sampler2D projectionLightSampler,mat4 textureProjectionMatrix){\nvec4 strq=textureProjectionMatrix*vec4(vPositionW,1.0);\nstrq/=strq.w;\nvec3 textureColor=texture2D(projectionLightSampler,strq.xy).rgb;\n#ifdef PBR\ntextureColor=toLinearSpace(textureColor);\n#endif\nreturn textureColor;\n}","lightUboDeclaration":"#ifdef LIGHT{X}\nuniform Light{X}\n{\nvec4 vLightData;\nvec4 vLightDiffuse;\nvec3 vLightSpecular;\n#ifdef SPOTLIGHT{X}\nvec4 vLightDirection;\n#endif\n#ifdef HEMILIGHT{X}\nvec3 vLightGround;\n#endif\nvec4 shadowsInfo;\nvec2 depthValues;\n} light{X};\n#ifdef PROJECTEDLIGHTTEXTURE{X}\nuniform mat4 textureProjectionMatrix{X};\nuniform sampler2D projectionLightSampler{X};\n#endif\n#ifdef SHADOW{X}\n#if defined(SHADOWCUBE{X})\nuniform samplerCube shadowSampler{X};\n#else\nvarying vec4 vPositionFromLight{X};\nvarying float vDepthMetric{X};\nuniform sampler2D shadowSampler{X};\nuniform mat4 lightMatrix{X};\n#endif\n#endif\n#endif","defaultVertexDeclaration":"\nuniform mat4 viewProjection;\nuniform mat4 view;\n#ifdef DIFFUSE\nuniform mat4 diffuseMatrix;\nuniform vec2 vDiffuseInfos;\n#endif\n#ifdef AMBIENT\nuniform mat4 ambientMatrix;\nuniform vec2 vAmbientInfos;\n#endif\n#ifdef OPACITY\nuniform mat4 opacityMatrix;\nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nuniform vec2 vEmissiveInfos;\nuniform mat4 emissiveMatrix;\n#endif\n#ifdef LIGHTMAP\nuniform vec2 vLightmapInfos;\nuniform mat4 lightmapMatrix;\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM)\nuniform vec2 vSpecularInfos;\nuniform mat4 specularMatrix;\n#endif\n#ifdef BUMP\nuniform vec3 vBumpInfos;\nuniform mat4 bumpMatrix;\n#endif\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif\n","defaultFragmentDeclaration":"uniform vec4 vDiffuseColor;\n#ifdef SPECULARTERM\nuniform vec4 vSpecularColor;\n#endif\nuniform vec3 vEmissiveColor;\n\n#ifdef DIFFUSE\nuniform vec2 vDiffuseInfos;\n#endif\n#ifdef AMBIENT\nuniform vec2 vAmbientInfos;\n#endif\n#ifdef OPACITY \nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nuniform vec2 vEmissiveInfos;\n#endif\n#ifdef LIGHTMAP\nuniform vec2 vLightmapInfos;\n#endif\n#ifdef BUMP\nuniform vec3 vBumpInfos;\nuniform vec2 vTangentSpaceParams;\n#endif\n#if defined(REFLECTIONMAP_SPHERICAL) || defined(REFLECTIONMAP_PROJECTION) || defined(REFRACTION)\nuniform mat4 view;\n#endif\n#ifdef REFRACTION\nuniform vec4 vRefractionInfos;\n#ifndef REFRACTIONMAP_3D\nuniform mat4 refractionMatrix;\n#endif\n#ifdef REFRACTIONFRESNEL\nuniform vec4 refractionLeftColor;\nuniform vec4 refractionRightColor;\n#endif\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM)\nuniform vec2 vSpecularInfos;\n#endif\n#ifdef DIFFUSEFRESNEL\nuniform vec4 diffuseLeftColor;\nuniform vec4 diffuseRightColor;\n#endif\n#ifdef OPACITYFRESNEL\nuniform vec4 opacityParts;\n#endif\n#ifdef EMISSIVEFRESNEL\nuniform vec4 emissiveLeftColor;\nuniform vec4 emissiveRightColor;\n#endif\n\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;\n#ifdef REFLECTIONMAP_SKYBOX\n#else\n#if defined(REFLECTIONMAP_PLANAR) || defined(REFLECTIONMAP_CUBIC) || defined(REFLECTIONMAP_PROJECTION)\nuniform mat4 reflectionMatrix;\n#endif\n#if defined(USE_LOCAL_REFLECTIONMAP_CUBIC) && defined(REFLECTIONMAP_CUBIC)\nuniform vec3 vReflectionPosition;\nuniform vec3 vReflectionSize; \n#endif\n#endif\n#ifdef REFLECTIONFRESNEL\nuniform vec4 reflectionLeftColor;\nuniform vec4 reflectionRightColor;\n#endif\n#endif","defaultUboDeclaration":"layout(std140,column_major) uniform;\nuniform Material\n{\nvec4 diffuseLeftColor;\nvec4 diffuseRightColor;\nvec4 opacityParts;\nvec4 reflectionLeftColor;\nvec4 reflectionRightColor;\nvec4 refractionLeftColor;\nvec4 refractionRightColor;\nvec4 emissiveLeftColor; \nvec4 emissiveRightColor;\nvec2 vDiffuseInfos;\nvec2 vAmbientInfos;\nvec2 vOpacityInfos;\nvec2 vReflectionInfos;\nvec3 vReflectionPosition;\nvec3 vReflectionSize;\nvec2 vEmissiveInfos;\nvec2 vLightmapInfos;\nvec2 vSpecularInfos;\nvec3 vBumpInfos;\nmat4 diffuseMatrix;\nmat4 ambientMatrix;\nmat4 opacityMatrix;\nmat4 reflectionMatrix;\nmat4 emissiveMatrix;\nmat4 lightmapMatrix;\nmat4 specularMatrix;\nmat4 bumpMatrix; \nvec4 vTangentSpaceParams;\nmat4 refractionMatrix;\nvec4 vRefractionInfos;\nvec4 vSpecularColor;\nvec3 vEmissiveColor;\nvec4 vDiffuseColor;\nfloat pointSize; \n};\nuniform Scene {\nmat4 viewProjection;\nmat4 view;\n};","shadowsFragmentFunctions":"#ifdef SHADOWS\n#ifndef SHADOWFLOAT\nfloat unpack(vec4 color)\n{\nconst vec4 bit_shift=vec4(1.0/(255.0*255.0*255.0),1.0/(255.0*255.0),1.0/255.0,1.0);\nreturn dot(color,bit_shift);\n}\n#endif\nfloat computeShadowCube(vec3 lightPosition,samplerCube shadowSampler,float darkness,vec2 depthValues)\n{\nvec3 directionToLight=vPositionW-lightPosition;\nfloat depth=length(directionToLight);\ndepth=(depth+depthValues.x)/(depthValues.y);\ndepth=clamp(depth,0.,1.0);\ndirectionToLight=normalize(directionToLight);\ndirectionToLight.y=-directionToLight.y;\n#ifndef SHADOWFLOAT\nfloat shadow=unpack(textureCube(shadowSampler,directionToLight));\n#else\nfloat shadow=textureCube(shadowSampler,directionToLight).x;\n#endif\nif (depth>shadow)\n{\nreturn darkness;\n}\nreturn 1.0;\n}\nfloat computeShadowWithPCFCube(vec3 lightPosition,samplerCube shadowSampler,float mapSize,float darkness,vec2 depthValues)\n{\nvec3 directionToLight=vPositionW-lightPosition;\nfloat depth=length(directionToLight);\ndepth=(depth+depthValues.x)/(depthValues.y);\ndepth=clamp(depth,0.,1.0);\ndirectionToLight=normalize(directionToLight);\ndirectionToLight.y=-directionToLight.y;\nfloat visibility=1.;\nvec3 poissonDisk[4];\npoissonDisk[0]=vec3(-1.0,1.0,-1.0);\npoissonDisk[1]=vec3(1.0,-1.0,-1.0);\npoissonDisk[2]=vec3(-1.0,-1.0,-1.0);\npoissonDisk[3]=vec3(1.0,-1.0,1.0);\n\n#ifndef SHADOWFLOAT\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[0]*mapSize))<depth) visibility-=0.25;\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[1]*mapSize))<depth) visibility-=0.25;\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[2]*mapSize))<depth) visibility-=0.25;\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[3]*mapSize))<depth) visibility-=0.25;\n#else\nif (textureCube(shadowSampler,directionToLight+poissonDisk[0]*mapSize).x<depth) visibility-=0.25;\nif (textureCube(shadowSampler,directionToLight+poissonDisk[1]*mapSize).x<depth) visibility-=0.25;\nif (textureCube(shadowSampler,directionToLight+poissonDisk[2]*mapSize).x<depth) visibility-=0.25;\nif (textureCube(shadowSampler,directionToLight+poissonDisk[3]*mapSize).x<depth) visibility-=0.25;\n#endif\nreturn min(1.0,visibility+darkness);\n}\nfloat computeShadowWithESMCube(vec3 lightPosition,samplerCube shadowSampler,float darkness,float depthScale,vec2 depthValues)\n{\nvec3 directionToLight=vPositionW-lightPosition;\nfloat depth=length(directionToLight);\ndepth=(depth+depthValues.x)/(depthValues.y);\nfloat shadowPixelDepth=clamp(depth,0.,1.0);\ndirectionToLight=normalize(directionToLight);\ndirectionToLight.y=-directionToLight.y;\n#ifndef SHADOWFLOAT\nfloat shadowMapSample=unpack(textureCube(shadowSampler,directionToLight));\n#else\nfloat shadowMapSample=textureCube(shadowSampler,directionToLight).x;\n#endif\nfloat esm=1.0-clamp(exp(min(87.,depthScale*shadowPixelDepth))*shadowMapSample,0.,1.-darkness); \nreturn esm;\n}\nfloat computeShadowWithCloseESMCube(vec3 lightPosition,samplerCube shadowSampler,float darkness,float depthScale,vec2 depthValues)\n{\nvec3 directionToLight=vPositionW-lightPosition;\nfloat depth=length(directionToLight);\ndepth=(depth+depthValues.x)/(depthValues.y);\nfloat shadowPixelDepth=clamp(depth,0.,1.0);\ndirectionToLight=normalize(directionToLight);\ndirectionToLight.y=-directionToLight.y;\n#ifndef SHADOWFLOAT\nfloat shadowMapSample=unpack(textureCube(shadowSampler,directionToLight));\n#else\nfloat shadowMapSample=textureCube(shadowSampler,directionToLight).x;\n#endif\nfloat esm=clamp(exp(min(87.,-depthScale*(shadowPixelDepth-shadowMapSample))),darkness,1.);\nreturn esm;\n}\nfloat computeShadow(vec4 vPositionFromLight,float depthMetric,sampler2D shadowSampler,float darkness,float frustumEdgeFalloff)\n{\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec2 uv=0.5*clipSpace.xy+vec2(0.5);\nif (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0)\n{\nreturn 1.0;\n}\nfloat shadowPixelDepth=clamp(depthMetric,0.,1.0);\n#ifndef SHADOWFLOAT\nfloat shadow=unpack(texture2D(shadowSampler,uv));\n#else\nfloat shadow=texture2D(shadowSampler,uv).x;\n#endif\nif (shadowPixelDepth>shadow)\n{\nreturn computeFallOff(darkness,clipSpace.xy,frustumEdgeFalloff);\n}\nreturn 1.;\n}\nfloat computeShadowWithPCF(vec4 vPositionFromLight,float depthMetric,sampler2D shadowSampler,float mapSize,float darkness,float frustumEdgeFalloff)\n{\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec2 uv=0.5*clipSpace.xy+vec2(0.5);\nif (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0)\n{\nreturn 1.0;\n}\nfloat shadowPixelDepth=clamp(depthMetric,0.,1.0);\nfloat visibility=1.;\nvec2 poissonDisk[4];\npoissonDisk[0]=vec2(-0.94201624,-0.39906216);\npoissonDisk[1]=vec2(0.94558609,-0.76890725);\npoissonDisk[2]=vec2(-0.094184101,-0.92938870);\npoissonDisk[3]=vec2(0.34495938,0.29387760);\n\n#ifndef SHADOWFLOAT\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[0]*mapSize))<shadowPixelDepth) visibility-=0.25;\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[1]*mapSize))<shadowPixelDepth) visibility-=0.25;\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[2]*mapSize))<shadowPixelDepth) visibility-=0.25;\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[3]*mapSize))<shadowPixelDepth) visibility-=0.25;\n#else\nif (texture2D(shadowSampler,uv+poissonDisk[0]*mapSize).x<shadowPixelDepth) visibility-=0.25;\nif (texture2D(shadowSampler,uv+poissonDisk[1]*mapSize).x<shadowPixelDepth) visibility-=0.25;\nif (texture2D(shadowSampler,uv+poissonDisk[2]*mapSize).x<shadowPixelDepth) visibility-=0.25;\nif (texture2D(shadowSampler,uv+poissonDisk[3]*mapSize).x<shadowPixelDepth) visibility-=0.25;\n#endif\nreturn computeFallOff(min(1.0,visibility+darkness),clipSpace.xy,frustumEdgeFalloff);\n}\nfloat computeShadowWithESM(vec4 vPositionFromLight,float depthMetric,sampler2D shadowSampler,float darkness,float depthScale,float frustumEdgeFalloff)\n{\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec2 uv=0.5*clipSpace.xy+vec2(0.5);\nif (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0)\n{\nreturn 1.0;\n}\nfloat shadowPixelDepth=clamp(depthMetric,0.,1.0);\n#ifndef SHADOWFLOAT\nfloat shadowMapSample=unpack(texture2D(shadowSampler,uv));\n#else\nfloat shadowMapSample=texture2D(shadowSampler,uv).x;\n#endif\nfloat esm=1.0-clamp(exp(min(87.,depthScale*shadowPixelDepth))*shadowMapSample,0.,1.-darkness);\nreturn computeFallOff(esm,clipSpace.xy,frustumEdgeFalloff);\n}\nfloat computeShadowWithCloseESM(vec4 vPositionFromLight,float depthMetric,sampler2D shadowSampler,float darkness,float depthScale,float frustumEdgeFalloff)\n{\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec2 uv=0.5*clipSpace.xy+vec2(0.5);\nif (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0)\n{\nreturn 1.0;\n}\nfloat shadowPixelDepth=clamp(depthMetric,0.,1.0); \n#ifndef SHADOWFLOAT\nfloat shadowMapSample=unpack(texture2D(shadowSampler,uv));\n#else\nfloat shadowMapSample=texture2D(shadowSampler,uv).x;\n#endif\nfloat esm=clamp(exp(min(87.,-depthScale*(shadowPixelDepth-shadowMapSample))),darkness,1.);\nreturn computeFallOff(esm,clipSpace.xy,frustumEdgeFalloff);\n}\n#endif\n","fresnelFunction":"#ifdef FRESNEL\nfloat computeFresnelTerm(vec3 viewDirection,vec3 worldNormal,float bias,float power)\n{\nfloat fresnelTerm=pow(bias+abs(dot(viewDirection,worldNormal)),power);\nreturn clamp(fresnelTerm,0.,1.);\n}\n#endif","reflectionFunction":"#ifdef USE_LOCAL_REFLECTIONMAP_CUBIC\nvec3 parallaxCorrectNormal( vec3 vertexPos,vec3 origVec,vec3 cubeSize,vec3 cubePos ) {\n\nvec3 invOrigVec=vec3(1.0,1.0,1.0)/origVec;\nvec3 halfSize=cubeSize*0.5;\nvec3 intersecAtMaxPlane=(cubePos+halfSize-vertexPos)*invOrigVec;\nvec3 intersecAtMinPlane=(cubePos-halfSize-vertexPos)*invOrigVec;\n\nvec3 largestIntersec=max(intersecAtMaxPlane,intersecAtMinPlane);\n\nfloat distance=min(min(largestIntersec.x,largestIntersec.y),largestIntersec.z);\n\nvec3 intersectPositionWS=vertexPos+origVec*distance;\n\nreturn intersectPositionWS-cubePos;\n}\n#endif\nvec3 computeReflectionCoords(vec4 worldPos,vec3 worldNormal)\n{\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvec3 direction=vDirectionW;\nfloat t=clamp(direction.y*-0.5+0.5,0.,1.0);\nfloat s=atan(direction.z,direction.x)*RECIPROCAL_PI2+0.5;\n#ifdef REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED\nreturn vec3(1.0-s,t,0);\n#else\nreturn vec3(s,t,0);\n#endif\n#endif\n#ifdef REFLECTIONMAP_EQUIRECTANGULAR\nvec3 cameraToVertex=normalize(worldPos.xyz-vEyePosition.xyz);\nvec3 r=reflect(cameraToVertex,worldNormal);\nfloat t=clamp(r.y*-0.5+0.5,0.,1.0);\nfloat s=atan(r.z,r.x)*RECIPROCAL_PI2+0.5;\nreturn vec3(s,t,0);\n#endif\n#ifdef REFLECTIONMAP_SPHERICAL\nvec3 viewDir=normalize(vec3(view*worldPos));\nvec3 viewNormal=normalize(vec3(view*vec4(worldNormal,0.0)));\nvec3 r=reflect(viewDir,viewNormal);\nr.z=r.z-1.0;\nfloat m=2.0*length(r);\nreturn vec3(r.x/m+0.5,1.0-r.y/m-0.5,0);\n#endif\n#ifdef REFLECTIONMAP_PLANAR\nvec3 viewDir=worldPos.xyz-vEyePosition.xyz;\nvec3 coords=normalize(reflect(viewDir,worldNormal));\nreturn vec3(reflectionMatrix*vec4(coords,1));\n#endif\n#ifdef REFLECTIONMAP_CUBIC\nvec3 viewDir=worldPos.xyz-vEyePosition.xyz;\nvec3 coords=reflect(viewDir,worldNormal);\n#ifdef INVERTCUBICMAP\ncoords.y=1.0-coords.y;\n#endif\n#ifdef USE_LOCAL_REFLECTIONMAP_CUBIC\ncoords=parallaxCorrectNormal(worldPos.xyz,coords,vReflectionSize,vReflectionPosition );\n#endif\nreturn vec3(reflectionMatrix*vec4(coords,0));\n#endif\n#ifdef REFLECTIONMAP_PROJECTION\nreturn vec3(reflectionMatrix*(view*worldPos));\n#endif\n#ifdef REFLECTIONMAP_SKYBOX\nreturn vPositionUVW;\n#endif\n#ifdef REFLECTIONMAP_EXPLICIT\nreturn vec3(0,0,0);\n#endif\n}","imageProcessingDeclaration":"#ifdef EXPOSURE\nuniform float exposureLinear;\n#endif\n#ifdef CONTRAST\nuniform float contrast;\n#endif\n#ifdef VIGNETTE\nuniform vec2 vInverseScreenSize;\nuniform vec4 vignetteSettings1;\nuniform vec4 vignetteSettings2;\n#endif\n#ifdef COLORCURVES\nuniform vec4 vCameraColorCurveNegative;\nuniform vec4 vCameraColorCurveNeutral;\nuniform vec4 vCameraColorCurvePositive;\n#endif\n#ifdef COLORGRADING\n#ifdef COLORGRADING3D\nuniform highp sampler3D txColorTransform;\n#else\nuniform sampler2D txColorTransform;\n#endif\nuniform vec4 colorTransformSettings;\n#endif","imageProcessingFunctions":"#if defined(COLORGRADING) && !defined(COLORGRADING3D)\n\nvec3 sampleTexture3D(sampler2D colorTransform,vec3 color,vec2 sampler3dSetting)\n{\nfloat sliceSize=2.0*sampler3dSetting.x; \n#ifdef SAMPLER3DGREENDEPTH\nfloat sliceContinuous=(color.g-sampler3dSetting.x)*sampler3dSetting.y;\n#else\nfloat sliceContinuous=(color.b-sampler3dSetting.x)*sampler3dSetting.y;\n#endif\nfloat sliceInteger=floor(sliceContinuous);\n\n\nfloat sliceFraction=sliceContinuous-sliceInteger;\n#ifdef SAMPLER3DGREENDEPTH\nvec2 sliceUV=color.rb;\n#else\nvec2 sliceUV=color.rg;\n#endif\nsliceUV.x*=sliceSize;\nsliceUV.x+=sliceInteger*sliceSize;\nsliceUV=clamp(sliceUV,0.,1.);\nvec4 slice0Color=texture2D(colorTransform,sliceUV);\nsliceUV.x+=sliceSize;\nsliceUV=clamp(sliceUV,0.,1.);\nvec4 slice1Color=texture2D(colorTransform,sliceUV);\nvec3 result=mix(slice0Color.rgb,slice1Color.rgb,sliceFraction);\n#ifdef SAMPLER3DBGRMAP\ncolor.rgb=result.rgb;\n#else\ncolor.rgb=result.bgr;\n#endif\nreturn color;\n}\n#endif\nvec4 applyImageProcessing(vec4 result) {\n#ifdef EXPOSURE\nresult.rgb*=exposureLinear;\n#endif\n#ifdef VIGNETTE\n\nvec2 viewportXY=gl_FragCoord.xy*vInverseScreenSize;\nviewportXY=viewportXY*2.0-1.0;\nvec3 vignetteXY1=vec3(viewportXY*vignetteSettings1.xy+vignetteSettings1.zw,1.0);\nfloat vignetteTerm=dot(vignetteXY1,vignetteXY1);\nfloat vignette=pow(vignetteTerm,vignetteSettings2.w);\n\nvec3 vignetteColor=vignetteSettings2.rgb;\n#ifdef VIGNETTEBLENDMODEMULTIPLY\nvec3 vignetteColorMultiplier=mix(vignetteColor,vec3(1,1,1),vignette);\nresult.rgb*=vignetteColorMultiplier;\n#endif\n#ifdef VIGNETTEBLENDMODEOPAQUE\nresult.rgb=mix(vignetteColor,result.rgb,vignette);\n#endif\n#endif\n#ifdef TONEMAPPING\nconst float tonemappingCalibration=1.590579;\nresult.rgb=1.0-exp2(-tonemappingCalibration*result.rgb);\n#endif\n\nresult.rgb=toGammaSpace(result.rgb);\nresult.rgb=clamp(result.rgb,0.0,1.0);\n#ifdef CONTRAST\n\nvec3 resultHighContrast=applyEaseInOut(result.rgb);\nif (contrast<1.0) {\n\nresult.rgb=mix(vec3(0.5,0.5,0.5),result.rgb,contrast);\n} else {\n\nresult.rgb=mix(result.rgb,resultHighContrast,contrast-1.0);\n}\n#endif\n\n#ifdef COLORGRADING\nvec3 colorTransformInput=result.rgb*colorTransformSettings.xxx+colorTransformSettings.yyy;\n#ifdef COLORGRADING3D\nvec3 colorTransformOutput=texture(txColorTransform,colorTransformInput).rgb;\n#else\nvec3 colorTransformOutput=sampleTexture3D(txColorTransform,colorTransformInput,colorTransformSettings.yz).rgb;\n#endif\nresult.rgb=mix(result.rgb,colorTransformOutput,colorTransformSettings.www);\n#endif\n#ifdef COLORCURVES\n\nfloat luma=getLuminance(result.rgb);\nvec2 curveMix=clamp(vec2(luma*3.0-1.5,luma*-3.0+1.5),vec2(0.0),vec2(1.0));\nvec4 colorCurve=vCameraColorCurveNeutral+curveMix.x*vCameraColorCurvePositive-curveMix.y*vCameraColorCurveNegative;\nresult.rgb*=colorCurve.rgb;\nresult.rgb=mix(vec3(luma),result.rgb,colorCurve.a);\n#endif\nreturn result;\n}","bumpFragmentFunctions":"#ifdef BUMP\n#if BUMPDIRECTUV == 1\n#define vBumpUV vMainUV1\n#elif BUMPDIRECTUV == 2\n#define vBumpUV vMainUV2\n#else\nvarying vec2 vBumpUV;\n#endif\nuniform sampler2D bumpSampler;\n#if defined(TANGENT) && defined(NORMAL) \nvarying mat3 vTBN;\n#endif\n#ifdef OBJECTSPACE_NORMALMAP\nuniform mat4 normalMatrix;\n#endif\n\nmat3 cotangent_frame(vec3 normal,vec3 p,vec2 uv)\n{\n\nuv=gl_FrontFacing ? uv : -uv;\n\nvec3 dp1=dFdx(p);\nvec3 dp2=dFdy(p);\nvec2 duv1=dFdx(uv);\nvec2 duv2=dFdy(uv);\n\nvec3 dp2perp=cross(dp2,normal);\nvec3 dp1perp=cross(normal,dp1);\nvec3 tangent=dp2perp*duv1.x+dp1perp*duv2.x;\nvec3 bitangent=dp2perp*duv1.y+dp1perp*duv2.y;\n\ntangent*=vTangentSpaceParams.x;\nbitangent*=vTangentSpaceParams.y;\n\nfloat invmax=inversesqrt(max(dot(tangent,tangent),dot(bitangent,bitangent)));\nreturn mat3(tangent*invmax,bitangent*invmax,normal);\n}\nvec3 perturbNormal(mat3 cotangentFrame,vec2 uv)\n{\nvec3 map=texture2D(bumpSampler,uv).xyz;\nmap=map*2.0-1.0;\n#ifdef NORMALXYSCALE\nmap=normalize(map*vec3(vBumpInfos.y,vBumpInfos.y,1.0));\n#endif\nreturn normalize(cotangentFrame*map);\n}\n#ifdef PARALLAX\nconst float minSamples=4.;\nconst float maxSamples=15.;\nconst int iMaxSamples=15;\n\nvec2 parallaxOcclusion(vec3 vViewDirCoT,vec3 vNormalCoT,vec2 texCoord,float parallaxScale) {\nfloat parallaxLimit=length(vViewDirCoT.xy)/vViewDirCoT.z;\nparallaxLimit*=parallaxScale;\nvec2 vOffsetDir=normalize(vViewDirCoT.xy);\nvec2 vMaxOffset=vOffsetDir*parallaxLimit;\nfloat numSamples=maxSamples+(dot(vViewDirCoT,vNormalCoT)*(minSamples-maxSamples));\nfloat stepSize=1.0/numSamples;\n\nfloat currRayHeight=1.0;\nvec2 vCurrOffset=vec2(0,0);\nvec2 vLastOffset=vec2(0,0);\nfloat lastSampledHeight=1.0;\nfloat currSampledHeight=1.0;\nfor (int i=0; i<iMaxSamples; i++)\n{\ncurrSampledHeight=texture2D(bumpSampler,vBumpUV+vCurrOffset).w;\n\nif (currSampledHeight>currRayHeight)\n{\nfloat delta1=currSampledHeight-currRayHeight;\nfloat delta2=(currRayHeight+stepSize)-lastSampledHeight;\nfloat ratio=delta1/(delta1+delta2);\nvCurrOffset=(ratio)* vLastOffset+(1.0-ratio)*vCurrOffset;\n\nbreak;\n}\nelse\n{\ncurrRayHeight-=stepSize;\nvLastOffset=vCurrOffset;\nvCurrOffset+=stepSize*vMaxOffset;\nlastSampledHeight=currSampledHeight;\n}\n}\nreturn vCurrOffset;\n}\nvec2 parallaxOffset(vec3 viewDir,float heightScale)\n{\n\nfloat height=texture2D(bumpSampler,vBumpUV).w;\nvec2 texCoordOffset=heightScale*viewDir.xy*height;\nreturn -texCoordOffset;\n}\n#endif\n#endif","clipPlaneFragmentDeclaration":"#ifdef CLIPPLANE\nvarying float fClipDistance;\n#endif","fogFragmentDeclaration":"#ifdef FOG\n#define FOGMODE_NONE 0.\n#define FOGMODE_EXP 1.\n#define FOGMODE_EXP2 2.\n#define FOGMODE_LINEAR 3.\n#define E 2.71828\nuniform vec4 vFogInfos;\nuniform vec3 vFogColor;\nvarying vec3 vFogDistance;\nfloat CalcFogFactor()\n{\nfloat fogCoeff=1.0;\nfloat fogStart=vFogInfos.y;\nfloat fogEnd=vFogInfos.z;\nfloat fogDensity=vFogInfos.w;\nfloat fogDistance=length(vFogDistance);\nif (FOGMODE_LINEAR == vFogInfos.x)\n{\nfogCoeff=(fogEnd-fogDistance)/(fogEnd-fogStart);\n}\nelse if (FOGMODE_EXP == vFogInfos.x)\n{\nfogCoeff=1.0/pow(E,fogDistance*fogDensity);\n}\nelse if (FOGMODE_EXP2 == vFogInfos.x)\n{\nfogCoeff=1.0/pow(E,fogDistance*fogDistance*fogDensity*fogDensity);\n}\nreturn clamp(fogCoeff,0.0,1.0);\n}\n#endif","clipPlaneFragment":"#ifdef CLIPPLANE\nif (fClipDistance>0.0)\n{\ndiscard;\n}\n#endif","bumpFragment":"vec2 uvOffset=vec2(0.0,0.0);\n#if defined(BUMP) || defined(PARALLAX)\n#ifdef NORMALXYSCALE\nfloat normalScale=1.0;\n#else \nfloat normalScale=vBumpInfos.y;\n#endif\n#if defined(TANGENT) && defined(NORMAL)\nmat3 TBN=vTBN;\n#else\nmat3 TBN=cotangent_frame(normalW*normalScale,vPositionW,vBumpUV);\n#endif\n#endif\n#ifdef PARALLAX\nmat3 invTBN=transposeMat3(TBN);\n#ifdef PARALLAXOCCLUSION\nuvOffset=parallaxOcclusion(invTBN*-viewDirectionW,invTBN*normalW,vBumpUV,vBumpInfos.z);\n#else\nuvOffset=parallaxOffset(invTBN*viewDirectionW,vBumpInfos.z);\n#endif\n#endif\n#ifdef BUMP\n#ifdef OBJECTSPACE_NORMALMAP\nnormalW=normalize(texture2D(bumpSampler,vBumpUV).xyz*2.0-1.0);\nnormalW=normalize(mat3(normalMatrix)*normalW); \n#else\nnormalW=perturbNormal(TBN,vBumpUV+uvOffset);\n#endif\n#endif","lightFragment":"#ifdef LIGHT{X}\n#if defined(SHADOWONLY) || (defined(LIGHTMAP) && defined(LIGHTMAPEXCLUDED{X}) && defined(LIGHTMAPNOSPECULAR{X}))\n\n#else\n#ifdef PBR\n#ifdef SPOTLIGHT{X}\ninfo=computeSpotLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDirection,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightDiffuse.a,roughness,NdotV,specularEnvironmentR0,specularEnvironmentR90,NdotL);\n#endif\n#ifdef HEMILIGHT{X}\ninfo=computeHemisphericLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightGround,roughness,NdotV,specularEnvironmentR0,specularEnvironmentR90,NdotL);\n#endif\n#if defined(POINTLIGHT{X}) || defined(DIRLIGHT{X})\ninfo=computeLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightDiffuse.a,roughness,NdotV,specularEnvironmentR0,specularEnvironmentR90,NdotL);\n#endif\n#else\n#ifdef SPOTLIGHT{X}\ninfo=computeSpotLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDirection,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightDiffuse.a,glossiness);\n#endif\n#ifdef HEMILIGHT{X}\ninfo=computeHemisphericLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightGround,glossiness);\n#endif\n#if defined(POINTLIGHT{X}) || defined(DIRLIGHT{X})\ninfo=computeLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightDiffuse.a,glossiness);\n#endif\n#endif\n#ifdef PROJECTEDLIGHTTEXTURE{X}\ninfo.diffuse*=computeProjectionTextureDiffuseLighting(projectionLightSampler{X},textureProjectionMatrix{X});\n#endif\n#endif\n#ifdef SHADOW{X}\n#ifdef SHADOWCLOSEESM{X}\n#if defined(SHADOWCUBE{X})\nshadow=computeShadowWithCloseESMCube(light{X}.vLightData.xyz,shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.z,light{X}.depthValues);\n#else\nshadow=computeShadowWithCloseESM(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.z,light{X}.shadowsInfo.w);\n#endif\n#else\n#ifdef SHADOWESM{X}\n#if defined(SHADOWCUBE{X})\nshadow=computeShadowWithESMCube(light{X}.vLightData.xyz,shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.z,light{X}.depthValues);\n#else\nshadow=computeShadowWithESM(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.z,light{X}.shadowsInfo.w);\n#endif\n#else \n#ifdef SHADOWPCF{X}\n#if defined(SHADOWCUBE{X})\nshadow=computeShadowWithPCFCube(light{X}.vLightData.xyz,shadowSampler{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.x,light{X}.depthValues);\n#else\nshadow=computeShadowWithPCF(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#endif\n#else\n#if defined(SHADOWCUBE{X})\nshadow=computeShadowCube(light{X}.vLightData.xyz,shadowSampler{X},light{X}.shadowsInfo.x,light{X}.depthValues);\n#else\nshadow=computeShadow(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#endif\n#endif\n#endif\n#endif\n#ifdef SHADOWONLY\n#ifndef SHADOWINUSE\n#define SHADOWINUSE\n#endif\nglobalShadow+=shadow;\nshadowLightCount+=1.0;\n#endif\n#else\nshadow=1.;\n#endif\n#ifndef SHADOWONLY\n#ifdef CUSTOMUSERLIGHTING\ndiffuseBase+=computeCustomDiffuseLighting(info,diffuseBase,shadow);\n#ifdef SPECULARTERM\nspecularBase+=computeCustomSpecularLighting(info,specularBase,shadow);\n#endif\n#elif defined(LIGHTMAP) && defined(LIGHTMAPEXCLUDED{X})\ndiffuseBase+=lightmapColor*shadow;\n#ifdef SPECULARTERM\n#ifndef LIGHTMAPNOSPECULAR{X}\nspecularBase+=info.specular*shadow*lightmapColor;\n#endif\n#endif\n#else\ndiffuseBase+=info.diffuse*shadow;\n#ifdef SPECULARTERM\nspecularBase+=info.specular*shadow;\n#endif\n#endif\n#endif\n#endif","logDepthFragment":"#ifdef LOGARITHMICDEPTH\ngl_FragDepthEXT=log2(vFragmentDepth)*logarithmicDepthConstant*0.5;\n#endif","fogFragment":"#ifdef FOG\nfloat fog=CalcFogFactor();\ncolor.rgb=fog*color.rgb+(1.0-fog)*vFogColor;\n#endif","pbrVertexDeclaration":"uniform mat4 view;\nuniform mat4 viewProjection;\n#ifdef ALBEDO\nuniform mat4 albedoMatrix;\nuniform vec2 vAlbedoInfos;\n#endif\n#ifdef AMBIENT\nuniform mat4 ambientMatrix;\nuniform vec3 vAmbientInfos;\n#endif\n#ifdef OPACITY\nuniform mat4 opacityMatrix;\nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nuniform vec2 vEmissiveInfos;\nuniform mat4 emissiveMatrix;\n#endif\n#ifdef LIGHTMAP\nuniform vec2 vLightmapInfos;\nuniform mat4 lightmapMatrix;\n#endif\n#ifdef REFLECTIVITY \nuniform vec3 vReflectivityInfos;\nuniform mat4 reflectivityMatrix;\n#endif\n#ifdef MICROSURFACEMAP\nuniform vec2 vMicroSurfaceSamplerInfos;\nuniform mat4 microSurfaceSamplerMatrix;\n#endif\n#ifdef BUMP\nuniform vec3 vBumpInfos;\nuniform mat4 bumpMatrix;\n#endif\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif\n\n#ifdef REFRACTION\nuniform vec4 vRefractionInfos;\nuniform mat4 refractionMatrix;\nuniform vec3 vRefractionMicrosurfaceInfos;\n#endif\n\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;\nuniform mat4 reflectionMatrix;\nuniform vec3 vReflectionMicrosurfaceInfos;\n#endif\n","pbrFragmentDeclaration":"uniform vec3 vReflectionColor;\nuniform vec4 vAlbedoColor;\n\nuniform vec4 vLightingIntensity;\nuniform vec4 vReflectivityColor;\nuniform vec3 vEmissiveColor;\n\n#ifdef ALBEDO\nuniform vec2 vAlbedoInfos;\n#endif\n#ifdef AMBIENT\nuniform vec3 vAmbientInfos;\n#endif\n#ifdef BUMP\nuniform vec3 vBumpInfos;\nuniform vec2 vTangentSpaceParams;\n#endif\n#ifdef OPACITY \nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nuniform vec2 vEmissiveInfos;\n#endif\n#ifdef LIGHTMAP\nuniform vec2 vLightmapInfos;\n#endif\n#ifdef REFLECTIVITY\nuniform vec3 vReflectivityInfos;\n#endif\n#ifdef MICROSURFACEMAP\nuniform vec2 vMicroSurfaceSamplerInfos;\n#endif\n\n#if defined(REFLECTIONMAP_SPHERICAL) || defined(REFLECTIONMAP_PROJECTION) || defined(REFRACTION)\nuniform mat4 view;\n#endif\n\n#ifdef REFRACTION\nuniform vec4 vRefractionInfos;\nuniform mat4 refractionMatrix;\nuniform vec3 vRefractionMicrosurfaceInfos;\n#endif\n\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;\nuniform mat4 reflectionMatrix;\nuniform vec3 vReflectionMicrosurfaceInfos;\n#if defined(USE_LOCAL_REFLECTIONMAP_CUBIC) && defined(REFLECTIONMAP_CUBIC)\nuniform vec3 vReflectionPosition;\nuniform vec3 vReflectionSize; \n#endif\n#endif","pbrUboDeclaration":"layout(std140,column_major) uniform;\nuniform Material\n{\nuniform vec2 vAlbedoInfos;\nuniform vec3 vAmbientInfos;\nuniform vec2 vOpacityInfos;\nuniform vec2 vEmissiveInfos;\nuniform vec2 vLightmapInfos;\nuniform vec3 vReflectivityInfos;\nuniform vec2 vMicroSurfaceSamplerInfos;\nuniform vec4 vRefractionInfos;\nuniform vec2 vReflectionInfos;\nuniform vec3 vReflectionPosition;\nuniform vec3 vReflectionSize; \nuniform vec3 vBumpInfos;\nuniform mat4 albedoMatrix;\nuniform mat4 ambientMatrix;\nuniform mat4 opacityMatrix;\nuniform mat4 emissiveMatrix;\nuniform mat4 lightmapMatrix;\nuniform mat4 reflectivityMatrix;\nuniform mat4 microSurfaceSamplerMatrix;\nuniform mat4 bumpMatrix;\nuniform vec2 vTangentSpaceParams;\nuniform mat4 refractionMatrix;\nuniform mat4 reflectionMatrix;\nuniform vec3 vReflectionColor;\nuniform vec4 vAlbedoColor;\nuniform vec4 vLightingIntensity;\nuniform vec3 vRefractionMicrosurfaceInfos;\nuniform vec3 vReflectionMicrosurfaceInfos;\nuniform vec4 vReflectivityColor;\nuniform vec3 vEmissiveColor;\nuniform float pointSize;\n};\nuniform Scene {\nmat4 viewProjection;\nmat4 view;\n};","pbrFunctions":"\n#define RECIPROCAL_PI2 0.15915494\n#define FRESNEL_MAXIMUM_ON_ROUGH 0.25\n\nconst float kRougnhessToAlphaScale=0.1;\nconst float kRougnhessToAlphaOffset=0.29248125;\nfloat convertRoughnessToAverageSlope(float roughness)\n{\n\nconst float kMinimumVariance=0.0005;\nfloat alphaG=square(roughness)+kMinimumVariance;\nreturn alphaG;\n}\n\nfloat smithVisibilityG1_TrowbridgeReitzGGX(float dot,float alphaG)\n{\nfloat tanSquared=(1.0-dot*dot)/(dot*dot);\nreturn 2.0/(1.0+sqrt(1.0+alphaG*alphaG*tanSquared));\n}\nfloat smithVisibilityG_TrowbridgeReitzGGX_Walter(float NdotL,float NdotV,float alphaG)\n{\nreturn smithVisibilityG1_TrowbridgeReitzGGX(NdotL,alphaG)*smithVisibilityG1_TrowbridgeReitzGGX(NdotV,alphaG);\n}\n\n\nfloat normalDistributionFunction_TrowbridgeReitzGGX(float NdotH,float alphaG)\n{\n\n\n\nfloat a2=square(alphaG);\nfloat d=NdotH*NdotH*(a2-1.0)+1.0;\nreturn a2/(PI*d*d);\n}\nvec3 fresnelSchlickGGX(float VdotH,vec3 reflectance0,vec3 reflectance90)\n{\nreturn reflectance0+(reflectance90-reflectance0)*pow(clamp(1.0-VdotH,0.,1.),5.0);\n}\nvec3 fresnelSchlickEnvironmentGGX(float VdotN,vec3 reflectance0,vec3 reflectance90,float smoothness)\n{\n\nfloat weight=mix(FRESNEL_MAXIMUM_ON_ROUGH,1.0,smoothness);\nreturn reflectance0+weight*(reflectance90-reflectance0)*pow(clamp(1.0-VdotN,0.,1.),5.0);\n}\n\nvec3 computeSpecularTerm(float NdotH,float NdotL,float NdotV,float VdotH,float roughness,vec3 reflectance0,vec3 reflectance90)\n{\nfloat alphaG=convertRoughnessToAverageSlope(roughness);\nfloat distribution=normalDistributionFunction_TrowbridgeReitzGGX(NdotH,alphaG);\nfloat visibility=smithVisibilityG_TrowbridgeReitzGGX_Walter(NdotL,NdotV,alphaG);\nvisibility/=(4.0*NdotL*NdotV); \nfloat specTerm=max(0.,visibility*distribution)*NdotL;\nvec3 fresnel=fresnelSchlickGGX(VdotH,reflectance0,reflectance90);\nreturn fresnel*specTerm;\n}\nfloat computeDiffuseTerm(float NdotL,float NdotV,float VdotH,float roughness)\n{\n\n\nfloat diffuseFresnelNV=pow(clamp(1.0-NdotL,0.000001,1.),5.0);\nfloat diffuseFresnelNL=pow(clamp(1.0-NdotV,0.000001,1.),5.0);\nfloat diffuseFresnel90=0.5+2.0*VdotH*VdotH*roughness;\nfloat fresnel =\n(1.0+(diffuseFresnel90-1.0)*diffuseFresnelNL) *\n(1.0+(diffuseFresnel90-1.0)*diffuseFresnelNV);\nreturn fresnel*NdotL/PI;\n}\nfloat adjustRoughnessFromLightProperties(float roughness,float lightRadius,float lightDistance)\n{\n#ifdef USEPHYSICALLIGHTFALLOFF\n\nfloat lightRoughness=lightRadius/lightDistance;\n\nfloat totalRoughness=clamp(lightRoughness+roughness,0.,1.);\nreturn totalRoughness;\n#else\nreturn roughness;\n#endif\n}\nfloat computeDefaultMicroSurface(float microSurface,vec3 reflectivityColor)\n{\nconst float kReflectivityNoAlphaWorkflow_SmoothnessMax=0.95;\nfloat reflectivityLuminance=getLuminance(reflectivityColor);\nfloat reflectivityLuma=sqrt(reflectivityLuminance);\nmicroSurface=reflectivityLuma*kReflectivityNoAlphaWorkflow_SmoothnessMax;\nreturn microSurface;\n}\n\n\nfloat fresnelGrazingReflectance(float reflectance0) {\nfloat reflectance90=clamp(reflectance0*25.0,0.0,1.0);\nreturn reflectance90;\n}\n\n\n#define UNPACK_LOD(x) (1.0-x)*255.0\nfloat getLodFromAlphaG(float cubeMapDimensionPixels,float alphaG,float NdotV) {\nfloat microsurfaceAverageSlope=alphaG;\n\n\n\n\n\n\nmicrosurfaceAverageSlope*=sqrt(abs(NdotV));\nfloat microsurfaceAverageSlopeTexels=microsurfaceAverageSlope*cubeMapDimensionPixels;\nfloat lod=log2(microsurfaceAverageSlopeTexels);\nreturn lod;\n}\nfloat environmentRadianceOcclusion(float ambientOcclusion,float NdotVUnclamped) {\n\n\nfloat temp=NdotVUnclamped+ambientOcclusion;\nreturn clamp(square(temp)-1.0+ambientOcclusion,0.0,1.0);\n}\nfloat environmentHorizonOcclusion(vec3 reflection,vec3 normal) {\n\n#ifdef REFLECTIONMAP_OPPOSITEZ\nreflection.z*=-1.0;\n#endif\nfloat temp=clamp( 1.0+1.1*dot(reflection,normal),0.0,1.0);\nreturn square(temp);\n}","harmonicsFunctions":"#ifdef USESPHERICALFROMREFLECTIONMAP\nuniform vec3 vSphericalX;\nuniform vec3 vSphericalY;\nuniform vec3 vSphericalZ;\nuniform vec3 vSphericalXX_ZZ;\nuniform vec3 vSphericalYY_ZZ;\nuniform vec3 vSphericalZZ;\nuniform vec3 vSphericalXY;\nuniform vec3 vSphericalYZ;\nuniform vec3 vSphericalZX;\nvec3 quaternionVectorRotation_ScaledSqrtTwo(vec4 Q,vec3 V){\nvec3 T=cross(Q.xyz,V);\nT+=Q.www*V;\nreturn cross(Q.xyz,T)+V;\n}\nvec3 environmentIrradianceJones(vec3 normal)\n{\n\n\n\n\n\n\n\n\n\nfloat Nx=normal.x;\nfloat Ny=normal.y;\nfloat Nz=normal.z;\nvec3 C1=vSphericalZZ.rgb;\nvec3 Cx=vSphericalX.rgb;\nvec3 Cy=vSphericalY.rgb;\nvec3 Cz=vSphericalZ.rgb;\nvec3 Cxx_zz=vSphericalXX_ZZ.rgb;\nvec3 Cyy_zz=vSphericalYY_ZZ.rgb;\nvec3 Cxy=vSphericalXY.rgb;\nvec3 Cyz=vSphericalYZ.rgb;\nvec3 Czx=vSphericalZX.rgb;\nvec3 a1=Cyy_zz*Ny+Cy;\nvec3 a2=Cyz*Nz+a1;\nvec3 b1=Czx*Nz+Cx;\nvec3 b2=Cxy*Ny+b1;\nvec3 b3=Cxx_zz*Nx+b2;\nvec3 t1=Cz*Nz+C1;\nvec3 t2=a2*Ny+t1;\nvec3 t3=b3*Nx+t2;\nreturn t3;\n}\n#endif","pbrLightFunctions":"\nstruct lightingInfo\n{\nvec3 diffuse;\n#ifdef SPECULARTERM\nvec3 specular;\n#endif\n};\nfloat computeDistanceLightFalloff(vec3 lightOffset,float lightDistanceSquared,float range)\n{ \n#ifdef USEPHYSICALLIGHTFALLOFF\nfloat lightDistanceFalloff=1.0/((lightDistanceSquared+0.001));\n#else\nfloat lightDistanceFalloff=max(0.,1.0-length(lightOffset)/range);\n#endif\nreturn lightDistanceFalloff;\n}\nfloat computeDirectionalLightFalloff(vec3 lightDirection,vec3 directionToLightCenterW,float cosHalfAngle,float exponent)\n{\nfloat falloff=0.0;\n#ifdef USEPHYSICALLIGHTFALLOFF\nconst float kMinusLog2ConeAngleIntensityRatio=6.64385618977; \n\n\n\n\n\nfloat concentrationKappa=kMinusLog2ConeAngleIntensityRatio/(1.0-cosHalfAngle);\n\n\nvec4 lightDirectionSpreadSG=vec4(-lightDirection*concentrationKappa,-concentrationKappa);\nfalloff=exp2(dot(vec4(directionToLightCenterW,1.0),lightDirectionSpreadSG));\n#else\nfloat cosAngle=max(0.000000000000001,dot(-lightDirection,directionToLightCenterW));\nif (cosAngle>=cosHalfAngle)\n{\nfalloff=max(0.,pow(cosAngle,exponent));\n}\n#endif\nreturn falloff;\n}\nlightingInfo computeLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec3 diffuseColor,vec3 specularColor,float rangeRadius,float roughness,float NdotV,vec3 reflectance0,vec3 reflectance90,out float NdotL) {\nlightingInfo result;\nvec3 lightDirection;\nfloat attenuation=1.0;\nfloat lightDistance;\n\nif (lightData.w == 0.)\n{\nvec3 lightOffset=lightData.xyz-vPositionW;\nfloat lightDistanceSquared=dot(lightOffset,lightOffset);\nattenuation=computeDistanceLightFalloff(lightOffset,lightDistanceSquared,rangeRadius);\nlightDistance=sqrt(lightDistanceSquared);\nlightDirection=normalize(lightOffset);\n}\n\nelse\n{\nlightDistance=length(-lightData.xyz);\nlightDirection=normalize(-lightData.xyz);\n}\n\nroughness=adjustRoughnessFromLightProperties(roughness,rangeRadius,lightDistance);\n\nvec3 H=normalize(viewDirectionW+lightDirection);\nNdotL=clamp(dot(vNormal,lightDirection),0.00000000001,1.0);\nfloat VdotH=clamp(dot(viewDirectionW,H),0.0,1.0);\nfloat diffuseTerm=computeDiffuseTerm(NdotL,NdotV,VdotH,roughness);\nresult.diffuse=diffuseTerm*diffuseColor*attenuation;\n#ifdef SPECULARTERM\n\nfloat NdotH=clamp(dot(vNormal,H),0.000000000001,1.0);\nvec3 specTerm=computeSpecularTerm(NdotH,NdotL,NdotV,VdotH,roughness,reflectance0,reflectance90);\nresult.specular=specTerm*diffuseColor*attenuation;\n#endif\nreturn result;\n}\nlightingInfo computeSpotLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec4 lightDirection,vec3 diffuseColor,vec3 specularColor,float rangeRadius,float roughness,float NdotV,vec3 reflectance0,vec3 reflectance90,out float NdotL) {\nlightingInfo result;\nvec3 lightOffset=lightData.xyz-vPositionW;\nvec3 directionToLightCenterW=normalize(lightOffset);\n\nfloat lightDistanceSquared=dot(lightOffset,lightOffset);\nfloat attenuation=computeDistanceLightFalloff(lightOffset,lightDistanceSquared,rangeRadius);\n\nfloat directionalAttenuation=computeDirectionalLightFalloff(lightDirection.xyz,directionToLightCenterW,lightDirection.w,lightData.w);\nattenuation*=directionalAttenuation;\n\nfloat lightDistance=sqrt(lightDistanceSquared);\nroughness=adjustRoughnessFromLightProperties(roughness,rangeRadius,lightDistance);\n\nvec3 H=normalize(viewDirectionW+directionToLightCenterW);\nNdotL=clamp(dot(vNormal,directionToLightCenterW),0.000000000001,1.0);\nfloat VdotH=clamp(dot(viewDirectionW,H),0.0,1.0);\nfloat diffuseTerm=computeDiffuseTerm(NdotL,NdotV,VdotH,roughness);\nresult.diffuse=diffuseTerm*diffuseColor*attenuation;\n#ifdef SPECULARTERM\n\nfloat NdotH=clamp(dot(vNormal,H),0.000000000001,1.0);\nvec3 specTerm=computeSpecularTerm(NdotH,NdotL,NdotV,VdotH,roughness,reflectance0,reflectance90);\nresult.specular=specTerm*diffuseColor*attenuation;\n#endif\nreturn result;\n}\nlightingInfo computeHemisphericLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec3 diffuseColor,vec3 specularColor,vec3 groundColor,float roughness,float NdotV,vec3 reflectance0,vec3 reflectance90,out float NdotL) {\nlightingInfo result;\n\n\n\nNdotL=dot(vNormal,lightData.xyz)*0.5+0.5;\nresult.diffuse=mix(groundColor,diffuseColor,NdotL);\n#ifdef SPECULARTERM\n\nvec3 lightVectorW=normalize(lightData.xyz);\nvec3 H=normalize(viewDirectionW+lightVectorW);\nfloat NdotH=clamp(dot(vNormal,H),0.000000000001,1.0);\nNdotL=clamp(NdotL,0.000000000001,1.0);\nfloat VdotH=clamp(dot(viewDirectionW,H),0.0,1.0);\nvec3 specTerm=computeSpecularTerm(NdotH,NdotL,NdotV,VdotH,roughness,reflectance0,reflectance90);\nresult.specular=specTerm*diffuseColor;\n#endif\nreturn result;\n}","mrtFragmentDeclaration":"#if __VERSION__>=200\nlayout(location=0) out vec4 glFragData[{X}];\n#endif\n","bones300Declaration":"#if NUM_BONE_INFLUENCERS>0\nuniform mat4 mBones[BonesPerMesh];\nin vec4 matricesIndices;\nin vec4 matricesWeights;\n#if NUM_BONE_INFLUENCERS>4\nin vec4 matricesIndicesExtra;\nin vec4 matricesWeightsExtra;\n#endif\n#endif","instances300Declaration":"#ifdef INSTANCES\nin vec4 world0;\nin vec4 world1;\nin vec4 world2;\nin vec4 world3;\n#else\nuniform mat4 world;\n#endif","kernelBlurFragment":"#ifdef DOF\nsampleDepth=sampleDistance(sampleCoord{X});\nfactor=clamp(1.0-((centerSampleDepth-sampleDepth)/centerSampleDepth),0.0,1.0);\ncomputedWeight=KERNEL_WEIGHT{X}*factor;\nsumOfWeights+=computedWeight;\n#else\ncomputedWeight=KERNEL_WEIGHT{X};\n#endif\n#ifdef PACKEDFLOAT\nblend+=unpack(texture2D(textureSampler,sampleCoord{X}))*computedWeight;\n#else\nblend+=texture2D(textureSampler,sampleCoord{X})*computedWeight;\n#endif","kernelBlurFragment2":"#ifdef DOF\nsampleDepth=sampleDistance(sampleCoord{X});\nfactor=clamp(1.0-((centerSampleDepth-sampleDepth)/centerSampleDepth),0.0,1.0);\ncomputedWeight=KERNEL_DEP_WEIGHT{X}*factor;\nsumOfWeights+=computedWeight;\n#else\ncomputedWeight=KERNEL_DEP_WEIGHT{X};\n#endif\n#ifdef PACKEDFLOAT\nblend+=unpack(texture2D(textureSampler,sampleCenter+delta*KERNEL_DEP_OFFSET{X}))*computedWeight;\n#else\nblend+=texture2D(textureSampler,sampleCenter+delta*KERNEL_DEP_OFFSET{X})*computedWeight;\n#endif","kernelBlurVaryingDeclaration":"varying vec2 sampleCoord{X};","kernelBlurVertex":"sampleCoord{X}=sampleCenter+delta*KERNEL_OFFSET{X};","backgroundVertexDeclaration":"uniform mat4 view;\nuniform mat4 viewProjection;\nuniform float shadowLevel;\n#ifdef DIFFUSE\nuniform mat4 diffuseMatrix;\nuniform vec2 vDiffuseInfos;\n#endif\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;\nuniform mat4 reflectionMatrix;\nuniform vec3 vReflectionMicrosurfaceInfos;\nuniform float fFovMultiplier;\n#endif\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif","backgroundFragmentDeclaration":" uniform vec4 vPrimaryColor;\nuniform vec4 vSecondaryColor;\nuniform vec4 vTertiaryColor;\nuniform float shadowLevel;\nuniform float alpha;\n#ifdef DIFFUSE\nuniform vec2 vDiffuseInfos;\n#endif\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;\nuniform mat4 reflectionMatrix;\nuniform vec3 vReflectionMicrosurfaceInfos;\n#endif\n#if defined(REFLECTIONFRESNEL) || defined(OPACITYFRESNEL)\nuniform vec3 vBackgroundCenter;\n#endif\n#ifdef REFLECTIONFRESNEL\nuniform vec4 vReflectionControl;\n#endif\n#if defined(REFLECTIONMAP_SPHERICAL) || defined(REFLECTIONMAP_PROJECTION) || defined(REFRACTION)\nuniform mat4 view;\n#endif","backgroundUboDeclaration":"layout(std140,column_major) uniform;\nuniform Material\n{\nuniform vec4 vPrimaryColor;\nuniform vec4 vSecondaryColor;\nuniform vec4 vTertiaryColor;\nuniform vec2 vDiffuseInfos;\nuniform vec2 vReflectionInfos;\nuniform mat4 diffuseMatrix;\nuniform mat4 reflectionMatrix;\nuniform vec3 vReflectionMicrosurfaceInfos;\nuniform float fFovMultiplier;\nuniform float pointSize;\nuniform float shadowLevel;\nuniform float alpha;\n#if defined(REFLECTIONFRESNEL) || defined(OPACITYFRESNEL)\nuniform vec3 vBackgroundCenter;\n#endif\n#ifdef REFLECTIONFRESNEL\nuniform vec4 vReflectionControl;\n#endif\n};\nuniform Scene {\nmat4 viewProjection;\nmat4 view;\n};"};
  88122. /// <reference path="../../../dist/preview release/babylon.d.ts"/>
  88123. var BABYLON;
  88124. (function (BABYLON) {
  88125. var GridMaterialDefines = /** @class */ (function (_super) {
  88126. __extends(GridMaterialDefines, _super);
  88127. function GridMaterialDefines() {
  88128. var _this = _super.call(this) || this;
  88129. _this.TRANSPARENT = false;
  88130. _this.FOG = false;
  88131. _this.PREMULTIPLYALPHA = false;
  88132. _this.rebuild();
  88133. return _this;
  88134. }
  88135. return GridMaterialDefines;
  88136. }(BABYLON.MaterialDefines));
  88137. /**
  88138. * The grid materials allows you to wrap any shape with a grid.
  88139. * Colors are customizable.
  88140. */
  88141. var GridMaterial = /** @class */ (function (_super) {
  88142. __extends(GridMaterial, _super);
  88143. /**
  88144. * constructor
  88145. * @param name The name given to the material in order to identify it afterwards.
  88146. * @param scene The scene the material is used in.
  88147. */
  88148. function GridMaterial(name, scene) {
  88149. var _this = _super.call(this, name, scene) || this;
  88150. /**
  88151. * Main color of the grid (e.g. between lines)
  88152. */
  88153. _this.mainColor = BABYLON.Color3.Black();
  88154. /**
  88155. * Color of the grid lines.
  88156. */
  88157. _this.lineColor = BABYLON.Color3.Teal();
  88158. /**
  88159. * The scale of the grid compared to unit.
  88160. */
  88161. _this.gridRatio = 1.0;
  88162. /**
  88163. * Allows setting an offset for the grid lines.
  88164. */
  88165. _this.gridOffset = BABYLON.Vector3.Zero();
  88166. /**
  88167. * The frequency of thicker lines.
  88168. */
  88169. _this.majorUnitFrequency = 10;
  88170. /**
  88171. * The visibility of minor units in the grid.
  88172. */
  88173. _this.minorUnitVisibility = 0.33;
  88174. /**
  88175. * The grid opacity outside of the lines.
  88176. */
  88177. _this.opacity = 1.0;
  88178. /**
  88179. * Determine RBG output is premultiplied by alpha value.
  88180. */
  88181. _this.preMultiplyAlpha = false;
  88182. _this._gridControl = new BABYLON.Vector4(_this.gridRatio, _this.majorUnitFrequency, _this.minorUnitVisibility, _this.opacity);
  88183. return _this;
  88184. }
  88185. /**
  88186. * Returns wehter or not the grid requires alpha blending.
  88187. */
  88188. GridMaterial.prototype.needAlphaBlending = function () {
  88189. return this.opacity < 1.0;
  88190. };
  88191. GridMaterial.prototype.needAlphaBlendingForMesh = function (mesh) {
  88192. return this.needAlphaBlending();
  88193. };
  88194. GridMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  88195. if (this.isFrozen) {
  88196. if (this._wasPreviouslyReady && subMesh.effect) {
  88197. return true;
  88198. }
  88199. }
  88200. if (!subMesh._materialDefines) {
  88201. subMesh._materialDefines = new GridMaterialDefines();
  88202. }
  88203. var defines = subMesh._materialDefines;
  88204. var scene = this.getScene();
  88205. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  88206. if (this._renderId === scene.getRenderId()) {
  88207. return true;
  88208. }
  88209. }
  88210. if (defines.TRANSPARENT !== (this.opacity < 1.0)) {
  88211. defines.TRANSPARENT = !defines.TRANSPARENT;
  88212. defines.markAsUnprocessed();
  88213. }
  88214. if (defines.PREMULTIPLYALPHA != this.preMultiplyAlpha) {
  88215. defines.PREMULTIPLYALPHA = !defines.PREMULTIPLYALPHA;
  88216. defines.markAsUnprocessed();
  88217. }
  88218. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, false, false, this.fogEnabled, false, defines);
  88219. // Get correct effect
  88220. if (defines.isDirty) {
  88221. defines.markAsProcessed();
  88222. scene.resetCachedMaterial();
  88223. // Attributes
  88224. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  88225. // Defines
  88226. var join = defines.toString();
  88227. subMesh.setEffect(scene.getEngine().createEffect("grid", attribs, ["projection", "worldView", "mainColor", "lineColor", "gridControl", "gridOffset", "vFogInfos", "vFogColor", "world", "view"], [], join, undefined, this.onCompiled, this.onError), defines);
  88228. }
  88229. if (!subMesh.effect || !subMesh.effect.isReady()) {
  88230. return false;
  88231. }
  88232. this._renderId = scene.getRenderId();
  88233. this._wasPreviouslyReady = true;
  88234. return true;
  88235. };
  88236. GridMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  88237. var scene = this.getScene();
  88238. var defines = subMesh._materialDefines;
  88239. if (!defines) {
  88240. return;
  88241. }
  88242. var effect = subMesh.effect;
  88243. if (!effect) {
  88244. return;
  88245. }
  88246. this._activeEffect = effect;
  88247. // Matrices
  88248. this.bindOnlyWorldMatrix(world);
  88249. this._activeEffect.setMatrix("worldView", world.multiply(scene.getViewMatrix()));
  88250. this._activeEffect.setMatrix("view", scene.getViewMatrix());
  88251. this._activeEffect.setMatrix("projection", scene.getProjectionMatrix());
  88252. // Uniforms
  88253. if (this._mustRebind(scene, effect)) {
  88254. this._activeEffect.setColor3("mainColor", this.mainColor);
  88255. this._activeEffect.setColor3("lineColor", this.lineColor);
  88256. this._activeEffect.setVector3("gridOffset", this.gridOffset);
  88257. this._gridControl.x = this.gridRatio;
  88258. this._gridControl.y = Math.round(this.majorUnitFrequency);
  88259. this._gridControl.z = this.minorUnitVisibility;
  88260. this._gridControl.w = this.opacity;
  88261. this._activeEffect.setVector4("gridControl", this._gridControl);
  88262. }
  88263. // Fog
  88264. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, this._activeEffect);
  88265. this._afterBind(mesh, this._activeEffect);
  88266. };
  88267. GridMaterial.prototype.dispose = function (forceDisposeEffect) {
  88268. _super.prototype.dispose.call(this, forceDisposeEffect);
  88269. };
  88270. GridMaterial.prototype.clone = function (name) {
  88271. var _this = this;
  88272. return BABYLON.SerializationHelper.Clone(function () { return new GridMaterial(name, _this.getScene()); }, this);
  88273. };
  88274. GridMaterial.prototype.serialize = function () {
  88275. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  88276. serializationObject.customType = "BABYLON.GridMaterial";
  88277. return serializationObject;
  88278. };
  88279. GridMaterial.prototype.getClassName = function () {
  88280. return "GridMaterial";
  88281. };
  88282. GridMaterial.Parse = function (source, scene, rootUrl) {
  88283. return BABYLON.SerializationHelper.Parse(function () { return new GridMaterial(source.name, scene); }, source, scene, rootUrl);
  88284. };
  88285. __decorate([
  88286. BABYLON.serializeAsColor3()
  88287. ], GridMaterial.prototype, "mainColor", void 0);
  88288. __decorate([
  88289. BABYLON.serializeAsColor3()
  88290. ], GridMaterial.prototype, "lineColor", void 0);
  88291. __decorate([
  88292. BABYLON.serialize()
  88293. ], GridMaterial.prototype, "gridRatio", void 0);
  88294. __decorate([
  88295. BABYLON.serializeAsColor3()
  88296. ], GridMaterial.prototype, "gridOffset", void 0);
  88297. __decorate([
  88298. BABYLON.serialize()
  88299. ], GridMaterial.prototype, "majorUnitFrequency", void 0);
  88300. __decorate([
  88301. BABYLON.serialize()
  88302. ], GridMaterial.prototype, "minorUnitVisibility", void 0);
  88303. __decorate([
  88304. BABYLON.serialize()
  88305. ], GridMaterial.prototype, "opacity", void 0);
  88306. __decorate([
  88307. BABYLON.serialize()
  88308. ], GridMaterial.prototype, "preMultiplyAlpha", void 0);
  88309. return GridMaterial;
  88310. }(BABYLON.PushMaterial));
  88311. BABYLON.GridMaterial = GridMaterial;
  88312. })(BABYLON || (BABYLON = {}));
  88313. //# sourceMappingURL=babylon.gridmaterial.js.map
  88314. 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}";
  88315. 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}";
  88316. /// <reference path="../../../dist/preview release/babylon.d.ts"/>
  88317. var BABYLON;
  88318. (function (BABYLON) {
  88319. var GLTFLoaderCoordinateSystemMode;
  88320. (function (GLTFLoaderCoordinateSystemMode) {
  88321. /**
  88322. * Automatically convert the glTF right-handed data to the appropriate system based on the current coordinate system mode of the scene.
  88323. */
  88324. GLTFLoaderCoordinateSystemMode[GLTFLoaderCoordinateSystemMode["AUTO"] = 0] = "AUTO";
  88325. /**
  88326. * Sets the useRightHandedSystem flag on the scene.
  88327. */
  88328. GLTFLoaderCoordinateSystemMode[GLTFLoaderCoordinateSystemMode["FORCE_RIGHT_HANDED"] = 1] = "FORCE_RIGHT_HANDED";
  88329. })(GLTFLoaderCoordinateSystemMode = BABYLON.GLTFLoaderCoordinateSystemMode || (BABYLON.GLTFLoaderCoordinateSystemMode = {}));
  88330. var GLTFLoaderAnimationStartMode;
  88331. (function (GLTFLoaderAnimationStartMode) {
  88332. /**
  88333. * No animation will start.
  88334. */
  88335. GLTFLoaderAnimationStartMode[GLTFLoaderAnimationStartMode["NONE"] = 0] = "NONE";
  88336. /**
  88337. * The first animation will start.
  88338. */
  88339. GLTFLoaderAnimationStartMode[GLTFLoaderAnimationStartMode["FIRST"] = 1] = "FIRST";
  88340. /**
  88341. * All animations will start.
  88342. */
  88343. GLTFLoaderAnimationStartMode[GLTFLoaderAnimationStartMode["ALL"] = 2] = "ALL";
  88344. })(GLTFLoaderAnimationStartMode = BABYLON.GLTFLoaderAnimationStartMode || (BABYLON.GLTFLoaderAnimationStartMode = {}));
  88345. var GLTFLoaderState;
  88346. (function (GLTFLoaderState) {
  88347. GLTFLoaderState[GLTFLoaderState["Loading"] = 0] = "Loading";
  88348. GLTFLoaderState[GLTFLoaderState["Ready"] = 1] = "Ready";
  88349. GLTFLoaderState[GLTFLoaderState["Complete"] = 2] = "Complete";
  88350. })(GLTFLoaderState = BABYLON.GLTFLoaderState || (BABYLON.GLTFLoaderState = {}));
  88351. var GLTFFileLoader = /** @class */ (function () {
  88352. function GLTFFileLoader() {
  88353. // #region Common options
  88354. /**
  88355. * Raised when the asset has been parsed.
  88356. * The data.json property stores the glTF JSON.
  88357. * The data.bin property stores the BIN chunk from a glTF binary or null if the input is not a glTF binary.
  88358. */
  88359. this.onParsedObservable = new BABYLON.Observable();
  88360. // #endregion
  88361. // #region V2 options
  88362. /**
  88363. * The coordinate system mode (AUTO, FORCE_RIGHT_HANDED).
  88364. */
  88365. this.coordinateSystemMode = GLTFLoaderCoordinateSystemMode.AUTO;
  88366. /**
  88367. * The animation start mode (NONE, FIRST, ALL).
  88368. */
  88369. this.animationStartMode = GLTFLoaderAnimationStartMode.FIRST;
  88370. /**
  88371. * Set to true to compile materials before raising the success callback.
  88372. */
  88373. this.compileMaterials = false;
  88374. /**
  88375. * Set to true to also compile materials with clip planes.
  88376. */
  88377. this.useClipPlane = false;
  88378. /**
  88379. * Set to true to compile shadow generators before raising the success callback.
  88380. */
  88381. this.compileShadowGenerators = false;
  88382. /**
  88383. * Raised when the loader creates a mesh after parsing the glTF properties of the mesh.
  88384. */
  88385. this.onMeshLoadedObservable = new BABYLON.Observable();
  88386. /**
  88387. * Raised when the loader creates a texture after parsing the glTF properties of the texture.
  88388. */
  88389. this.onTextureLoadedObservable = new BABYLON.Observable();
  88390. /**
  88391. * Raised when the loader creates a material after parsing the glTF properties of the material.
  88392. */
  88393. this.onMaterialLoadedObservable = new BABYLON.Observable();
  88394. /**
  88395. * Raised when the asset is completely loaded, immediately before the loader is disposed.
  88396. * For assets with LODs, raised when all of the LODs are complete.
  88397. * For assets without LODs, raised when the model is complete, immediately after onSuccess.
  88398. */
  88399. this.onCompleteObservable = new BABYLON.Observable();
  88400. /**
  88401. * Raised when the loader is disposed.
  88402. */
  88403. this.onDisposeObservable = new BABYLON.Observable();
  88404. /**
  88405. * Raised after a loader extension is created.
  88406. * Set additional options for a loader extension in this event.
  88407. */
  88408. this.onExtensionLoadedObservable = new BABYLON.Observable();
  88409. // #endregion
  88410. this._loader = null;
  88411. this.name = "gltf";
  88412. this.extensions = {
  88413. ".gltf": { isBinary: false },
  88414. ".glb": { isBinary: true }
  88415. };
  88416. }
  88417. Object.defineProperty(GLTFFileLoader.prototype, "onParsed", {
  88418. set: function (callback) {
  88419. if (this._onParsedObserver) {
  88420. this.onParsedObservable.remove(this._onParsedObserver);
  88421. }
  88422. this._onParsedObserver = this.onParsedObservable.add(callback);
  88423. },
  88424. enumerable: true,
  88425. configurable: true
  88426. });
  88427. Object.defineProperty(GLTFFileLoader.prototype, "onMeshLoaded", {
  88428. set: function (callback) {
  88429. if (this._onMeshLoadedObserver) {
  88430. this.onMeshLoadedObservable.remove(this._onMeshLoadedObserver);
  88431. }
  88432. this._onMeshLoadedObserver = this.onMeshLoadedObservable.add(callback);
  88433. },
  88434. enumerable: true,
  88435. configurable: true
  88436. });
  88437. Object.defineProperty(GLTFFileLoader.prototype, "onTextureLoaded", {
  88438. set: function (callback) {
  88439. if (this._onTextureLoadedObserver) {
  88440. this.onTextureLoadedObservable.remove(this._onTextureLoadedObserver);
  88441. }
  88442. this._onTextureLoadedObserver = this.onTextureLoadedObservable.add(callback);
  88443. },
  88444. enumerable: true,
  88445. configurable: true
  88446. });
  88447. Object.defineProperty(GLTFFileLoader.prototype, "onMaterialLoaded", {
  88448. set: function (callback) {
  88449. if (this._onMaterialLoadedObserver) {
  88450. this.onMaterialLoadedObservable.remove(this._onMaterialLoadedObserver);
  88451. }
  88452. this._onMaterialLoadedObserver = this.onMaterialLoadedObservable.add(callback);
  88453. },
  88454. enumerable: true,
  88455. configurable: true
  88456. });
  88457. Object.defineProperty(GLTFFileLoader.prototype, "onComplete", {
  88458. set: function (callback) {
  88459. if (this._onCompleteObserver) {
  88460. this.onCompleteObservable.remove(this._onCompleteObserver);
  88461. }
  88462. this._onCompleteObserver = this.onCompleteObservable.add(callback);
  88463. },
  88464. enumerable: true,
  88465. configurable: true
  88466. });
  88467. Object.defineProperty(GLTFFileLoader.prototype, "onDispose", {
  88468. set: function (callback) {
  88469. if (this._onDisposeObserver) {
  88470. this.onDisposeObservable.remove(this._onDisposeObserver);
  88471. }
  88472. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  88473. },
  88474. enumerable: true,
  88475. configurable: true
  88476. });
  88477. Object.defineProperty(GLTFFileLoader.prototype, "onExtensionLoaded", {
  88478. set: function (callback) {
  88479. if (this._onExtensionLoadedObserver) {
  88480. this.onExtensionLoadedObservable.remove(this._onExtensionLoadedObserver);
  88481. }
  88482. this._onExtensionLoadedObserver = this.onExtensionLoadedObservable.add(callback);
  88483. },
  88484. enumerable: true,
  88485. configurable: true
  88486. });
  88487. Object.defineProperty(GLTFFileLoader.prototype, "loaderState", {
  88488. /**
  88489. * The loader state or null if not active.
  88490. */
  88491. get: function () {
  88492. return this._loader ? this._loader.state : null;
  88493. },
  88494. enumerable: true,
  88495. configurable: true
  88496. });
  88497. /**
  88498. * Disposes the loader, releases resources during load, and cancels any outstanding requests.
  88499. */
  88500. GLTFFileLoader.prototype.dispose = function () {
  88501. if (this._loader) {
  88502. this._loader.dispose();
  88503. this._loader = null;
  88504. }
  88505. this.onMeshLoadedObservable.clear();
  88506. this.onTextureLoadedObservable.clear();
  88507. this.onMaterialLoadedObservable.clear();
  88508. this.onDisposeObservable.notifyObservers(this);
  88509. this.onDisposeObservable.clear();
  88510. };
  88511. GLTFFileLoader.prototype.importMeshAsync = function (meshesNames, scene, data, rootUrl, onProgress) {
  88512. var _this = this;
  88513. return Promise.resolve().then(function () {
  88514. var loaderData = _this._parse(data);
  88515. _this._loader = _this._getLoader(loaderData);
  88516. return _this._loader.importMeshAsync(meshesNames, scene, loaderData, rootUrl, onProgress);
  88517. });
  88518. };
  88519. GLTFFileLoader.prototype.loadAsync = function (scene, data, rootUrl, onProgress) {
  88520. var _this = this;
  88521. return Promise.resolve().then(function () {
  88522. var loaderData = _this._parse(data);
  88523. _this._loader = _this._getLoader(loaderData);
  88524. return _this._loader.loadAsync(scene, loaderData, rootUrl, onProgress);
  88525. });
  88526. };
  88527. GLTFFileLoader.prototype.loadAssetContainerAsync = function (scene, data, rootUrl, onProgress) {
  88528. var _this = this;
  88529. return Promise.resolve().then(function () {
  88530. var loaderData = _this._parse(data);
  88531. _this._loader = _this._getLoader(loaderData);
  88532. return _this._loader.importMeshAsync(null, scene, loaderData, rootUrl, onProgress).then(function (result) {
  88533. var container = new BABYLON.AssetContainer(scene);
  88534. Array.prototype.push.apply(container.meshes, result.meshes);
  88535. Array.prototype.push.apply(container.particleSystems, result.particleSystems);
  88536. Array.prototype.push.apply(container.skeletons, result.skeletons);
  88537. container.removeAllFromScene();
  88538. return container;
  88539. });
  88540. });
  88541. };
  88542. GLTFFileLoader.prototype.canDirectLoad = function (data) {
  88543. return ((data.indexOf("scene") !== -1) && (data.indexOf("node") !== -1));
  88544. };
  88545. GLTFFileLoader.prototype.createPlugin = function () {
  88546. return new GLTFFileLoader();
  88547. };
  88548. GLTFFileLoader.prototype._parse = function (data) {
  88549. var parsedData;
  88550. if (data instanceof ArrayBuffer) {
  88551. parsedData = GLTFFileLoader._parseBinary(data);
  88552. }
  88553. else {
  88554. parsedData = {
  88555. json: JSON.parse(data),
  88556. bin: null
  88557. };
  88558. }
  88559. this.onParsedObservable.notifyObservers(parsedData);
  88560. this.onParsedObservable.clear();
  88561. return parsedData;
  88562. };
  88563. GLTFFileLoader.prototype._getLoader = function (loaderData) {
  88564. var _this = this;
  88565. var loaderVersion = { major: 2, minor: 0 };
  88566. var asset = loaderData.json.asset || {};
  88567. var version = GLTFFileLoader._parseVersion(asset.version);
  88568. if (!version) {
  88569. throw new Error("Invalid version: " + asset.version);
  88570. }
  88571. if (asset.minVersion !== undefined) {
  88572. var minVersion = GLTFFileLoader._parseVersion(asset.minVersion);
  88573. if (!minVersion) {
  88574. throw new Error("Invalid minimum version: " + asset.minVersion);
  88575. }
  88576. if (GLTFFileLoader._compareVersion(minVersion, loaderVersion) > 0) {
  88577. throw new Error("Incompatible minimum version: " + asset.minVersion);
  88578. }
  88579. }
  88580. var createLoaders = {
  88581. 1: GLTFFileLoader.CreateGLTFLoaderV1,
  88582. 2: GLTFFileLoader.CreateGLTFLoaderV2
  88583. };
  88584. var createLoader = createLoaders[version.major];
  88585. if (!createLoader) {
  88586. throw new Error("Unsupported version: " + asset.version);
  88587. }
  88588. var loader = createLoader();
  88589. loader.coordinateSystemMode = this.coordinateSystemMode;
  88590. loader.animationStartMode = this.animationStartMode;
  88591. loader.compileMaterials = this.compileMaterials;
  88592. loader.useClipPlane = this.useClipPlane;
  88593. loader.compileShadowGenerators = this.compileShadowGenerators;
  88594. loader.onMeshLoadedObservable.add(function (mesh) { return _this.onMeshLoadedObservable.notifyObservers(mesh); });
  88595. loader.onTextureLoadedObservable.add(function (texture) { return _this.onTextureLoadedObservable.notifyObservers(texture); });
  88596. loader.onMaterialLoadedObservable.add(function (material) { return _this.onMaterialLoadedObservable.notifyObservers(material); });
  88597. loader.onExtensionLoadedObservable.add(function (extension) { return _this.onExtensionLoadedObservable.notifyObservers(extension); });
  88598. loader.onCompleteObservable.add(function () {
  88599. _this.onMeshLoadedObservable.clear();
  88600. _this.onTextureLoadedObservable.clear();
  88601. _this.onMaterialLoadedObservable.clear();
  88602. _this.onCompleteObservable.notifyObservers(_this);
  88603. _this.onCompleteObservable.clear();
  88604. });
  88605. return loader;
  88606. };
  88607. GLTFFileLoader._parseBinary = function (data) {
  88608. var Binary = {
  88609. Magic: 0x46546C67
  88610. };
  88611. var binaryReader = new BinaryReader(data);
  88612. var magic = binaryReader.readUint32();
  88613. if (magic !== Binary.Magic) {
  88614. throw new Error("Unexpected magic: " + magic);
  88615. }
  88616. var version = binaryReader.readUint32();
  88617. switch (version) {
  88618. case 1: return GLTFFileLoader._parseV1(binaryReader);
  88619. case 2: return GLTFFileLoader._parseV2(binaryReader);
  88620. }
  88621. throw new Error("Unsupported version: " + version);
  88622. };
  88623. GLTFFileLoader._parseV1 = function (binaryReader) {
  88624. var ContentFormat = {
  88625. JSON: 0
  88626. };
  88627. var length = binaryReader.readUint32();
  88628. if (length != binaryReader.getLength()) {
  88629. throw new Error("Length in header does not match actual data length: " + length + " != " + binaryReader.getLength());
  88630. }
  88631. var contentLength = binaryReader.readUint32();
  88632. var contentFormat = binaryReader.readUint32();
  88633. var content;
  88634. switch (contentFormat) {
  88635. case ContentFormat.JSON: {
  88636. content = JSON.parse(GLTFFileLoader._decodeBufferToText(binaryReader.readUint8Array(contentLength)));
  88637. break;
  88638. }
  88639. default: {
  88640. throw new Error("Unexpected content format: " + contentFormat);
  88641. }
  88642. }
  88643. var bytesRemaining = binaryReader.getLength() - binaryReader.getPosition();
  88644. var body = binaryReader.readUint8Array(bytesRemaining);
  88645. return {
  88646. json: content,
  88647. bin: body
  88648. };
  88649. };
  88650. GLTFFileLoader._parseV2 = function (binaryReader) {
  88651. var ChunkFormat = {
  88652. JSON: 0x4E4F534A,
  88653. BIN: 0x004E4942
  88654. };
  88655. var length = binaryReader.readUint32();
  88656. if (length !== binaryReader.getLength()) {
  88657. throw new Error("Length in header does not match actual data length: " + length + " != " + binaryReader.getLength());
  88658. }
  88659. // JSON chunk
  88660. var chunkLength = binaryReader.readUint32();
  88661. var chunkFormat = binaryReader.readUint32();
  88662. if (chunkFormat !== ChunkFormat.JSON) {
  88663. throw new Error("First chunk format is not JSON");
  88664. }
  88665. var json = JSON.parse(GLTFFileLoader._decodeBufferToText(binaryReader.readUint8Array(chunkLength)));
  88666. // Look for BIN chunk
  88667. var bin = null;
  88668. while (binaryReader.getPosition() < binaryReader.getLength()) {
  88669. var chunkLength_1 = binaryReader.readUint32();
  88670. var chunkFormat_1 = binaryReader.readUint32();
  88671. switch (chunkFormat_1) {
  88672. case ChunkFormat.JSON: {
  88673. throw new Error("Unexpected JSON chunk");
  88674. }
  88675. case ChunkFormat.BIN: {
  88676. bin = binaryReader.readUint8Array(chunkLength_1);
  88677. break;
  88678. }
  88679. default: {
  88680. // ignore unrecognized chunkFormat
  88681. binaryReader.skipBytes(chunkLength_1);
  88682. break;
  88683. }
  88684. }
  88685. }
  88686. return {
  88687. json: json,
  88688. bin: bin
  88689. };
  88690. };
  88691. GLTFFileLoader._parseVersion = function (version) {
  88692. if (version === "1.0" || version === "1.0.1") {
  88693. return {
  88694. major: 1,
  88695. minor: 0
  88696. };
  88697. }
  88698. var match = (version + "").match(/^(\d+)\.(\d+)/);
  88699. if (!match) {
  88700. return null;
  88701. }
  88702. return {
  88703. major: parseInt(match[1]),
  88704. minor: parseInt(match[2])
  88705. };
  88706. };
  88707. GLTFFileLoader._compareVersion = function (a, b) {
  88708. if (a.major > b.major)
  88709. return 1;
  88710. if (a.major < b.major)
  88711. return -1;
  88712. if (a.minor > b.minor)
  88713. return 1;
  88714. if (a.minor < b.minor)
  88715. return -1;
  88716. return 0;
  88717. };
  88718. GLTFFileLoader._decodeBufferToText = function (buffer) {
  88719. var result = "";
  88720. var length = buffer.byteLength;
  88721. for (var i = 0; i < length; i++) {
  88722. result += String.fromCharCode(buffer[i]);
  88723. }
  88724. return result;
  88725. };
  88726. // #endregion
  88727. // #region V1 options
  88728. GLTFFileLoader.IncrementalLoading = true;
  88729. GLTFFileLoader.HomogeneousCoordinates = false;
  88730. return GLTFFileLoader;
  88731. }());
  88732. BABYLON.GLTFFileLoader = GLTFFileLoader;
  88733. var BinaryReader = /** @class */ (function () {
  88734. function BinaryReader(arrayBuffer) {
  88735. this._arrayBuffer = arrayBuffer;
  88736. this._dataView = new DataView(arrayBuffer);
  88737. this._byteOffset = 0;
  88738. }
  88739. BinaryReader.prototype.getPosition = function () {
  88740. return this._byteOffset;
  88741. };
  88742. BinaryReader.prototype.getLength = function () {
  88743. return this._arrayBuffer.byteLength;
  88744. };
  88745. BinaryReader.prototype.readUint32 = function () {
  88746. var value = this._dataView.getUint32(this._byteOffset, true);
  88747. this._byteOffset += 4;
  88748. return value;
  88749. };
  88750. BinaryReader.prototype.readUint8Array = function (length) {
  88751. var value = new Uint8Array(this._arrayBuffer, this._byteOffset, length);
  88752. this._byteOffset += length;
  88753. return value;
  88754. };
  88755. BinaryReader.prototype.skipBytes = function (length) {
  88756. this._byteOffset += length;
  88757. };
  88758. return BinaryReader;
  88759. }());
  88760. if (BABYLON.SceneLoader) {
  88761. BABYLON.SceneLoader.RegisterPlugin(new GLTFFileLoader());
  88762. }
  88763. })(BABYLON || (BABYLON = {}));
  88764. //# sourceMappingURL=babylon.glTFFileLoader.js.map
  88765. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  88766. var BABYLON;
  88767. (function (BABYLON) {
  88768. var GLTF1;
  88769. (function (GLTF1) {
  88770. /**
  88771. * Enums
  88772. */
  88773. var EComponentType;
  88774. (function (EComponentType) {
  88775. EComponentType[EComponentType["BYTE"] = 5120] = "BYTE";
  88776. EComponentType[EComponentType["UNSIGNED_BYTE"] = 5121] = "UNSIGNED_BYTE";
  88777. EComponentType[EComponentType["SHORT"] = 5122] = "SHORT";
  88778. EComponentType[EComponentType["UNSIGNED_SHORT"] = 5123] = "UNSIGNED_SHORT";
  88779. EComponentType[EComponentType["FLOAT"] = 5126] = "FLOAT";
  88780. })(EComponentType = GLTF1.EComponentType || (GLTF1.EComponentType = {}));
  88781. var EShaderType;
  88782. (function (EShaderType) {
  88783. EShaderType[EShaderType["FRAGMENT"] = 35632] = "FRAGMENT";
  88784. EShaderType[EShaderType["VERTEX"] = 35633] = "VERTEX";
  88785. })(EShaderType = GLTF1.EShaderType || (GLTF1.EShaderType = {}));
  88786. var EParameterType;
  88787. (function (EParameterType) {
  88788. EParameterType[EParameterType["BYTE"] = 5120] = "BYTE";
  88789. EParameterType[EParameterType["UNSIGNED_BYTE"] = 5121] = "UNSIGNED_BYTE";
  88790. EParameterType[EParameterType["SHORT"] = 5122] = "SHORT";
  88791. EParameterType[EParameterType["UNSIGNED_SHORT"] = 5123] = "UNSIGNED_SHORT";
  88792. EParameterType[EParameterType["INT"] = 5124] = "INT";
  88793. EParameterType[EParameterType["UNSIGNED_INT"] = 5125] = "UNSIGNED_INT";
  88794. EParameterType[EParameterType["FLOAT"] = 5126] = "FLOAT";
  88795. EParameterType[EParameterType["FLOAT_VEC2"] = 35664] = "FLOAT_VEC2";
  88796. EParameterType[EParameterType["FLOAT_VEC3"] = 35665] = "FLOAT_VEC3";
  88797. EParameterType[EParameterType["FLOAT_VEC4"] = 35666] = "FLOAT_VEC4";
  88798. EParameterType[EParameterType["INT_VEC2"] = 35667] = "INT_VEC2";
  88799. EParameterType[EParameterType["INT_VEC3"] = 35668] = "INT_VEC3";
  88800. EParameterType[EParameterType["INT_VEC4"] = 35669] = "INT_VEC4";
  88801. EParameterType[EParameterType["BOOL"] = 35670] = "BOOL";
  88802. EParameterType[EParameterType["BOOL_VEC2"] = 35671] = "BOOL_VEC2";
  88803. EParameterType[EParameterType["BOOL_VEC3"] = 35672] = "BOOL_VEC3";
  88804. EParameterType[EParameterType["BOOL_VEC4"] = 35673] = "BOOL_VEC4";
  88805. EParameterType[EParameterType["FLOAT_MAT2"] = 35674] = "FLOAT_MAT2";
  88806. EParameterType[EParameterType["FLOAT_MAT3"] = 35675] = "FLOAT_MAT3";
  88807. EParameterType[EParameterType["FLOAT_MAT4"] = 35676] = "FLOAT_MAT4";
  88808. EParameterType[EParameterType["SAMPLER_2D"] = 35678] = "SAMPLER_2D";
  88809. })(EParameterType = GLTF1.EParameterType || (GLTF1.EParameterType = {}));
  88810. var ETextureWrapMode;
  88811. (function (ETextureWrapMode) {
  88812. ETextureWrapMode[ETextureWrapMode["CLAMP_TO_EDGE"] = 33071] = "CLAMP_TO_EDGE";
  88813. ETextureWrapMode[ETextureWrapMode["MIRRORED_REPEAT"] = 33648] = "MIRRORED_REPEAT";
  88814. ETextureWrapMode[ETextureWrapMode["REPEAT"] = 10497] = "REPEAT";
  88815. })(ETextureWrapMode = GLTF1.ETextureWrapMode || (GLTF1.ETextureWrapMode = {}));
  88816. var ETextureFilterType;
  88817. (function (ETextureFilterType) {
  88818. ETextureFilterType[ETextureFilterType["NEAREST"] = 9728] = "NEAREST";
  88819. ETextureFilterType[ETextureFilterType["LINEAR"] = 9728] = "LINEAR";
  88820. ETextureFilterType[ETextureFilterType["NEAREST_MIPMAP_NEAREST"] = 9984] = "NEAREST_MIPMAP_NEAREST";
  88821. ETextureFilterType[ETextureFilterType["LINEAR_MIPMAP_NEAREST"] = 9985] = "LINEAR_MIPMAP_NEAREST";
  88822. ETextureFilterType[ETextureFilterType["NEAREST_MIPMAP_LINEAR"] = 9986] = "NEAREST_MIPMAP_LINEAR";
  88823. ETextureFilterType[ETextureFilterType["LINEAR_MIPMAP_LINEAR"] = 9987] = "LINEAR_MIPMAP_LINEAR";
  88824. })(ETextureFilterType = GLTF1.ETextureFilterType || (GLTF1.ETextureFilterType = {}));
  88825. var ETextureFormat;
  88826. (function (ETextureFormat) {
  88827. ETextureFormat[ETextureFormat["ALPHA"] = 6406] = "ALPHA";
  88828. ETextureFormat[ETextureFormat["RGB"] = 6407] = "RGB";
  88829. ETextureFormat[ETextureFormat["RGBA"] = 6408] = "RGBA";
  88830. ETextureFormat[ETextureFormat["LUMINANCE"] = 6409] = "LUMINANCE";
  88831. ETextureFormat[ETextureFormat["LUMINANCE_ALPHA"] = 6410] = "LUMINANCE_ALPHA";
  88832. })(ETextureFormat = GLTF1.ETextureFormat || (GLTF1.ETextureFormat = {}));
  88833. var ECullingType;
  88834. (function (ECullingType) {
  88835. ECullingType[ECullingType["FRONT"] = 1028] = "FRONT";
  88836. ECullingType[ECullingType["BACK"] = 1029] = "BACK";
  88837. ECullingType[ECullingType["FRONT_AND_BACK"] = 1032] = "FRONT_AND_BACK";
  88838. })(ECullingType = GLTF1.ECullingType || (GLTF1.ECullingType = {}));
  88839. var EBlendingFunction;
  88840. (function (EBlendingFunction) {
  88841. EBlendingFunction[EBlendingFunction["ZERO"] = 0] = "ZERO";
  88842. EBlendingFunction[EBlendingFunction["ONE"] = 1] = "ONE";
  88843. EBlendingFunction[EBlendingFunction["SRC_COLOR"] = 768] = "SRC_COLOR";
  88844. EBlendingFunction[EBlendingFunction["ONE_MINUS_SRC_COLOR"] = 769] = "ONE_MINUS_SRC_COLOR";
  88845. EBlendingFunction[EBlendingFunction["DST_COLOR"] = 774] = "DST_COLOR";
  88846. EBlendingFunction[EBlendingFunction["ONE_MINUS_DST_COLOR"] = 775] = "ONE_MINUS_DST_COLOR";
  88847. EBlendingFunction[EBlendingFunction["SRC_ALPHA"] = 770] = "SRC_ALPHA";
  88848. EBlendingFunction[EBlendingFunction["ONE_MINUS_SRC_ALPHA"] = 771] = "ONE_MINUS_SRC_ALPHA";
  88849. EBlendingFunction[EBlendingFunction["DST_ALPHA"] = 772] = "DST_ALPHA";
  88850. EBlendingFunction[EBlendingFunction["ONE_MINUS_DST_ALPHA"] = 773] = "ONE_MINUS_DST_ALPHA";
  88851. EBlendingFunction[EBlendingFunction["CONSTANT_COLOR"] = 32769] = "CONSTANT_COLOR";
  88852. EBlendingFunction[EBlendingFunction["ONE_MINUS_CONSTANT_COLOR"] = 32770] = "ONE_MINUS_CONSTANT_COLOR";
  88853. EBlendingFunction[EBlendingFunction["CONSTANT_ALPHA"] = 32771] = "CONSTANT_ALPHA";
  88854. EBlendingFunction[EBlendingFunction["ONE_MINUS_CONSTANT_ALPHA"] = 32772] = "ONE_MINUS_CONSTANT_ALPHA";
  88855. EBlendingFunction[EBlendingFunction["SRC_ALPHA_SATURATE"] = 776] = "SRC_ALPHA_SATURATE";
  88856. })(EBlendingFunction = GLTF1.EBlendingFunction || (GLTF1.EBlendingFunction = {}));
  88857. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  88858. })(BABYLON || (BABYLON = {}));
  88859. //# sourceMappingURL=babylon.glTFLoaderInterfaces.js.map
  88860. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  88861. var BABYLON;
  88862. (function (BABYLON) {
  88863. var GLTF1;
  88864. (function (GLTF1) {
  88865. /**
  88866. * Tokenizer. Used for shaders compatibility
  88867. * Automatically map world, view, projection, worldViewProjection, attributes and so on
  88868. */
  88869. var ETokenType;
  88870. (function (ETokenType) {
  88871. ETokenType[ETokenType["IDENTIFIER"] = 1] = "IDENTIFIER";
  88872. ETokenType[ETokenType["UNKNOWN"] = 2] = "UNKNOWN";
  88873. ETokenType[ETokenType["END_OF_INPUT"] = 3] = "END_OF_INPUT";
  88874. })(ETokenType || (ETokenType = {}));
  88875. var Tokenizer = /** @class */ (function () {
  88876. function Tokenizer(toParse) {
  88877. this._pos = 0;
  88878. this.isLetterOrDigitPattern = /^[a-zA-Z0-9]+$/;
  88879. this._toParse = toParse;
  88880. this._maxPos = toParse.length;
  88881. }
  88882. Tokenizer.prototype.getNextToken = function () {
  88883. if (this.isEnd())
  88884. return ETokenType.END_OF_INPUT;
  88885. this.currentString = this.read();
  88886. this.currentToken = ETokenType.UNKNOWN;
  88887. if (this.currentString === "_" || this.isLetterOrDigitPattern.test(this.currentString)) {
  88888. this.currentToken = ETokenType.IDENTIFIER;
  88889. this.currentIdentifier = this.currentString;
  88890. while (!this.isEnd() && (this.isLetterOrDigitPattern.test(this.currentString = this.peek()) || this.currentString === "_")) {
  88891. this.currentIdentifier += this.currentString;
  88892. this.forward();
  88893. }
  88894. }
  88895. return this.currentToken;
  88896. };
  88897. Tokenizer.prototype.peek = function () {
  88898. return this._toParse[this._pos];
  88899. };
  88900. Tokenizer.prototype.read = function () {
  88901. return this._toParse[this._pos++];
  88902. };
  88903. Tokenizer.prototype.forward = function () {
  88904. this._pos++;
  88905. };
  88906. Tokenizer.prototype.isEnd = function () {
  88907. return this._pos >= this._maxPos;
  88908. };
  88909. return Tokenizer;
  88910. }());
  88911. /**
  88912. * Values
  88913. */
  88914. var glTFTransforms = ["MODEL", "VIEW", "PROJECTION", "MODELVIEW", "MODELVIEWPROJECTION", "JOINTMATRIX"];
  88915. var babylonTransforms = ["world", "view", "projection", "worldView", "worldViewProjection", "mBones"];
  88916. var glTFAnimationPaths = ["translation", "rotation", "scale"];
  88917. var babylonAnimationPaths = ["position", "rotationQuaternion", "scaling"];
  88918. /**
  88919. * Parse
  88920. */
  88921. var parseBuffers = function (parsedBuffers, gltfRuntime) {
  88922. for (var buf in parsedBuffers) {
  88923. var parsedBuffer = parsedBuffers[buf];
  88924. gltfRuntime.buffers[buf] = parsedBuffer;
  88925. gltfRuntime.buffersCount++;
  88926. }
  88927. };
  88928. var parseShaders = function (parsedShaders, gltfRuntime) {
  88929. for (var sha in parsedShaders) {
  88930. var parsedShader = parsedShaders[sha];
  88931. gltfRuntime.shaders[sha] = parsedShader;
  88932. gltfRuntime.shaderscount++;
  88933. }
  88934. };
  88935. var parseObject = function (parsedObjects, runtimeProperty, gltfRuntime) {
  88936. for (var object in parsedObjects) {
  88937. var parsedObject = parsedObjects[object];
  88938. gltfRuntime[runtimeProperty][object] = parsedObject;
  88939. }
  88940. };
  88941. /**
  88942. * Utils
  88943. */
  88944. var normalizeUVs = function (buffer) {
  88945. if (!buffer) {
  88946. return;
  88947. }
  88948. for (var i = 0; i < buffer.length / 2; i++) {
  88949. buffer[i * 2 + 1] = 1.0 - buffer[i * 2 + 1];
  88950. }
  88951. };
  88952. var getAttribute = function (attributeParameter) {
  88953. if (attributeParameter.semantic === "NORMAL") {
  88954. return "normal";
  88955. }
  88956. else if (attributeParameter.semantic === "POSITION") {
  88957. return "position";
  88958. }
  88959. else if (attributeParameter.semantic === "JOINT") {
  88960. return "matricesIndices";
  88961. }
  88962. else if (attributeParameter.semantic === "WEIGHT") {
  88963. return "matricesWeights";
  88964. }
  88965. else if (attributeParameter.semantic === "COLOR") {
  88966. return "color";
  88967. }
  88968. else if (attributeParameter.semantic && attributeParameter.semantic.indexOf("TEXCOORD_") !== -1) {
  88969. var channel = Number(attributeParameter.semantic.split("_")[1]);
  88970. return "uv" + (channel === 0 ? "" : channel + 1);
  88971. }
  88972. return null;
  88973. };
  88974. /**
  88975. * Loads and creates animations
  88976. */
  88977. var loadAnimations = function (gltfRuntime) {
  88978. for (var anim in gltfRuntime.animations) {
  88979. var animation = gltfRuntime.animations[anim];
  88980. if (!animation.channels || !animation.samplers) {
  88981. continue;
  88982. }
  88983. var lastAnimation = null;
  88984. for (var i = 0; i < animation.channels.length; i++) {
  88985. // Get parameters and load buffers
  88986. var channel = animation.channels[i];
  88987. var sampler = animation.samplers[channel.sampler];
  88988. if (!sampler) {
  88989. continue;
  88990. }
  88991. var inputData = null;
  88992. var outputData = null;
  88993. if (animation.parameters) {
  88994. inputData = animation.parameters[sampler.input];
  88995. outputData = animation.parameters[sampler.output];
  88996. }
  88997. else {
  88998. inputData = sampler.input;
  88999. outputData = sampler.output;
  89000. }
  89001. var bufferInput = GLTF1.GLTFUtils.GetBufferFromAccessor(gltfRuntime, gltfRuntime.accessors[inputData]);
  89002. var bufferOutput = GLTF1.GLTFUtils.GetBufferFromAccessor(gltfRuntime, gltfRuntime.accessors[outputData]);
  89003. var targetID = channel.target.id;
  89004. var targetNode = gltfRuntime.scene.getNodeByID(targetID);
  89005. if (targetNode === null) {
  89006. targetNode = gltfRuntime.scene.getNodeByName(targetID);
  89007. }
  89008. if (targetNode === null) {
  89009. BABYLON.Tools.Warn("Creating animation named " + anim + ". But cannot find node named " + targetID + " to attach to");
  89010. continue;
  89011. }
  89012. var isBone = targetNode instanceof BABYLON.Bone;
  89013. // Get target path (position, rotation or scaling)
  89014. var targetPath = channel.target.path;
  89015. var targetPathIndex = glTFAnimationPaths.indexOf(targetPath);
  89016. if (targetPathIndex !== -1) {
  89017. targetPath = babylonAnimationPaths[targetPathIndex];
  89018. }
  89019. // Determine animation type
  89020. var animationType = BABYLON.Animation.ANIMATIONTYPE_MATRIX;
  89021. if (!isBone) {
  89022. if (targetPath === "rotationQuaternion") {
  89023. animationType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  89024. targetNode.rotationQuaternion = new BABYLON.Quaternion();
  89025. }
  89026. else {
  89027. animationType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  89028. }
  89029. }
  89030. // Create animation and key frames
  89031. var babylonAnimation = null;
  89032. var keys = [];
  89033. var arrayOffset = 0;
  89034. var modifyKey = false;
  89035. if (isBone && lastAnimation && lastAnimation.getKeys().length === bufferInput.length) {
  89036. babylonAnimation = lastAnimation;
  89037. modifyKey = true;
  89038. }
  89039. if (!modifyKey) {
  89040. babylonAnimation = new BABYLON.Animation(anim, isBone ? "_matrix" : targetPath, 1, animationType, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  89041. }
  89042. // For each frame
  89043. for (var j = 0; j < bufferInput.length; j++) {
  89044. var value = null;
  89045. if (targetPath === "rotationQuaternion") {
  89046. value = BABYLON.Quaternion.FromArray([bufferOutput[arrayOffset], bufferOutput[arrayOffset + 1], bufferOutput[arrayOffset + 2], bufferOutput[arrayOffset + 3]]);
  89047. arrayOffset += 4;
  89048. }
  89049. else {
  89050. value = BABYLON.Vector3.FromArray([bufferOutput[arrayOffset], bufferOutput[arrayOffset + 1], bufferOutput[arrayOffset + 2]]);
  89051. arrayOffset += 3;
  89052. }
  89053. if (isBone) {
  89054. var bone = targetNode;
  89055. var translation = BABYLON.Vector3.Zero();
  89056. var rotationQuaternion = new BABYLON.Quaternion();
  89057. var scaling = BABYLON.Vector3.Zero();
  89058. // Warning on decompose
  89059. var mat = bone.getBaseMatrix();
  89060. if (modifyKey && lastAnimation) {
  89061. mat = lastAnimation.getKeys()[j].value;
  89062. }
  89063. mat.decompose(scaling, rotationQuaternion, translation);
  89064. if (targetPath === "position") {
  89065. translation = value;
  89066. }
  89067. else if (targetPath === "rotationQuaternion") {
  89068. rotationQuaternion = value;
  89069. }
  89070. else {
  89071. scaling = value;
  89072. }
  89073. value = BABYLON.Matrix.Compose(scaling, rotationQuaternion, translation);
  89074. }
  89075. if (!modifyKey) {
  89076. keys.push({
  89077. frame: bufferInput[j],
  89078. value: value
  89079. });
  89080. }
  89081. else if (lastAnimation) {
  89082. lastAnimation.getKeys()[j].value = value;
  89083. }
  89084. }
  89085. // Finish
  89086. if (!modifyKey && babylonAnimation) {
  89087. babylonAnimation.setKeys(keys);
  89088. targetNode.animations.push(babylonAnimation);
  89089. }
  89090. lastAnimation = babylonAnimation;
  89091. gltfRuntime.scene.stopAnimation(targetNode);
  89092. gltfRuntime.scene.beginAnimation(targetNode, 0, bufferInput[bufferInput.length - 1], true, 1.0);
  89093. }
  89094. }
  89095. };
  89096. /**
  89097. * Returns the bones transformation matrix
  89098. */
  89099. var configureBoneTransformation = function (node) {
  89100. var mat = null;
  89101. if (node.translation || node.rotation || node.scale) {
  89102. var scale = BABYLON.Vector3.FromArray(node.scale || [1, 1, 1]);
  89103. var rotation = BABYLON.Quaternion.FromArray(node.rotation || [0, 0, 0, 1]);
  89104. var position = BABYLON.Vector3.FromArray(node.translation || [0, 0, 0]);
  89105. mat = BABYLON.Matrix.Compose(scale, rotation, position);
  89106. }
  89107. else {
  89108. mat = BABYLON.Matrix.FromArray(node.matrix);
  89109. }
  89110. return mat;
  89111. };
  89112. /**
  89113. * Returns the parent bone
  89114. */
  89115. var getParentBone = function (gltfRuntime, skins, jointName, newSkeleton) {
  89116. // Try to find
  89117. for (var i = 0; i < newSkeleton.bones.length; i++) {
  89118. if (newSkeleton.bones[i].name === jointName) {
  89119. return newSkeleton.bones[i];
  89120. }
  89121. }
  89122. // Not found, search in gltf nodes
  89123. var nodes = gltfRuntime.nodes;
  89124. for (var nde in nodes) {
  89125. var node = nodes[nde];
  89126. if (!node.jointName) {
  89127. continue;
  89128. }
  89129. var children = node.children;
  89130. for (var i = 0; i < children.length; i++) {
  89131. var child = gltfRuntime.nodes[children[i]];
  89132. if (!child.jointName) {
  89133. continue;
  89134. }
  89135. if (child.jointName === jointName) {
  89136. var mat = configureBoneTransformation(node);
  89137. var bone = new BABYLON.Bone(node.name || "", newSkeleton, getParentBone(gltfRuntime, skins, node.jointName, newSkeleton), mat);
  89138. bone.id = nde;
  89139. return bone;
  89140. }
  89141. }
  89142. }
  89143. return null;
  89144. };
  89145. /**
  89146. * Returns the appropriate root node
  89147. */
  89148. var getNodeToRoot = function (nodesToRoot, id) {
  89149. for (var i = 0; i < nodesToRoot.length; i++) {
  89150. var nodeToRoot = nodesToRoot[i];
  89151. for (var j = 0; j < nodeToRoot.node.children.length; j++) {
  89152. var child = nodeToRoot.node.children[j];
  89153. if (child === id) {
  89154. return nodeToRoot.bone;
  89155. }
  89156. }
  89157. }
  89158. return null;
  89159. };
  89160. /**
  89161. * Returns the node with the joint name
  89162. */
  89163. var getJointNode = function (gltfRuntime, jointName) {
  89164. var nodes = gltfRuntime.nodes;
  89165. var node = nodes[jointName];
  89166. if (node) {
  89167. return {
  89168. node: node,
  89169. id: jointName
  89170. };
  89171. }
  89172. for (var nde in nodes) {
  89173. node = nodes[nde];
  89174. if (node.jointName === jointName) {
  89175. return {
  89176. node: node,
  89177. id: nde
  89178. };
  89179. }
  89180. }
  89181. return null;
  89182. };
  89183. /**
  89184. * Checks if a nodes is in joints
  89185. */
  89186. var nodeIsInJoints = function (skins, id) {
  89187. for (var i = 0; i < skins.jointNames.length; i++) {
  89188. if (skins.jointNames[i] === id) {
  89189. return true;
  89190. }
  89191. }
  89192. return false;
  89193. };
  89194. /**
  89195. * Fills the nodes to root for bones and builds hierarchy
  89196. */
  89197. var getNodesToRoot = function (gltfRuntime, newSkeleton, skins, nodesToRoot) {
  89198. // Creates nodes for root
  89199. for (var nde in gltfRuntime.nodes) {
  89200. var node = gltfRuntime.nodes[nde];
  89201. var id = nde;
  89202. if (!node.jointName || nodeIsInJoints(skins, node.jointName)) {
  89203. continue;
  89204. }
  89205. // Create node to root bone
  89206. var mat = configureBoneTransformation(node);
  89207. var bone = new BABYLON.Bone(node.name || "", newSkeleton, null, mat);
  89208. bone.id = id;
  89209. nodesToRoot.push({ bone: bone, node: node, id: id });
  89210. }
  89211. // Parenting
  89212. for (var i = 0; i < nodesToRoot.length; i++) {
  89213. var nodeToRoot = nodesToRoot[i];
  89214. var children = nodeToRoot.node.children;
  89215. for (var j = 0; j < children.length; j++) {
  89216. var child = null;
  89217. for (var k = 0; k < nodesToRoot.length; k++) {
  89218. if (nodesToRoot[k].id === children[j]) {
  89219. child = nodesToRoot[k];
  89220. break;
  89221. }
  89222. }
  89223. if (child) {
  89224. child.bone._parent = nodeToRoot.bone;
  89225. nodeToRoot.bone.children.push(child.bone);
  89226. }
  89227. }
  89228. }
  89229. };
  89230. /**
  89231. * Imports a skeleton
  89232. */
  89233. var importSkeleton = function (gltfRuntime, skins, mesh, newSkeleton, id) {
  89234. if (!newSkeleton) {
  89235. newSkeleton = new BABYLON.Skeleton(skins.name || "", "", gltfRuntime.scene);
  89236. }
  89237. if (!skins.babylonSkeleton) {
  89238. return newSkeleton;
  89239. }
  89240. // Find the root bones
  89241. var nodesToRoot = [];
  89242. var nodesToRootToAdd = [];
  89243. getNodesToRoot(gltfRuntime, newSkeleton, skins, nodesToRoot);
  89244. newSkeleton.bones = [];
  89245. // Joints
  89246. for (var i = 0; i < skins.jointNames.length; i++) {
  89247. var jointNode = getJointNode(gltfRuntime, skins.jointNames[i]);
  89248. if (!jointNode) {
  89249. continue;
  89250. }
  89251. var node = jointNode.node;
  89252. if (!node) {
  89253. BABYLON.Tools.Warn("Joint named " + skins.jointNames[i] + " does not exist");
  89254. continue;
  89255. }
  89256. var id = jointNode.id;
  89257. // Optimize, if the bone already exists...
  89258. var existingBone = gltfRuntime.scene.getBoneByID(id);
  89259. if (existingBone) {
  89260. newSkeleton.bones.push(existingBone);
  89261. continue;
  89262. }
  89263. // Search for parent bone
  89264. var foundBone = false;
  89265. var parentBone = null;
  89266. for (var j = 0; j < i; j++) {
  89267. var jointNode_1 = getJointNode(gltfRuntime, skins.jointNames[j]);
  89268. if (!jointNode_1) {
  89269. continue;
  89270. }
  89271. var joint = jointNode_1.node;
  89272. if (!joint) {
  89273. BABYLON.Tools.Warn("Joint named " + skins.jointNames[j] + " does not exist when looking for parent");
  89274. continue;
  89275. }
  89276. var children = joint.children;
  89277. if (!children) {
  89278. continue;
  89279. }
  89280. foundBone = false;
  89281. for (var k = 0; k < children.length; k++) {
  89282. if (children[k] === id) {
  89283. parentBone = getParentBone(gltfRuntime, skins, skins.jointNames[j], newSkeleton);
  89284. foundBone = true;
  89285. break;
  89286. }
  89287. }
  89288. if (foundBone) {
  89289. break;
  89290. }
  89291. }
  89292. // Create bone
  89293. var mat = configureBoneTransformation(node);
  89294. if (!parentBone && nodesToRoot.length > 0) {
  89295. parentBone = getNodeToRoot(nodesToRoot, id);
  89296. if (parentBone) {
  89297. if (nodesToRootToAdd.indexOf(parentBone) === -1) {
  89298. nodesToRootToAdd.push(parentBone);
  89299. }
  89300. }
  89301. }
  89302. var bone = new BABYLON.Bone(node.jointName || "", newSkeleton, parentBone, mat);
  89303. bone.id = id;
  89304. }
  89305. // Polish
  89306. var bones = newSkeleton.bones;
  89307. newSkeleton.bones = [];
  89308. for (var i = 0; i < skins.jointNames.length; i++) {
  89309. var jointNode = getJointNode(gltfRuntime, skins.jointNames[i]);
  89310. if (!jointNode) {
  89311. continue;
  89312. }
  89313. for (var j = 0; j < bones.length; j++) {
  89314. if (bones[j].id === jointNode.id) {
  89315. newSkeleton.bones.push(bones[j]);
  89316. break;
  89317. }
  89318. }
  89319. }
  89320. newSkeleton.prepare();
  89321. // Finish
  89322. for (var i = 0; i < nodesToRootToAdd.length; i++) {
  89323. newSkeleton.bones.push(nodesToRootToAdd[i]);
  89324. }
  89325. return newSkeleton;
  89326. };
  89327. /**
  89328. * Imports a mesh and its geometries
  89329. */
  89330. var importMesh = function (gltfRuntime, node, meshes, id, newMesh) {
  89331. if (!newMesh) {
  89332. newMesh = new BABYLON.Mesh(node.name || "", gltfRuntime.scene);
  89333. newMesh.id = id;
  89334. }
  89335. if (!node.babylonNode) {
  89336. return newMesh;
  89337. }
  89338. var subMaterials = [];
  89339. var vertexData = null;
  89340. var verticesStarts = new Array();
  89341. var verticesCounts = new Array();
  89342. var indexStarts = new Array();
  89343. var indexCounts = new Array();
  89344. for (var meshIndex = 0; meshIndex < meshes.length; meshIndex++) {
  89345. var meshID = meshes[meshIndex];
  89346. var mesh = gltfRuntime.meshes[meshID];
  89347. if (!mesh) {
  89348. continue;
  89349. }
  89350. // Positions, normals and UVs
  89351. for (var i = 0; i < mesh.primitives.length; i++) {
  89352. // Temporary vertex data
  89353. var tempVertexData = new BABYLON.VertexData();
  89354. var primitive = mesh.primitives[i];
  89355. if (primitive.mode !== 4) {
  89356. // continue;
  89357. }
  89358. var attributes = primitive.attributes;
  89359. var accessor = null;
  89360. var buffer = null;
  89361. // Set positions, normal and uvs
  89362. for (var semantic in attributes) {
  89363. // Link accessor and buffer view
  89364. accessor = gltfRuntime.accessors[attributes[semantic]];
  89365. buffer = GLTF1.GLTFUtils.GetBufferFromAccessor(gltfRuntime, accessor);
  89366. if (semantic === "NORMAL") {
  89367. tempVertexData.normals = new Float32Array(buffer.length);
  89368. tempVertexData.normals.set(buffer);
  89369. }
  89370. else if (semantic === "POSITION") {
  89371. if (BABYLON.GLTFFileLoader.HomogeneousCoordinates) {
  89372. tempVertexData.positions = new Float32Array(buffer.length - buffer.length / 4);
  89373. for (var j = 0; j < buffer.length; j += 4) {
  89374. tempVertexData.positions[j] = buffer[j];
  89375. tempVertexData.positions[j + 1] = buffer[j + 1];
  89376. tempVertexData.positions[j + 2] = buffer[j + 2];
  89377. }
  89378. }
  89379. else {
  89380. tempVertexData.positions = new Float32Array(buffer.length);
  89381. tempVertexData.positions.set(buffer);
  89382. }
  89383. verticesCounts.push(tempVertexData.positions.length);
  89384. }
  89385. else if (semantic.indexOf("TEXCOORD_") !== -1) {
  89386. var channel = Number(semantic.split("_")[1]);
  89387. var uvKind = BABYLON.VertexBuffer.UVKind + (channel === 0 ? "" : (channel + 1));
  89388. var uvs = new Float32Array(buffer.length);
  89389. uvs.set(buffer);
  89390. normalizeUVs(uvs);
  89391. tempVertexData.set(uvs, uvKind);
  89392. }
  89393. else if (semantic === "JOINT") {
  89394. tempVertexData.matricesIndices = new Float32Array(buffer.length);
  89395. tempVertexData.matricesIndices.set(buffer);
  89396. }
  89397. else if (semantic === "WEIGHT") {
  89398. tempVertexData.matricesWeights = new Float32Array(buffer.length);
  89399. tempVertexData.matricesWeights.set(buffer);
  89400. }
  89401. else if (semantic === "COLOR") {
  89402. tempVertexData.colors = new Float32Array(buffer.length);
  89403. tempVertexData.colors.set(buffer);
  89404. }
  89405. }
  89406. // Indices
  89407. accessor = gltfRuntime.accessors[primitive.indices];
  89408. if (accessor) {
  89409. buffer = GLTF1.GLTFUtils.GetBufferFromAccessor(gltfRuntime, accessor);
  89410. tempVertexData.indices = new Int32Array(buffer.length);
  89411. tempVertexData.indices.set(buffer);
  89412. indexCounts.push(tempVertexData.indices.length);
  89413. }
  89414. else {
  89415. // Set indices on the fly
  89416. var indices = [];
  89417. for (var j = 0; j < tempVertexData.positions.length / 3; j++) {
  89418. indices.push(j);
  89419. }
  89420. tempVertexData.indices = new Int32Array(indices);
  89421. indexCounts.push(tempVertexData.indices.length);
  89422. }
  89423. if (!vertexData) {
  89424. vertexData = tempVertexData;
  89425. }
  89426. else {
  89427. vertexData.merge(tempVertexData);
  89428. }
  89429. // Sub material
  89430. var material_1 = gltfRuntime.scene.getMaterialByID(primitive.material);
  89431. subMaterials.push(material_1 === null ? GLTF1.GLTFUtils.GetDefaultMaterial(gltfRuntime.scene) : material_1);
  89432. // Update vertices start and index start
  89433. verticesStarts.push(verticesStarts.length === 0 ? 0 : verticesStarts[verticesStarts.length - 1] + verticesCounts[verticesCounts.length - 2]);
  89434. indexStarts.push(indexStarts.length === 0 ? 0 : indexStarts[indexStarts.length - 1] + indexCounts[indexCounts.length - 2]);
  89435. }
  89436. }
  89437. var material;
  89438. if (subMaterials.length > 1) {
  89439. material = new BABYLON.MultiMaterial("multimat" + id, gltfRuntime.scene);
  89440. material.subMaterials = subMaterials;
  89441. }
  89442. else {
  89443. material = new BABYLON.StandardMaterial("multimat" + id, gltfRuntime.scene);
  89444. }
  89445. if (subMaterials.length === 1) {
  89446. material = subMaterials[0];
  89447. }
  89448. if (!newMesh.material) {
  89449. newMesh.material = material;
  89450. }
  89451. // Apply geometry
  89452. new BABYLON.Geometry(id, gltfRuntime.scene, vertexData, false, newMesh);
  89453. newMesh.computeWorldMatrix(true);
  89454. // Apply submeshes
  89455. newMesh.subMeshes = [];
  89456. var index = 0;
  89457. for (var meshIndex = 0; meshIndex < meshes.length; meshIndex++) {
  89458. var meshID = meshes[meshIndex];
  89459. var mesh = gltfRuntime.meshes[meshID];
  89460. if (!mesh) {
  89461. continue;
  89462. }
  89463. for (var i = 0; i < mesh.primitives.length; i++) {
  89464. if (mesh.primitives[i].mode !== 4) {
  89465. //continue;
  89466. }
  89467. BABYLON.SubMesh.AddToMesh(index, verticesStarts[index], verticesCounts[index], indexStarts[index], indexCounts[index], newMesh, newMesh, true);
  89468. index++;
  89469. }
  89470. }
  89471. // Finish
  89472. return newMesh;
  89473. };
  89474. /**
  89475. * Configure node transformation from position, rotation and scaling
  89476. */
  89477. var configureNode = function (newNode, position, rotation, scaling) {
  89478. if (newNode.position) {
  89479. newNode.position = position;
  89480. }
  89481. if (newNode.rotationQuaternion || newNode.rotation) {
  89482. newNode.rotationQuaternion = rotation;
  89483. }
  89484. if (newNode.scaling) {
  89485. newNode.scaling = scaling;
  89486. }
  89487. };
  89488. /**
  89489. * Configures node from transformation matrix
  89490. */
  89491. var configureNodeFromMatrix = function (newNode, node, parent) {
  89492. if (node.matrix) {
  89493. var position = new BABYLON.Vector3(0, 0, 0);
  89494. var rotation = new BABYLON.Quaternion();
  89495. var scaling = new BABYLON.Vector3(0, 0, 0);
  89496. var mat = BABYLON.Matrix.FromArray(node.matrix);
  89497. mat.decompose(scaling, rotation, position);
  89498. configureNode(newNode, position, rotation, scaling);
  89499. }
  89500. else if (node.translation && node.rotation && node.scale) {
  89501. configureNode(newNode, BABYLON.Vector3.FromArray(node.translation), BABYLON.Quaternion.FromArray(node.rotation), BABYLON.Vector3.FromArray(node.scale));
  89502. }
  89503. newNode.computeWorldMatrix(true);
  89504. };
  89505. /**
  89506. * Imports a node
  89507. */
  89508. var importNode = function (gltfRuntime, node, id, parent) {
  89509. var lastNode = null;
  89510. if (gltfRuntime.importOnlyMeshes && (node.skin || node.meshes)) {
  89511. if (gltfRuntime.importMeshesNames && gltfRuntime.importMeshesNames.length > 0 && gltfRuntime.importMeshesNames.indexOf(node.name || "") === -1) {
  89512. return null;
  89513. }
  89514. }
  89515. // Meshes
  89516. if (node.skin) {
  89517. if (node.meshes) {
  89518. var skin = gltfRuntime.skins[node.skin];
  89519. var newMesh = importMesh(gltfRuntime, node, node.meshes, id, node.babylonNode);
  89520. newMesh.skeleton = gltfRuntime.scene.getLastSkeletonByID(node.skin);
  89521. if (newMesh.skeleton === null) {
  89522. newMesh.skeleton = importSkeleton(gltfRuntime, skin, newMesh, skin.babylonSkeleton, node.skin);
  89523. if (!skin.babylonSkeleton) {
  89524. skin.babylonSkeleton = newMesh.skeleton;
  89525. }
  89526. }
  89527. lastNode = newMesh;
  89528. }
  89529. }
  89530. else if (node.meshes) {
  89531. /**
  89532. * Improve meshes property
  89533. */
  89534. var newMesh = importMesh(gltfRuntime, node, node.mesh ? [node.mesh] : node.meshes, id, node.babylonNode);
  89535. lastNode = newMesh;
  89536. }
  89537. else if (node.light && !node.babylonNode && !gltfRuntime.importOnlyMeshes) {
  89538. var light = gltfRuntime.lights[node.light];
  89539. if (light) {
  89540. if (light.type === "ambient") {
  89541. var ambienLight = light[light.type];
  89542. var hemiLight = new BABYLON.HemisphericLight(node.light, BABYLON.Vector3.Zero(), gltfRuntime.scene);
  89543. hemiLight.name = node.name || "";
  89544. if (ambienLight.color) {
  89545. hemiLight.diffuse = BABYLON.Color3.FromArray(ambienLight.color);
  89546. }
  89547. lastNode = hemiLight;
  89548. }
  89549. else if (light.type === "directional") {
  89550. var directionalLight = light[light.type];
  89551. var dirLight = new BABYLON.DirectionalLight(node.light, BABYLON.Vector3.Zero(), gltfRuntime.scene);
  89552. dirLight.name = node.name || "";
  89553. if (directionalLight.color) {
  89554. dirLight.diffuse = BABYLON.Color3.FromArray(directionalLight.color);
  89555. }
  89556. lastNode = dirLight;
  89557. }
  89558. else if (light.type === "point") {
  89559. var pointLight = light[light.type];
  89560. var ptLight = new BABYLON.PointLight(node.light, BABYLON.Vector3.Zero(), gltfRuntime.scene);
  89561. ptLight.name = node.name || "";
  89562. if (pointLight.color) {
  89563. ptLight.diffuse = BABYLON.Color3.FromArray(pointLight.color);
  89564. }
  89565. lastNode = ptLight;
  89566. }
  89567. else if (light.type === "spot") {
  89568. var spotLight = light[light.type];
  89569. var spLight = new BABYLON.SpotLight(node.light, BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), 0, 0, gltfRuntime.scene);
  89570. spLight.name = node.name || "";
  89571. if (spotLight.color) {
  89572. spLight.diffuse = BABYLON.Color3.FromArray(spotLight.color);
  89573. }
  89574. if (spotLight.fallOfAngle) {
  89575. spLight.angle = spotLight.fallOfAngle;
  89576. }
  89577. if (spotLight.fallOffExponent) {
  89578. spLight.exponent = spotLight.fallOffExponent;
  89579. }
  89580. lastNode = spLight;
  89581. }
  89582. }
  89583. }
  89584. else if (node.camera && !node.babylonNode && !gltfRuntime.importOnlyMeshes) {
  89585. var camera = gltfRuntime.cameras[node.camera];
  89586. if (camera) {
  89587. if (camera.type === "orthographic") {
  89588. var orthoCamera = new BABYLON.FreeCamera(node.camera, BABYLON.Vector3.Zero(), gltfRuntime.scene);
  89589. orthoCamera.name = node.name || "";
  89590. orthoCamera.mode = BABYLON.Camera.ORTHOGRAPHIC_CAMERA;
  89591. orthoCamera.attachControl(gltfRuntime.scene.getEngine().getRenderingCanvas());
  89592. lastNode = orthoCamera;
  89593. }
  89594. else if (camera.type === "perspective") {
  89595. var perspectiveCamera = camera[camera.type];
  89596. var persCamera = new BABYLON.FreeCamera(node.camera, BABYLON.Vector3.Zero(), gltfRuntime.scene);
  89597. persCamera.name = node.name || "";
  89598. persCamera.attachControl(gltfRuntime.scene.getEngine().getRenderingCanvas());
  89599. if (!perspectiveCamera.aspectRatio) {
  89600. perspectiveCamera.aspectRatio = gltfRuntime.scene.getEngine().getRenderWidth() / gltfRuntime.scene.getEngine().getRenderHeight();
  89601. }
  89602. if (perspectiveCamera.znear && perspectiveCamera.zfar) {
  89603. persCamera.maxZ = perspectiveCamera.zfar;
  89604. persCamera.minZ = perspectiveCamera.znear;
  89605. }
  89606. lastNode = persCamera;
  89607. }
  89608. }
  89609. }
  89610. // Empty node
  89611. if (!node.jointName) {
  89612. if (node.babylonNode) {
  89613. return node.babylonNode;
  89614. }
  89615. else if (lastNode === null) {
  89616. var dummy = new BABYLON.Mesh(node.name || "", gltfRuntime.scene);
  89617. node.babylonNode = dummy;
  89618. lastNode = dummy;
  89619. }
  89620. }
  89621. if (lastNode !== null) {
  89622. if (node.matrix && lastNode instanceof BABYLON.Mesh) {
  89623. configureNodeFromMatrix(lastNode, node, parent);
  89624. }
  89625. else {
  89626. var translation = node.translation || [0, 0, 0];
  89627. var rotation = node.rotation || [0, 0, 0, 1];
  89628. var scale = node.scale || [1, 1, 1];
  89629. configureNode(lastNode, BABYLON.Vector3.FromArray(translation), BABYLON.Quaternion.FromArray(rotation), BABYLON.Vector3.FromArray(scale));
  89630. }
  89631. lastNode.updateCache(true);
  89632. node.babylonNode = lastNode;
  89633. }
  89634. return lastNode;
  89635. };
  89636. /**
  89637. * Traverses nodes and creates them
  89638. */
  89639. var traverseNodes = function (gltfRuntime, id, parent, meshIncluded) {
  89640. if (meshIncluded === void 0) { meshIncluded = false; }
  89641. var node = gltfRuntime.nodes[id];
  89642. var newNode = null;
  89643. if (gltfRuntime.importOnlyMeshes && !meshIncluded && gltfRuntime.importMeshesNames) {
  89644. if (gltfRuntime.importMeshesNames.indexOf(node.name || "") !== -1 || gltfRuntime.importMeshesNames.length === 0) {
  89645. meshIncluded = true;
  89646. }
  89647. else {
  89648. meshIncluded = false;
  89649. }
  89650. }
  89651. else {
  89652. meshIncluded = true;
  89653. }
  89654. if (!node.jointName && meshIncluded) {
  89655. newNode = importNode(gltfRuntime, node, id, parent);
  89656. if (newNode !== null) {
  89657. newNode.id = id;
  89658. newNode.parent = parent;
  89659. }
  89660. }
  89661. if (node.children) {
  89662. for (var i = 0; i < node.children.length; i++) {
  89663. traverseNodes(gltfRuntime, node.children[i], newNode, meshIncluded);
  89664. }
  89665. }
  89666. };
  89667. /**
  89668. * do stuff after buffers, shaders are loaded (e.g. hook up materials, load animations, etc.)
  89669. */
  89670. var postLoad = function (gltfRuntime) {
  89671. // Nodes
  89672. var currentScene = gltfRuntime.currentScene;
  89673. if (currentScene) {
  89674. for (var i = 0; i < currentScene.nodes.length; i++) {
  89675. traverseNodes(gltfRuntime, currentScene.nodes[i], null);
  89676. }
  89677. }
  89678. else {
  89679. for (var thing in gltfRuntime.scenes) {
  89680. currentScene = gltfRuntime.scenes[thing];
  89681. for (var i = 0; i < currentScene.nodes.length; i++) {
  89682. traverseNodes(gltfRuntime, currentScene.nodes[i], null);
  89683. }
  89684. }
  89685. }
  89686. // Set animations
  89687. loadAnimations(gltfRuntime);
  89688. for (var i = 0; i < gltfRuntime.scene.skeletons.length; i++) {
  89689. var skeleton = gltfRuntime.scene.skeletons[i];
  89690. gltfRuntime.scene.beginAnimation(skeleton, 0, Number.MAX_VALUE, true, 1.0);
  89691. }
  89692. };
  89693. /**
  89694. * onBind shaderrs callback to set uniforms and matrices
  89695. */
  89696. var onBindShaderMaterial = function (mesh, gltfRuntime, unTreatedUniforms, shaderMaterial, technique, material, onSuccess) {
  89697. var materialValues = material.values || technique.parameters;
  89698. for (var unif in unTreatedUniforms) {
  89699. var uniform = unTreatedUniforms[unif];
  89700. var type = uniform.type;
  89701. if (type === GLTF1.EParameterType.FLOAT_MAT2 || type === GLTF1.EParameterType.FLOAT_MAT3 || type === GLTF1.EParameterType.FLOAT_MAT4) {
  89702. if (uniform.semantic && !uniform.source && !uniform.node) {
  89703. GLTF1.GLTFUtils.SetMatrix(gltfRuntime.scene, mesh, uniform, unif, shaderMaterial.getEffect());
  89704. }
  89705. else if (uniform.semantic && (uniform.source || uniform.node)) {
  89706. var source = gltfRuntime.scene.getNodeByName(uniform.source || uniform.node || "");
  89707. if (source === null) {
  89708. source = gltfRuntime.scene.getNodeByID(uniform.source || uniform.node || "");
  89709. }
  89710. if (source === null) {
  89711. continue;
  89712. }
  89713. GLTF1.GLTFUtils.SetMatrix(gltfRuntime.scene, source, uniform, unif, shaderMaterial.getEffect());
  89714. }
  89715. }
  89716. else {
  89717. var value = materialValues[technique.uniforms[unif]];
  89718. if (!value) {
  89719. continue;
  89720. }
  89721. if (type === GLTF1.EParameterType.SAMPLER_2D) {
  89722. var texture = gltfRuntime.textures[material.values ? value : uniform.value].babylonTexture;
  89723. if (texture === null || texture === undefined) {
  89724. continue;
  89725. }
  89726. shaderMaterial.getEffect().setTexture(unif, texture);
  89727. }
  89728. else {
  89729. GLTF1.GLTFUtils.SetUniform((shaderMaterial.getEffect()), unif, value, type);
  89730. }
  89731. }
  89732. }
  89733. onSuccess(shaderMaterial);
  89734. };
  89735. /**
  89736. * Prepare uniforms to send the only one time
  89737. * Loads the appropriate textures
  89738. */
  89739. var prepareShaderMaterialUniforms = function (gltfRuntime, shaderMaterial, technique, material, unTreatedUniforms) {
  89740. var materialValues = material.values || technique.parameters;
  89741. var techniqueUniforms = technique.uniforms;
  89742. /**
  89743. * Prepare values here (not matrices)
  89744. */
  89745. for (var unif in unTreatedUniforms) {
  89746. var uniform = unTreatedUniforms[unif];
  89747. var type = uniform.type;
  89748. var value = materialValues[techniqueUniforms[unif]];
  89749. if (value === undefined) {
  89750. // In case the value is the same for all materials
  89751. value = uniform.value;
  89752. }
  89753. if (!value) {
  89754. continue;
  89755. }
  89756. var onLoadTexture = function (uniformName) {
  89757. return function (texture) {
  89758. if (uniform.value && uniformName) {
  89759. // Static uniform
  89760. shaderMaterial.setTexture(uniformName, texture);
  89761. delete unTreatedUniforms[uniformName];
  89762. }
  89763. };
  89764. };
  89765. // Texture (sampler2D)
  89766. if (type === GLTF1.EParameterType.SAMPLER_2D) {
  89767. GLTF1.GLTFLoaderExtension.LoadTextureAsync(gltfRuntime, material.values ? value : uniform.value, onLoadTexture(unif), function () { return onLoadTexture(null); });
  89768. }
  89769. else {
  89770. if (uniform.value && GLTF1.GLTFUtils.SetUniform(shaderMaterial, unif, material.values ? value : uniform.value, type)) {
  89771. // Static uniform
  89772. delete unTreatedUniforms[unif];
  89773. }
  89774. }
  89775. }
  89776. };
  89777. /**
  89778. * Shader compilation failed
  89779. */
  89780. var onShaderCompileError = function (program, shaderMaterial, onError) {
  89781. return function (effect, error) {
  89782. shaderMaterial.dispose(true);
  89783. onError("Cannot compile program named " + program.name + ". Error: " + error + ". Default material will be applied");
  89784. };
  89785. };
  89786. /**
  89787. * Shader compilation success
  89788. */
  89789. var onShaderCompileSuccess = function (gltfRuntime, shaderMaterial, technique, material, unTreatedUniforms, onSuccess) {
  89790. return function (_) {
  89791. prepareShaderMaterialUniforms(gltfRuntime, shaderMaterial, technique, material, unTreatedUniforms);
  89792. shaderMaterial.onBind = function (mesh) {
  89793. onBindShaderMaterial(mesh, gltfRuntime, unTreatedUniforms, shaderMaterial, technique, material, onSuccess);
  89794. };
  89795. };
  89796. };
  89797. /**
  89798. * Returns the appropriate uniform if already handled by babylon
  89799. */
  89800. var parseShaderUniforms = function (tokenizer, technique, unTreatedUniforms) {
  89801. for (var unif in technique.uniforms) {
  89802. var uniform = technique.uniforms[unif];
  89803. var uniformParameter = technique.parameters[uniform];
  89804. if (tokenizer.currentIdentifier === unif) {
  89805. if (uniformParameter.semantic && !uniformParameter.source && !uniformParameter.node) {
  89806. var transformIndex = glTFTransforms.indexOf(uniformParameter.semantic);
  89807. if (transformIndex !== -1) {
  89808. delete unTreatedUniforms[unif];
  89809. return babylonTransforms[transformIndex];
  89810. }
  89811. }
  89812. }
  89813. }
  89814. return tokenizer.currentIdentifier;
  89815. };
  89816. /**
  89817. * All shaders loaded. Create materials one by one
  89818. */
  89819. var importMaterials = function (gltfRuntime) {
  89820. // Create materials
  89821. for (var mat in gltfRuntime.materials) {
  89822. GLTF1.GLTFLoaderExtension.LoadMaterialAsync(gltfRuntime, mat, function (material) { }, function () { });
  89823. }
  89824. };
  89825. /**
  89826. * Implementation of the base glTF spec
  89827. */
  89828. var GLTFLoaderBase = /** @class */ (function () {
  89829. function GLTFLoaderBase() {
  89830. }
  89831. GLTFLoaderBase.CreateRuntime = function (parsedData, scene, rootUrl) {
  89832. var gltfRuntime = {
  89833. extensions: {},
  89834. accessors: {},
  89835. buffers: {},
  89836. bufferViews: {},
  89837. meshes: {},
  89838. lights: {},
  89839. cameras: {},
  89840. nodes: {},
  89841. images: {},
  89842. textures: {},
  89843. shaders: {},
  89844. programs: {},
  89845. samplers: {},
  89846. techniques: {},
  89847. materials: {},
  89848. animations: {},
  89849. skins: {},
  89850. extensionsUsed: [],
  89851. scenes: {},
  89852. buffersCount: 0,
  89853. shaderscount: 0,
  89854. scene: scene,
  89855. rootUrl: rootUrl,
  89856. loadedBufferCount: 0,
  89857. loadedBufferViews: {},
  89858. loadedShaderCount: 0,
  89859. importOnlyMeshes: false,
  89860. dummyNodes: []
  89861. };
  89862. // Parse
  89863. if (parsedData.extensions) {
  89864. parseObject(parsedData.extensions, "extensions", gltfRuntime);
  89865. }
  89866. if (parsedData.extensionsUsed) {
  89867. parseObject(parsedData.extensionsUsed, "extensionsUsed", gltfRuntime);
  89868. }
  89869. if (parsedData.buffers) {
  89870. parseBuffers(parsedData.buffers, gltfRuntime);
  89871. }
  89872. if (parsedData.bufferViews) {
  89873. parseObject(parsedData.bufferViews, "bufferViews", gltfRuntime);
  89874. }
  89875. if (parsedData.accessors) {
  89876. parseObject(parsedData.accessors, "accessors", gltfRuntime);
  89877. }
  89878. if (parsedData.meshes) {
  89879. parseObject(parsedData.meshes, "meshes", gltfRuntime);
  89880. }
  89881. if (parsedData.lights) {
  89882. parseObject(parsedData.lights, "lights", gltfRuntime);
  89883. }
  89884. if (parsedData.cameras) {
  89885. parseObject(parsedData.cameras, "cameras", gltfRuntime);
  89886. }
  89887. if (parsedData.nodes) {
  89888. parseObject(parsedData.nodes, "nodes", gltfRuntime);
  89889. }
  89890. if (parsedData.images) {
  89891. parseObject(parsedData.images, "images", gltfRuntime);
  89892. }
  89893. if (parsedData.textures) {
  89894. parseObject(parsedData.textures, "textures", gltfRuntime);
  89895. }
  89896. if (parsedData.shaders) {
  89897. parseShaders(parsedData.shaders, gltfRuntime);
  89898. }
  89899. if (parsedData.programs) {
  89900. parseObject(parsedData.programs, "programs", gltfRuntime);
  89901. }
  89902. if (parsedData.samplers) {
  89903. parseObject(parsedData.samplers, "samplers", gltfRuntime);
  89904. }
  89905. if (parsedData.techniques) {
  89906. parseObject(parsedData.techniques, "techniques", gltfRuntime);
  89907. }
  89908. if (parsedData.materials) {
  89909. parseObject(parsedData.materials, "materials", gltfRuntime);
  89910. }
  89911. if (parsedData.animations) {
  89912. parseObject(parsedData.animations, "animations", gltfRuntime);
  89913. }
  89914. if (parsedData.skins) {
  89915. parseObject(parsedData.skins, "skins", gltfRuntime);
  89916. }
  89917. if (parsedData.scenes) {
  89918. gltfRuntime.scenes = parsedData.scenes;
  89919. }
  89920. if (parsedData.scene && parsedData.scenes) {
  89921. gltfRuntime.currentScene = parsedData.scenes[parsedData.scene];
  89922. }
  89923. return gltfRuntime;
  89924. };
  89925. GLTFLoaderBase.LoadBufferAsync = function (gltfRuntime, id, onSuccess, onError, onProgress) {
  89926. var buffer = gltfRuntime.buffers[id];
  89927. if (BABYLON.Tools.IsBase64(buffer.uri)) {
  89928. setTimeout(function () { return onSuccess(new Uint8Array(BABYLON.Tools.DecodeBase64(buffer.uri))); });
  89929. }
  89930. else {
  89931. BABYLON.Tools.LoadFile(gltfRuntime.rootUrl + buffer.uri, function (data) { return onSuccess(new Uint8Array(data)); }, onProgress, undefined, true, function (request) {
  89932. if (request) {
  89933. onError(request.status + " " + request.statusText);
  89934. }
  89935. });
  89936. }
  89937. };
  89938. GLTFLoaderBase.LoadTextureBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  89939. var texture = gltfRuntime.textures[id];
  89940. if (!texture || !texture.source) {
  89941. onError("");
  89942. return;
  89943. }
  89944. if (texture.babylonTexture) {
  89945. onSuccess(null);
  89946. return;
  89947. }
  89948. var source = gltfRuntime.images[texture.source];
  89949. if (BABYLON.Tools.IsBase64(source.uri)) {
  89950. setTimeout(function () { return onSuccess(new Uint8Array(BABYLON.Tools.DecodeBase64(source.uri))); });
  89951. }
  89952. else {
  89953. BABYLON.Tools.LoadFile(gltfRuntime.rootUrl + source.uri, function (data) { return onSuccess(new Uint8Array(data)); }, undefined, undefined, true, function (request) {
  89954. if (request) {
  89955. onError(request.status + " " + request.statusText);
  89956. }
  89957. });
  89958. }
  89959. };
  89960. GLTFLoaderBase.CreateTextureAsync = function (gltfRuntime, id, buffer, onSuccess, onError) {
  89961. var texture = gltfRuntime.textures[id];
  89962. if (texture.babylonTexture) {
  89963. onSuccess(texture.babylonTexture);
  89964. return;
  89965. }
  89966. var sampler = gltfRuntime.samplers[texture.sampler];
  89967. var createMipMaps = (sampler.minFilter === GLTF1.ETextureFilterType.NEAREST_MIPMAP_NEAREST) ||
  89968. (sampler.minFilter === GLTF1.ETextureFilterType.NEAREST_MIPMAP_LINEAR) ||
  89969. (sampler.minFilter === GLTF1.ETextureFilterType.LINEAR_MIPMAP_NEAREST) ||
  89970. (sampler.minFilter === GLTF1.ETextureFilterType.LINEAR_MIPMAP_LINEAR);
  89971. var samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE;
  89972. var blob = new Blob([buffer]);
  89973. var blobURL = URL.createObjectURL(blob);
  89974. var revokeBlobURL = function () { return URL.revokeObjectURL(blobURL); };
  89975. var newTexture = new BABYLON.Texture(blobURL, gltfRuntime.scene, !createMipMaps, true, samplingMode, revokeBlobURL, revokeBlobURL);
  89976. if (sampler.wrapS !== undefined) {
  89977. newTexture.wrapU = GLTF1.GLTFUtils.GetWrapMode(sampler.wrapS);
  89978. }
  89979. if (sampler.wrapT !== undefined) {
  89980. newTexture.wrapV = GLTF1.GLTFUtils.GetWrapMode(sampler.wrapT);
  89981. }
  89982. newTexture.name = id;
  89983. texture.babylonTexture = newTexture;
  89984. onSuccess(newTexture);
  89985. };
  89986. GLTFLoaderBase.LoadShaderStringAsync = function (gltfRuntime, id, onSuccess, onError) {
  89987. var shader = gltfRuntime.shaders[id];
  89988. if (BABYLON.Tools.IsBase64(shader.uri)) {
  89989. var shaderString = atob(shader.uri.split(",")[1]);
  89990. onSuccess(shaderString);
  89991. }
  89992. else {
  89993. BABYLON.Tools.LoadFile(gltfRuntime.rootUrl + shader.uri, onSuccess, undefined, undefined, false, function (request) {
  89994. if (request) {
  89995. onError(request.status + " " + request.statusText);
  89996. }
  89997. });
  89998. }
  89999. };
  90000. GLTFLoaderBase.LoadMaterialAsync = function (gltfRuntime, id, onSuccess, onError) {
  90001. var material = gltfRuntime.materials[id];
  90002. if (!material.technique) {
  90003. if (onError) {
  90004. onError("No technique found.");
  90005. }
  90006. return;
  90007. }
  90008. var technique = gltfRuntime.techniques[material.technique];
  90009. if (!technique) {
  90010. var defaultMaterial = new BABYLON.StandardMaterial(id, gltfRuntime.scene);
  90011. defaultMaterial.diffuseColor = new BABYLON.Color3(0.5, 0.5, 0.5);
  90012. defaultMaterial.sideOrientation = BABYLON.Material.CounterClockWiseSideOrientation;
  90013. onSuccess(defaultMaterial);
  90014. return;
  90015. }
  90016. var program = gltfRuntime.programs[technique.program];
  90017. var states = technique.states;
  90018. var vertexShader = BABYLON.Effect.ShadersStore[program.vertexShader + "VertexShader"];
  90019. var pixelShader = BABYLON.Effect.ShadersStore[program.fragmentShader + "PixelShader"];
  90020. var newVertexShader = "";
  90021. var newPixelShader = "";
  90022. var vertexTokenizer = new Tokenizer(vertexShader);
  90023. var pixelTokenizer = new Tokenizer(pixelShader);
  90024. var unTreatedUniforms = {};
  90025. var uniforms = [];
  90026. var attributes = [];
  90027. var samplers = [];
  90028. // Fill uniform, sampler2D and attributes
  90029. for (var unif in technique.uniforms) {
  90030. var uniform = technique.uniforms[unif];
  90031. var uniformParameter = technique.parameters[uniform];
  90032. unTreatedUniforms[unif] = uniformParameter;
  90033. if (uniformParameter.semantic && !uniformParameter.node && !uniformParameter.source) {
  90034. var transformIndex = glTFTransforms.indexOf(uniformParameter.semantic);
  90035. if (transformIndex !== -1) {
  90036. uniforms.push(babylonTransforms[transformIndex]);
  90037. delete unTreatedUniforms[unif];
  90038. }
  90039. else {
  90040. uniforms.push(unif);
  90041. }
  90042. }
  90043. else if (uniformParameter.type === GLTF1.EParameterType.SAMPLER_2D) {
  90044. samplers.push(unif);
  90045. }
  90046. else {
  90047. uniforms.push(unif);
  90048. }
  90049. }
  90050. for (var attr in technique.attributes) {
  90051. var attribute = technique.attributes[attr];
  90052. var attributeParameter = technique.parameters[attribute];
  90053. if (attributeParameter.semantic) {
  90054. attributes.push(getAttribute(attributeParameter));
  90055. }
  90056. }
  90057. // Configure vertex shader
  90058. while (!vertexTokenizer.isEnd() && vertexTokenizer.getNextToken()) {
  90059. var tokenType = vertexTokenizer.currentToken;
  90060. if (tokenType !== ETokenType.IDENTIFIER) {
  90061. newVertexShader += vertexTokenizer.currentString;
  90062. continue;
  90063. }
  90064. var foundAttribute = false;
  90065. for (var attr in technique.attributes) {
  90066. var attribute = technique.attributes[attr];
  90067. var attributeParameter = technique.parameters[attribute];
  90068. if (vertexTokenizer.currentIdentifier === attr && attributeParameter.semantic) {
  90069. newVertexShader += getAttribute(attributeParameter);
  90070. foundAttribute = true;
  90071. break;
  90072. }
  90073. }
  90074. if (foundAttribute) {
  90075. continue;
  90076. }
  90077. newVertexShader += parseShaderUniforms(vertexTokenizer, technique, unTreatedUniforms);
  90078. }
  90079. // Configure pixel shader
  90080. while (!pixelTokenizer.isEnd() && pixelTokenizer.getNextToken()) {
  90081. var tokenType = pixelTokenizer.currentToken;
  90082. if (tokenType !== ETokenType.IDENTIFIER) {
  90083. newPixelShader += pixelTokenizer.currentString;
  90084. continue;
  90085. }
  90086. newPixelShader += parseShaderUniforms(pixelTokenizer, technique, unTreatedUniforms);
  90087. }
  90088. // Create shader material
  90089. var shaderPath = {
  90090. vertex: program.vertexShader + id,
  90091. fragment: program.fragmentShader + id
  90092. };
  90093. var options = {
  90094. attributes: attributes,
  90095. uniforms: uniforms,
  90096. samplers: samplers,
  90097. needAlphaBlending: states && states.enable && states.enable.indexOf(3042) !== -1
  90098. };
  90099. BABYLON.Effect.ShadersStore[program.vertexShader + id + "VertexShader"] = newVertexShader;
  90100. BABYLON.Effect.ShadersStore[program.fragmentShader + id + "PixelShader"] = newPixelShader;
  90101. var shaderMaterial = new BABYLON.ShaderMaterial(id, gltfRuntime.scene, shaderPath, options);
  90102. shaderMaterial.onError = onShaderCompileError(program, shaderMaterial, onError);
  90103. shaderMaterial.onCompiled = onShaderCompileSuccess(gltfRuntime, shaderMaterial, technique, material, unTreatedUniforms, onSuccess);
  90104. shaderMaterial.sideOrientation = BABYLON.Material.CounterClockWiseSideOrientation;
  90105. if (states && states.functions) {
  90106. var functions = states.functions;
  90107. if (functions.cullFace && functions.cullFace[0] !== GLTF1.ECullingType.BACK) {
  90108. shaderMaterial.backFaceCulling = false;
  90109. }
  90110. var blendFunc = functions.blendFuncSeparate;
  90111. if (blendFunc) {
  90112. 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) {
  90113. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_COMBINE;
  90114. }
  90115. else if (blendFunc[0] === GLTF1.EBlendingFunction.ONE && blendFunc[1] === GLTF1.EBlendingFunction.ONE && blendFunc[2] === GLTF1.EBlendingFunction.ZERO && blendFunc[3] === GLTF1.EBlendingFunction.ONE) {
  90116. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_ONEONE;
  90117. }
  90118. else if (blendFunc[0] === GLTF1.EBlendingFunction.SRC_ALPHA && blendFunc[1] === GLTF1.EBlendingFunction.ONE && blendFunc[2] === GLTF1.EBlendingFunction.ZERO && blendFunc[3] === GLTF1.EBlendingFunction.ONE) {
  90119. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_ADD;
  90120. }
  90121. 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) {
  90122. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_SUBTRACT;
  90123. }
  90124. else if (blendFunc[0] === GLTF1.EBlendingFunction.DST_COLOR && blendFunc[1] === GLTF1.EBlendingFunction.ZERO && blendFunc[2] === GLTF1.EBlendingFunction.ONE && blendFunc[3] === GLTF1.EBlendingFunction.ONE) {
  90125. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_MULTIPLY;
  90126. }
  90127. 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) {
  90128. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_MAXIMIZED;
  90129. }
  90130. }
  90131. }
  90132. };
  90133. return GLTFLoaderBase;
  90134. }());
  90135. GLTF1.GLTFLoaderBase = GLTFLoaderBase;
  90136. /**
  90137. * glTF V1 Loader
  90138. */
  90139. var GLTFLoader = /** @class */ (function () {
  90140. function GLTFLoader() {
  90141. // #region Stubs for IGLTFLoader interface
  90142. this.coordinateSystemMode = BABYLON.GLTFLoaderCoordinateSystemMode.AUTO;
  90143. this.animationStartMode = BABYLON.GLTFLoaderAnimationStartMode.FIRST;
  90144. this.compileMaterials = false;
  90145. this.useClipPlane = false;
  90146. this.compileShadowGenerators = false;
  90147. this.onDisposeObservable = new BABYLON.Observable();
  90148. this.onMeshLoadedObservable = new BABYLON.Observable();
  90149. this.onTextureLoadedObservable = new BABYLON.Observable();
  90150. this.onMaterialLoadedObservable = new BABYLON.Observable();
  90151. this.onCompleteObservable = new BABYLON.Observable();
  90152. this.onExtensionLoadedObservable = new BABYLON.Observable();
  90153. this.state = null;
  90154. }
  90155. GLTFLoader.RegisterExtension = function (extension) {
  90156. if (GLTFLoader.Extensions[extension.name]) {
  90157. BABYLON.Tools.Error("Tool with the same name \"" + extension.name + "\" already exists");
  90158. return;
  90159. }
  90160. GLTFLoader.Extensions[extension.name] = extension;
  90161. };
  90162. GLTFLoader.prototype.dispose = function () { };
  90163. // #endregion
  90164. GLTFLoader.prototype._importMeshAsync = function (meshesNames, scene, data, rootUrl, onSuccess, onProgress, onError) {
  90165. var _this = this;
  90166. scene.useRightHandedSystem = true;
  90167. GLTF1.GLTFLoaderExtension.LoadRuntimeAsync(scene, data, rootUrl, function (gltfRuntime) {
  90168. gltfRuntime.importOnlyMeshes = true;
  90169. if (meshesNames === "") {
  90170. gltfRuntime.importMeshesNames = [];
  90171. }
  90172. else if (typeof meshesNames === "string") {
  90173. gltfRuntime.importMeshesNames = [meshesNames];
  90174. }
  90175. else if (meshesNames && !(meshesNames instanceof Array)) {
  90176. gltfRuntime.importMeshesNames = [meshesNames];
  90177. }
  90178. else {
  90179. gltfRuntime.importMeshesNames = [];
  90180. BABYLON.Tools.Warn("Argument meshesNames must be of type string or string[]");
  90181. }
  90182. // Create nodes
  90183. _this._createNodes(gltfRuntime);
  90184. var meshes = new Array();
  90185. var skeletons = new Array();
  90186. // Fill arrays of meshes and skeletons
  90187. for (var nde in gltfRuntime.nodes) {
  90188. var node = gltfRuntime.nodes[nde];
  90189. if (node.babylonNode instanceof BABYLON.AbstractMesh) {
  90190. meshes.push(node.babylonNode);
  90191. }
  90192. }
  90193. for (var skl in gltfRuntime.skins) {
  90194. var skin = gltfRuntime.skins[skl];
  90195. if (skin.babylonSkeleton instanceof BABYLON.Skeleton) {
  90196. skeletons.push(skin.babylonSkeleton);
  90197. }
  90198. }
  90199. // Load buffers, shaders, materials, etc.
  90200. _this._loadBuffersAsync(gltfRuntime, function () {
  90201. _this._loadShadersAsync(gltfRuntime, function () {
  90202. importMaterials(gltfRuntime);
  90203. postLoad(gltfRuntime);
  90204. if (!BABYLON.GLTFFileLoader.IncrementalLoading && onSuccess) {
  90205. onSuccess(meshes, [], skeletons);
  90206. }
  90207. });
  90208. }, onProgress);
  90209. if (BABYLON.GLTFFileLoader.IncrementalLoading && onSuccess) {
  90210. onSuccess(meshes, [], skeletons);
  90211. }
  90212. }, onError);
  90213. return true;
  90214. };
  90215. GLTFLoader.prototype.importMeshAsync = function (meshesNames, scene, data, rootUrl, onProgress) {
  90216. var _this = this;
  90217. return new Promise(function (resolve, reject) {
  90218. _this._importMeshAsync(meshesNames, scene, data, rootUrl, function (meshes, particleSystems, skeletons) {
  90219. resolve({
  90220. meshes: meshes,
  90221. particleSystems: particleSystems,
  90222. skeletons: skeletons
  90223. });
  90224. }, onProgress, function (message) {
  90225. reject(new Error(message));
  90226. });
  90227. });
  90228. };
  90229. GLTFLoader.prototype._loadAsync = function (scene, data, rootUrl, onSuccess, onProgress, onError) {
  90230. var _this = this;
  90231. scene.useRightHandedSystem = true;
  90232. GLTF1.GLTFLoaderExtension.LoadRuntimeAsync(scene, data, rootUrl, function (gltfRuntime) {
  90233. // Load runtime extensios
  90234. GLTF1.GLTFLoaderExtension.LoadRuntimeExtensionsAsync(gltfRuntime, function () {
  90235. // Create nodes
  90236. _this._createNodes(gltfRuntime);
  90237. // Load buffers, shaders, materials, etc.
  90238. _this._loadBuffersAsync(gltfRuntime, function () {
  90239. _this._loadShadersAsync(gltfRuntime, function () {
  90240. importMaterials(gltfRuntime);
  90241. postLoad(gltfRuntime);
  90242. if (!BABYLON.GLTFFileLoader.IncrementalLoading) {
  90243. onSuccess();
  90244. }
  90245. });
  90246. });
  90247. if (BABYLON.GLTFFileLoader.IncrementalLoading) {
  90248. onSuccess();
  90249. }
  90250. }, onError);
  90251. }, onError);
  90252. };
  90253. GLTFLoader.prototype.loadAsync = function (scene, data, rootUrl, onProgress) {
  90254. var _this = this;
  90255. return new Promise(function (resolve, reject) {
  90256. _this._loadAsync(scene, data, rootUrl, function () {
  90257. resolve();
  90258. }, onProgress, function (message) {
  90259. reject(new Error(message));
  90260. });
  90261. });
  90262. };
  90263. GLTFLoader.prototype._loadShadersAsync = function (gltfRuntime, onload) {
  90264. var hasShaders = false;
  90265. var processShader = function (sha, shader) {
  90266. GLTF1.GLTFLoaderExtension.LoadShaderStringAsync(gltfRuntime, sha, function (shaderString) {
  90267. gltfRuntime.loadedShaderCount++;
  90268. if (shaderString) {
  90269. BABYLON.Effect.ShadersStore[sha + (shader.type === GLTF1.EShaderType.VERTEX ? "VertexShader" : "PixelShader")] = shaderString;
  90270. }
  90271. if (gltfRuntime.loadedShaderCount === gltfRuntime.shaderscount) {
  90272. onload();
  90273. }
  90274. }, function () {
  90275. BABYLON.Tools.Error("Error when loading shader program named " + sha + " located at " + shader.uri);
  90276. });
  90277. };
  90278. for (var sha in gltfRuntime.shaders) {
  90279. hasShaders = true;
  90280. var shader = gltfRuntime.shaders[sha];
  90281. if (shader) {
  90282. processShader.bind(this, sha, shader)();
  90283. }
  90284. else {
  90285. BABYLON.Tools.Error("No shader named: " + sha);
  90286. }
  90287. }
  90288. if (!hasShaders) {
  90289. onload();
  90290. }
  90291. };
  90292. ;
  90293. GLTFLoader.prototype._loadBuffersAsync = function (gltfRuntime, onLoad, onProgress) {
  90294. var hasBuffers = false;
  90295. var processBuffer = function (buf, buffer) {
  90296. GLTF1.GLTFLoaderExtension.LoadBufferAsync(gltfRuntime, buf, function (bufferView) {
  90297. gltfRuntime.loadedBufferCount++;
  90298. if (bufferView) {
  90299. if (bufferView.byteLength != gltfRuntime.buffers[buf].byteLength) {
  90300. BABYLON.Tools.Error("Buffer named " + buf + " is length " + bufferView.byteLength + ". Expected: " + buffer.byteLength); // Improve error message
  90301. }
  90302. gltfRuntime.loadedBufferViews[buf] = bufferView;
  90303. }
  90304. if (gltfRuntime.loadedBufferCount === gltfRuntime.buffersCount) {
  90305. onLoad();
  90306. }
  90307. }, function () {
  90308. BABYLON.Tools.Error("Error when loading buffer named " + buf + " located at " + buffer.uri);
  90309. });
  90310. };
  90311. for (var buf in gltfRuntime.buffers) {
  90312. hasBuffers = true;
  90313. var buffer = gltfRuntime.buffers[buf];
  90314. if (buffer) {
  90315. processBuffer.bind(this, buf, buffer)();
  90316. }
  90317. else {
  90318. BABYLON.Tools.Error("No buffer named: " + buf);
  90319. }
  90320. }
  90321. if (!hasBuffers) {
  90322. onLoad();
  90323. }
  90324. };
  90325. GLTFLoader.prototype._createNodes = function (gltfRuntime) {
  90326. var currentScene = gltfRuntime.currentScene;
  90327. if (currentScene) {
  90328. // Only one scene even if multiple scenes are defined
  90329. for (var i = 0; i < currentScene.nodes.length; i++) {
  90330. traverseNodes(gltfRuntime, currentScene.nodes[i], null);
  90331. }
  90332. }
  90333. else {
  90334. // Load all scenes
  90335. for (var thing in gltfRuntime.scenes) {
  90336. currentScene = gltfRuntime.scenes[thing];
  90337. for (var i = 0; i < currentScene.nodes.length; i++) {
  90338. traverseNodes(gltfRuntime, currentScene.nodes[i], null);
  90339. }
  90340. }
  90341. }
  90342. };
  90343. GLTFLoader.Extensions = {};
  90344. return GLTFLoader;
  90345. }());
  90346. GLTF1.GLTFLoader = GLTFLoader;
  90347. ;
  90348. BABYLON.GLTFFileLoader.CreateGLTFLoaderV1 = function () { return new GLTFLoader(); };
  90349. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  90350. })(BABYLON || (BABYLON = {}));
  90351. //# sourceMappingURL=babylon.glTFLoader.js.map
  90352. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  90353. var BABYLON;
  90354. (function (BABYLON) {
  90355. var GLTF1;
  90356. (function (GLTF1) {
  90357. /**
  90358. * Utils functions for GLTF
  90359. */
  90360. var GLTFUtils = /** @class */ (function () {
  90361. function GLTFUtils() {
  90362. }
  90363. /**
  90364. * Sets the given "parameter" matrix
  90365. * @param scene: the {BABYLON.Scene} object
  90366. * @param source: the source node where to pick the matrix
  90367. * @param parameter: the GLTF technique parameter
  90368. * @param uniformName: the name of the shader's uniform
  90369. * @param shaderMaterial: the shader material
  90370. */
  90371. GLTFUtils.SetMatrix = function (scene, source, parameter, uniformName, shaderMaterial) {
  90372. var mat = null;
  90373. if (parameter.semantic === "MODEL") {
  90374. mat = source.getWorldMatrix();
  90375. }
  90376. else if (parameter.semantic === "PROJECTION") {
  90377. mat = scene.getProjectionMatrix();
  90378. }
  90379. else if (parameter.semantic === "VIEW") {
  90380. mat = scene.getViewMatrix();
  90381. }
  90382. else if (parameter.semantic === "MODELVIEWINVERSETRANSPOSE") {
  90383. mat = BABYLON.Matrix.Transpose(source.getWorldMatrix().multiply(scene.getViewMatrix()).invert());
  90384. }
  90385. else if (parameter.semantic === "MODELVIEW") {
  90386. mat = source.getWorldMatrix().multiply(scene.getViewMatrix());
  90387. }
  90388. else if (parameter.semantic === "MODELVIEWPROJECTION") {
  90389. mat = source.getWorldMatrix().multiply(scene.getTransformMatrix());
  90390. }
  90391. else if (parameter.semantic === "MODELINVERSE") {
  90392. mat = source.getWorldMatrix().invert();
  90393. }
  90394. else if (parameter.semantic === "VIEWINVERSE") {
  90395. mat = scene.getViewMatrix().invert();
  90396. }
  90397. else if (parameter.semantic === "PROJECTIONINVERSE") {
  90398. mat = scene.getProjectionMatrix().invert();
  90399. }
  90400. else if (parameter.semantic === "MODELVIEWINVERSE") {
  90401. mat = source.getWorldMatrix().multiply(scene.getViewMatrix()).invert();
  90402. }
  90403. else if (parameter.semantic === "MODELVIEWPROJECTIONINVERSE") {
  90404. mat = source.getWorldMatrix().multiply(scene.getTransformMatrix()).invert();
  90405. }
  90406. else if (parameter.semantic === "MODELINVERSETRANSPOSE") {
  90407. mat = BABYLON.Matrix.Transpose(source.getWorldMatrix().invert());
  90408. }
  90409. else {
  90410. debugger;
  90411. }
  90412. if (mat) {
  90413. switch (parameter.type) {
  90414. case GLTF1.EParameterType.FLOAT_MAT2:
  90415. shaderMaterial.setMatrix2x2(uniformName, BABYLON.Matrix.GetAsMatrix2x2(mat));
  90416. break;
  90417. case GLTF1.EParameterType.FLOAT_MAT3:
  90418. shaderMaterial.setMatrix3x3(uniformName, BABYLON.Matrix.GetAsMatrix3x3(mat));
  90419. break;
  90420. case GLTF1.EParameterType.FLOAT_MAT4:
  90421. shaderMaterial.setMatrix(uniformName, mat);
  90422. break;
  90423. default: break;
  90424. }
  90425. }
  90426. };
  90427. /**
  90428. * Sets the given "parameter" matrix
  90429. * @param shaderMaterial: the shader material
  90430. * @param uniform: the name of the shader's uniform
  90431. * @param value: the value of the uniform
  90432. * @param type: the uniform's type (EParameterType FLOAT, VEC2, VEC3 or VEC4)
  90433. */
  90434. GLTFUtils.SetUniform = function (shaderMaterial, uniform, value, type) {
  90435. switch (type) {
  90436. case GLTF1.EParameterType.FLOAT:
  90437. shaderMaterial.setFloat(uniform, value);
  90438. return true;
  90439. case GLTF1.EParameterType.FLOAT_VEC2:
  90440. shaderMaterial.setVector2(uniform, BABYLON.Vector2.FromArray(value));
  90441. return true;
  90442. case GLTF1.EParameterType.FLOAT_VEC3:
  90443. shaderMaterial.setVector3(uniform, BABYLON.Vector3.FromArray(value));
  90444. return true;
  90445. case GLTF1.EParameterType.FLOAT_VEC4:
  90446. shaderMaterial.setVector4(uniform, BABYLON.Vector4.FromArray(value));
  90447. return true;
  90448. default: return false;
  90449. }
  90450. };
  90451. /**
  90452. * Returns the wrap mode of the texture
  90453. * @param mode: the mode value
  90454. */
  90455. GLTFUtils.GetWrapMode = function (mode) {
  90456. switch (mode) {
  90457. case GLTF1.ETextureWrapMode.CLAMP_TO_EDGE: return BABYLON.Texture.CLAMP_ADDRESSMODE;
  90458. case GLTF1.ETextureWrapMode.MIRRORED_REPEAT: return BABYLON.Texture.MIRROR_ADDRESSMODE;
  90459. case GLTF1.ETextureWrapMode.REPEAT: return BABYLON.Texture.WRAP_ADDRESSMODE;
  90460. default: return BABYLON.Texture.WRAP_ADDRESSMODE;
  90461. }
  90462. };
  90463. /**
  90464. * Returns the byte stride giving an accessor
  90465. * @param accessor: the GLTF accessor objet
  90466. */
  90467. GLTFUtils.GetByteStrideFromType = function (accessor) {
  90468. // Needs this function since "byteStride" isn't requiered in glTF format
  90469. var type = accessor.type;
  90470. switch (type) {
  90471. case "VEC2": return 2;
  90472. case "VEC3": return 3;
  90473. case "VEC4": return 4;
  90474. case "MAT2": return 4;
  90475. case "MAT3": return 9;
  90476. case "MAT4": return 16;
  90477. default: return 1;
  90478. }
  90479. };
  90480. /**
  90481. * Returns the texture filter mode giving a mode value
  90482. * @param mode: the filter mode value
  90483. */
  90484. GLTFUtils.GetTextureFilterMode = function (mode) {
  90485. switch (mode) {
  90486. case GLTF1.ETextureFilterType.LINEAR:
  90487. case GLTF1.ETextureFilterType.LINEAR_MIPMAP_NEAREST:
  90488. case GLTF1.ETextureFilterType.LINEAR_MIPMAP_LINEAR: return BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  90489. case GLTF1.ETextureFilterType.NEAREST:
  90490. case GLTF1.ETextureFilterType.NEAREST_MIPMAP_NEAREST: return BABYLON.Texture.NEAREST_SAMPLINGMODE;
  90491. default: return BABYLON.Texture.BILINEAR_SAMPLINGMODE;
  90492. }
  90493. };
  90494. GLTFUtils.GetBufferFromBufferView = function (gltfRuntime, bufferView, byteOffset, byteLength, componentType) {
  90495. var byteOffset = bufferView.byteOffset + byteOffset;
  90496. var loadedBufferView = gltfRuntime.loadedBufferViews[bufferView.buffer];
  90497. if (byteOffset + byteLength > loadedBufferView.byteLength) {
  90498. throw new Error("Buffer access is out of range");
  90499. }
  90500. var buffer = loadedBufferView.buffer;
  90501. byteOffset += loadedBufferView.byteOffset;
  90502. switch (componentType) {
  90503. case GLTF1.EComponentType.BYTE: return new Int8Array(buffer, byteOffset, byteLength);
  90504. case GLTF1.EComponentType.UNSIGNED_BYTE: return new Uint8Array(buffer, byteOffset, byteLength);
  90505. case GLTF1.EComponentType.SHORT: return new Int16Array(buffer, byteOffset, byteLength);
  90506. case GLTF1.EComponentType.UNSIGNED_SHORT: return new Uint16Array(buffer, byteOffset, byteLength);
  90507. default: return new Float32Array(buffer, byteOffset, byteLength);
  90508. }
  90509. };
  90510. /**
  90511. * Returns a buffer from its accessor
  90512. * @param gltfRuntime: the GLTF runtime
  90513. * @param accessor: the GLTF accessor
  90514. */
  90515. GLTFUtils.GetBufferFromAccessor = function (gltfRuntime, accessor) {
  90516. var bufferView = gltfRuntime.bufferViews[accessor.bufferView];
  90517. var byteLength = accessor.count * GLTFUtils.GetByteStrideFromType(accessor);
  90518. return GLTFUtils.GetBufferFromBufferView(gltfRuntime, bufferView, accessor.byteOffset, byteLength, accessor.componentType);
  90519. };
  90520. /**
  90521. * Decodes a buffer view into a string
  90522. * @param view: the buffer view
  90523. */
  90524. GLTFUtils.DecodeBufferToText = function (view) {
  90525. var result = "";
  90526. var length = view.byteLength;
  90527. for (var i = 0; i < length; ++i) {
  90528. result += String.fromCharCode(view[i]);
  90529. }
  90530. return result;
  90531. };
  90532. /**
  90533. * Returns the default material of gltf. Related to
  90534. * https://github.com/KhronosGroup/glTF/tree/master/specification/1.0#appendix-a-default-material
  90535. * @param scene: the Babylon.js scene
  90536. */
  90537. GLTFUtils.GetDefaultMaterial = function (scene) {
  90538. if (!GLTFUtils._DefaultMaterial) {
  90539. BABYLON.Effect.ShadersStore["GLTFDefaultMaterialVertexShader"] = [
  90540. "precision highp float;",
  90541. "",
  90542. "uniform mat4 worldView;",
  90543. "uniform mat4 projection;",
  90544. "",
  90545. "attribute vec3 position;",
  90546. "",
  90547. "void main(void)",
  90548. "{",
  90549. " gl_Position = projection * worldView * vec4(position, 1.0);",
  90550. "}"
  90551. ].join("\n");
  90552. BABYLON.Effect.ShadersStore["GLTFDefaultMaterialPixelShader"] = [
  90553. "precision highp float;",
  90554. "",
  90555. "uniform vec4 u_emission;",
  90556. "",
  90557. "void main(void)",
  90558. "{",
  90559. " gl_FragColor = u_emission;",
  90560. "}"
  90561. ].join("\n");
  90562. var shaderPath = {
  90563. vertex: "GLTFDefaultMaterial",
  90564. fragment: "GLTFDefaultMaterial"
  90565. };
  90566. var options = {
  90567. attributes: ["position"],
  90568. uniforms: ["worldView", "projection", "u_emission"],
  90569. samplers: new Array(),
  90570. needAlphaBlending: false
  90571. };
  90572. GLTFUtils._DefaultMaterial = new BABYLON.ShaderMaterial("GLTFDefaultMaterial", scene, shaderPath, options);
  90573. GLTFUtils._DefaultMaterial.setColor4("u_emission", new BABYLON.Color4(0.5, 0.5, 0.5, 1.0));
  90574. }
  90575. return GLTFUtils._DefaultMaterial;
  90576. };
  90577. // The GLTF default material
  90578. GLTFUtils._DefaultMaterial = null;
  90579. return GLTFUtils;
  90580. }());
  90581. GLTF1.GLTFUtils = GLTFUtils;
  90582. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  90583. })(BABYLON || (BABYLON = {}));
  90584. //# sourceMappingURL=babylon.glTFLoaderUtils.js.map
  90585. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  90586. var BABYLON;
  90587. (function (BABYLON) {
  90588. var GLTF1;
  90589. (function (GLTF1) {
  90590. var GLTFLoaderExtension = /** @class */ (function () {
  90591. function GLTFLoaderExtension(name) {
  90592. this._name = name;
  90593. }
  90594. Object.defineProperty(GLTFLoaderExtension.prototype, "name", {
  90595. get: function () {
  90596. return this._name;
  90597. },
  90598. enumerable: true,
  90599. configurable: true
  90600. });
  90601. /**
  90602. * Defines an override for loading the runtime
  90603. * Return true to stop further extensions from loading the runtime
  90604. */
  90605. GLTFLoaderExtension.prototype.loadRuntimeAsync = function (scene, data, rootUrl, onSuccess, onError) {
  90606. return false;
  90607. };
  90608. /**
  90609. * Defines an onverride for creating gltf runtime
  90610. * Return true to stop further extensions from creating the runtime
  90611. */
  90612. GLTFLoaderExtension.prototype.loadRuntimeExtensionsAsync = function (gltfRuntime, onSuccess, onError) {
  90613. return false;
  90614. };
  90615. /**
  90616. * Defines an override for loading buffers
  90617. * Return true to stop further extensions from loading this buffer
  90618. */
  90619. GLTFLoaderExtension.prototype.loadBufferAsync = function (gltfRuntime, id, onSuccess, onError, onProgress) {
  90620. return false;
  90621. };
  90622. /**
  90623. * Defines an override for loading texture buffers
  90624. * Return true to stop further extensions from loading this texture data
  90625. */
  90626. GLTFLoaderExtension.prototype.loadTextureBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  90627. return false;
  90628. };
  90629. /**
  90630. * Defines an override for creating textures
  90631. * Return true to stop further extensions from loading this texture
  90632. */
  90633. GLTFLoaderExtension.prototype.createTextureAsync = function (gltfRuntime, id, buffer, onSuccess, onError) {
  90634. return false;
  90635. };
  90636. /**
  90637. * Defines an override for loading shader strings
  90638. * Return true to stop further extensions from loading this shader data
  90639. */
  90640. GLTFLoaderExtension.prototype.loadShaderStringAsync = function (gltfRuntime, id, onSuccess, onError) {
  90641. return false;
  90642. };
  90643. /**
  90644. * Defines an override for loading materials
  90645. * Return true to stop further extensions from loading this material
  90646. */
  90647. GLTFLoaderExtension.prototype.loadMaterialAsync = function (gltfRuntime, id, onSuccess, onError) {
  90648. return false;
  90649. };
  90650. // ---------
  90651. // Utilities
  90652. // ---------
  90653. GLTFLoaderExtension.LoadRuntimeAsync = function (scene, data, rootUrl, onSuccess, onError) {
  90654. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  90655. return loaderExtension.loadRuntimeAsync(scene, data, rootUrl, onSuccess, onError);
  90656. }, function () {
  90657. setTimeout(function () {
  90658. onSuccess(GLTF1.GLTFLoaderBase.CreateRuntime(data.json, scene, rootUrl));
  90659. });
  90660. });
  90661. };
  90662. GLTFLoaderExtension.LoadRuntimeExtensionsAsync = function (gltfRuntime, onSuccess, onError) {
  90663. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  90664. return loaderExtension.loadRuntimeExtensionsAsync(gltfRuntime, onSuccess, onError);
  90665. }, function () {
  90666. setTimeout(function () {
  90667. onSuccess();
  90668. });
  90669. });
  90670. };
  90671. GLTFLoaderExtension.LoadBufferAsync = function (gltfRuntime, id, onSuccess, onError, onProgress) {
  90672. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  90673. return loaderExtension.loadBufferAsync(gltfRuntime, id, onSuccess, onError, onProgress);
  90674. }, function () {
  90675. GLTF1.GLTFLoaderBase.LoadBufferAsync(gltfRuntime, id, onSuccess, onError, onProgress);
  90676. });
  90677. };
  90678. GLTFLoaderExtension.LoadTextureAsync = function (gltfRuntime, id, onSuccess, onError) {
  90679. GLTFLoaderExtension.LoadTextureBufferAsync(gltfRuntime, id, function (buffer) { return GLTFLoaderExtension.CreateTextureAsync(gltfRuntime, id, buffer, onSuccess, onError); }, onError);
  90680. };
  90681. GLTFLoaderExtension.LoadShaderStringAsync = function (gltfRuntime, id, onSuccess, onError) {
  90682. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  90683. return loaderExtension.loadShaderStringAsync(gltfRuntime, id, onSuccess, onError);
  90684. }, function () {
  90685. GLTF1.GLTFLoaderBase.LoadShaderStringAsync(gltfRuntime, id, onSuccess, onError);
  90686. });
  90687. };
  90688. GLTFLoaderExtension.LoadMaterialAsync = function (gltfRuntime, id, onSuccess, onError) {
  90689. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  90690. return loaderExtension.loadMaterialAsync(gltfRuntime, id, onSuccess, onError);
  90691. }, function () {
  90692. GLTF1.GLTFLoaderBase.LoadMaterialAsync(gltfRuntime, id, onSuccess, onError);
  90693. });
  90694. };
  90695. GLTFLoaderExtension.LoadTextureBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  90696. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  90697. return loaderExtension.loadTextureBufferAsync(gltfRuntime, id, onSuccess, onError);
  90698. }, function () {
  90699. GLTF1.GLTFLoaderBase.LoadTextureBufferAsync(gltfRuntime, id, onSuccess, onError);
  90700. });
  90701. };
  90702. GLTFLoaderExtension.CreateTextureAsync = function (gltfRuntime, id, buffer, onSuccess, onError) {
  90703. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  90704. return loaderExtension.createTextureAsync(gltfRuntime, id, buffer, onSuccess, onError);
  90705. }, function () {
  90706. GLTF1.GLTFLoaderBase.CreateTextureAsync(gltfRuntime, id, buffer, onSuccess, onError);
  90707. });
  90708. };
  90709. GLTFLoaderExtension.ApplyExtensions = function (func, defaultFunc) {
  90710. for (var extensionName in GLTF1.GLTFLoader.Extensions) {
  90711. var loaderExtension = GLTF1.GLTFLoader.Extensions[extensionName];
  90712. if (func(loaderExtension)) {
  90713. return;
  90714. }
  90715. }
  90716. defaultFunc();
  90717. };
  90718. return GLTFLoaderExtension;
  90719. }());
  90720. GLTF1.GLTFLoaderExtension = GLTFLoaderExtension;
  90721. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  90722. })(BABYLON || (BABYLON = {}));
  90723. //# sourceMappingURL=babylon.glTFLoaderExtension.js.map
  90724. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  90725. var BABYLON;
  90726. (function (BABYLON) {
  90727. var GLTF1;
  90728. (function (GLTF1) {
  90729. var BinaryExtensionBufferName = "binary_glTF";
  90730. ;
  90731. ;
  90732. var GLTFBinaryExtension = /** @class */ (function (_super) {
  90733. __extends(GLTFBinaryExtension, _super);
  90734. function GLTFBinaryExtension() {
  90735. return _super.call(this, "KHR_binary_glTF") || this;
  90736. }
  90737. GLTFBinaryExtension.prototype.loadRuntimeAsync = function (scene, data, rootUrl, onSuccess, onError) {
  90738. var extensionsUsed = data.json.extensionsUsed;
  90739. if (!extensionsUsed || extensionsUsed.indexOf(this.name) === -1 || !data.bin) {
  90740. return false;
  90741. }
  90742. this._bin = data.bin;
  90743. onSuccess(GLTF1.GLTFLoaderBase.CreateRuntime(data.json, scene, rootUrl));
  90744. return true;
  90745. };
  90746. GLTFBinaryExtension.prototype.loadBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  90747. if (gltfRuntime.extensionsUsed.indexOf(this.name) === -1) {
  90748. return false;
  90749. }
  90750. if (id !== BinaryExtensionBufferName) {
  90751. return false;
  90752. }
  90753. onSuccess(this._bin);
  90754. return true;
  90755. };
  90756. GLTFBinaryExtension.prototype.loadTextureBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  90757. var texture = gltfRuntime.textures[id];
  90758. var source = gltfRuntime.images[texture.source];
  90759. if (!source.extensions || !(this.name in source.extensions)) {
  90760. return false;
  90761. }
  90762. var sourceExt = source.extensions[this.name];
  90763. var bufferView = gltfRuntime.bufferViews[sourceExt.bufferView];
  90764. var buffer = GLTF1.GLTFUtils.GetBufferFromBufferView(gltfRuntime, bufferView, 0, bufferView.byteLength, GLTF1.EComponentType.UNSIGNED_BYTE);
  90765. onSuccess(buffer);
  90766. return true;
  90767. };
  90768. GLTFBinaryExtension.prototype.loadShaderStringAsync = function (gltfRuntime, id, onSuccess, onError) {
  90769. var shader = gltfRuntime.shaders[id];
  90770. if (!shader.extensions || !(this.name in shader.extensions)) {
  90771. return false;
  90772. }
  90773. var binaryExtensionShader = shader.extensions[this.name];
  90774. var bufferView = gltfRuntime.bufferViews[binaryExtensionShader.bufferView];
  90775. var shaderBytes = GLTF1.GLTFUtils.GetBufferFromBufferView(gltfRuntime, bufferView, 0, bufferView.byteLength, GLTF1.EComponentType.UNSIGNED_BYTE);
  90776. setTimeout(function () {
  90777. var shaderString = GLTF1.GLTFUtils.DecodeBufferToText(shaderBytes);
  90778. onSuccess(shaderString);
  90779. });
  90780. return true;
  90781. };
  90782. return GLTFBinaryExtension;
  90783. }(GLTF1.GLTFLoaderExtension));
  90784. GLTF1.GLTFBinaryExtension = GLTFBinaryExtension;
  90785. GLTF1.GLTFLoader.RegisterExtension(new GLTFBinaryExtension());
  90786. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  90787. })(BABYLON || (BABYLON = {}));
  90788. //# sourceMappingURL=babylon.glTFBinaryExtension.js.map
  90789. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  90790. var BABYLON;
  90791. (function (BABYLON) {
  90792. var GLTF1;
  90793. (function (GLTF1) {
  90794. ;
  90795. ;
  90796. ;
  90797. var GLTFMaterialsCommonExtension = /** @class */ (function (_super) {
  90798. __extends(GLTFMaterialsCommonExtension, _super);
  90799. function GLTFMaterialsCommonExtension() {
  90800. return _super.call(this, "KHR_materials_common") || this;
  90801. }
  90802. GLTFMaterialsCommonExtension.prototype.loadRuntimeExtensionsAsync = function (gltfRuntime, onSuccess, onError) {
  90803. if (!gltfRuntime.extensions)
  90804. return false;
  90805. var extension = gltfRuntime.extensions[this.name];
  90806. if (!extension)
  90807. return false;
  90808. // Create lights
  90809. var lights = extension.lights;
  90810. if (lights) {
  90811. for (var thing in lights) {
  90812. var light = lights[thing];
  90813. switch (light.type) {
  90814. case "ambient":
  90815. var ambientLight = new BABYLON.HemisphericLight(light.name, new BABYLON.Vector3(0, 1, 0), gltfRuntime.scene);
  90816. var ambient = light.ambient;
  90817. if (ambient) {
  90818. ambientLight.diffuse = BABYLON.Color3.FromArray(ambient.color || [1, 1, 1]);
  90819. }
  90820. break;
  90821. case "point":
  90822. var pointLight = new BABYLON.PointLight(light.name, new BABYLON.Vector3(10, 10, 10), gltfRuntime.scene);
  90823. var point = light.point;
  90824. if (point) {
  90825. pointLight.diffuse = BABYLON.Color3.FromArray(point.color || [1, 1, 1]);
  90826. }
  90827. break;
  90828. case "directional":
  90829. var dirLight = new BABYLON.DirectionalLight(light.name, new BABYLON.Vector3(0, -1, 0), gltfRuntime.scene);
  90830. var directional = light.directional;
  90831. if (directional) {
  90832. dirLight.diffuse = BABYLON.Color3.FromArray(directional.color || [1, 1, 1]);
  90833. }
  90834. break;
  90835. case "spot":
  90836. var spot = light.spot;
  90837. if (spot) {
  90838. 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);
  90839. spotLight.diffuse = BABYLON.Color3.FromArray(spot.color || [1, 1, 1]);
  90840. }
  90841. break;
  90842. default:
  90843. BABYLON.Tools.Warn("GLTF Material Common extension: light type \"" + light.type + "\” not supported");
  90844. break;
  90845. }
  90846. }
  90847. }
  90848. return false;
  90849. };
  90850. GLTFMaterialsCommonExtension.prototype.loadMaterialAsync = function (gltfRuntime, id, onSuccess, onError) {
  90851. var material = gltfRuntime.materials[id];
  90852. if (!material || !material.extensions)
  90853. return false;
  90854. var extension = material.extensions[this.name];
  90855. if (!extension)
  90856. return false;
  90857. var standardMaterial = new BABYLON.StandardMaterial(id, gltfRuntime.scene);
  90858. standardMaterial.sideOrientation = BABYLON.Material.CounterClockWiseSideOrientation;
  90859. if (extension.technique === "CONSTANT") {
  90860. standardMaterial.disableLighting = true;
  90861. }
  90862. standardMaterial.backFaceCulling = extension.doubleSided === undefined ? false : !extension.doubleSided;
  90863. standardMaterial.alpha = extension.values.transparency === undefined ? 1.0 : extension.values.transparency;
  90864. standardMaterial.specularPower = extension.values.shininess === undefined ? 0.0 : extension.values.shininess;
  90865. // Ambient
  90866. if (typeof extension.values.ambient === "string") {
  90867. this._loadTexture(gltfRuntime, extension.values.ambient, standardMaterial, "ambientTexture", onError);
  90868. }
  90869. else {
  90870. standardMaterial.ambientColor = BABYLON.Color3.FromArray(extension.values.ambient || [0, 0, 0]);
  90871. }
  90872. // Diffuse
  90873. if (typeof extension.values.diffuse === "string") {
  90874. this._loadTexture(gltfRuntime, extension.values.diffuse, standardMaterial, "diffuseTexture", onError);
  90875. }
  90876. else {
  90877. standardMaterial.diffuseColor = BABYLON.Color3.FromArray(extension.values.diffuse || [0, 0, 0]);
  90878. }
  90879. // Emission
  90880. if (typeof extension.values.emission === "string") {
  90881. this._loadTexture(gltfRuntime, extension.values.emission, standardMaterial, "emissiveTexture", onError);
  90882. }
  90883. else {
  90884. standardMaterial.emissiveColor = BABYLON.Color3.FromArray(extension.values.emission || [0, 0, 0]);
  90885. }
  90886. // Specular
  90887. if (typeof extension.values.specular === "string") {
  90888. this._loadTexture(gltfRuntime, extension.values.specular, standardMaterial, "specularTexture", onError);
  90889. }
  90890. else {
  90891. standardMaterial.specularColor = BABYLON.Color3.FromArray(extension.values.specular || [0, 0, 0]);
  90892. }
  90893. return true;
  90894. };
  90895. GLTFMaterialsCommonExtension.prototype._loadTexture = function (gltfRuntime, id, material, propertyPath, onError) {
  90896. // Create buffer from texture url
  90897. GLTF1.GLTFLoaderBase.LoadTextureBufferAsync(gltfRuntime, id, function (buffer) {
  90898. // Create texture from buffer
  90899. GLTF1.GLTFLoaderBase.CreateTextureAsync(gltfRuntime, id, buffer, function (texture) { return material[propertyPath] = texture; }, onError);
  90900. }, onError);
  90901. };
  90902. return GLTFMaterialsCommonExtension;
  90903. }(GLTF1.GLTFLoaderExtension));
  90904. GLTF1.GLTFMaterialsCommonExtension = GLTFMaterialsCommonExtension;
  90905. GLTF1.GLTFLoader.RegisterExtension(new GLTFMaterialsCommonExtension());
  90906. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  90907. })(BABYLON || (BABYLON = {}));
  90908. //# sourceMappingURL=babylon.glTFMaterialsCommonExtension.js.map
  90909. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  90910. var BABYLON;
  90911. (function (BABYLON) {
  90912. var GLTF2;
  90913. (function (GLTF2) {
  90914. var ArrayItem = /** @class */ (function () {
  90915. function ArrayItem() {
  90916. }
  90917. ArrayItem.Assign = function (values) {
  90918. if (values) {
  90919. for (var index = 0; index < values.length; index++) {
  90920. values[index]._index = index;
  90921. }
  90922. }
  90923. };
  90924. return ArrayItem;
  90925. }());
  90926. GLTF2.ArrayItem = ArrayItem;
  90927. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  90928. })(BABYLON || (BABYLON = {}));
  90929. //# sourceMappingURL=babylon.glTFLoaderUtilities.js.map
  90930. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  90931. /// <reference path="../../../../dist/babylon.glTF2Interface.d.ts"/>
  90932. //# sourceMappingURL=babylon.glTFLoaderInterfaces.js.map
  90933. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  90934. var BABYLON;
  90935. (function (BABYLON) {
  90936. var GLTF2;
  90937. (function (GLTF2) {
  90938. var GLTFLoader = /** @class */ (function () {
  90939. function GLTFLoader() {
  90940. this._completePromises = new Array();
  90941. this._disposed = false;
  90942. this._state = null;
  90943. this._extensions = {};
  90944. this._defaultSampler = {};
  90945. this._requests = new Array();
  90946. this.coordinateSystemMode = BABYLON.GLTFLoaderCoordinateSystemMode.AUTO;
  90947. this.animationStartMode = BABYLON.GLTFLoaderAnimationStartMode.FIRST;
  90948. this.compileMaterials = false;
  90949. this.useClipPlane = false;
  90950. this.compileShadowGenerators = false;
  90951. this.onDisposeObservable = new BABYLON.Observable();
  90952. this.onMeshLoadedObservable = new BABYLON.Observable();
  90953. this.onTextureLoadedObservable = new BABYLON.Observable();
  90954. this.onMaterialLoadedObservable = new BABYLON.Observable();
  90955. this.onExtensionLoadedObservable = new BABYLON.Observable();
  90956. this.onCompleteObservable = new BABYLON.Observable();
  90957. }
  90958. GLTFLoader._Register = function (name, factory) {
  90959. if (GLTFLoader._Factories[name]) {
  90960. BABYLON.Tools.Error("Extension with the name '" + name + "' already exists");
  90961. return;
  90962. }
  90963. GLTFLoader._Factories[name] = factory;
  90964. // Keep the order of registration so that extensions registered first are called first.
  90965. GLTFLoader._Names.push(name);
  90966. };
  90967. Object.defineProperty(GLTFLoader.prototype, "state", {
  90968. get: function () {
  90969. return this._state;
  90970. },
  90971. enumerable: true,
  90972. configurable: true
  90973. });
  90974. GLTFLoader.prototype.dispose = function () {
  90975. if (this._disposed) {
  90976. return;
  90977. }
  90978. this._disposed = true;
  90979. this.onDisposeObservable.notifyObservers(this);
  90980. this.onDisposeObservable.clear();
  90981. this._clear();
  90982. };
  90983. GLTFLoader.prototype.importMeshAsync = function (meshesNames, scene, data, rootUrl, onProgress) {
  90984. var _this = this;
  90985. return Promise.resolve().then(function () {
  90986. var nodes = null;
  90987. if (meshesNames) {
  90988. var nodeMap_1 = {};
  90989. if (_this._gltf.nodes) {
  90990. for (var _i = 0, _a = _this._gltf.nodes; _i < _a.length; _i++) {
  90991. var node = _a[_i];
  90992. if (node.name) {
  90993. nodeMap_1[node.name] = node;
  90994. }
  90995. }
  90996. }
  90997. var names = (meshesNames instanceof Array) ? meshesNames : [meshesNames];
  90998. nodes = names.map(function (name) {
  90999. var node = nodeMap_1[name];
  91000. if (!node) {
  91001. throw new Error("Failed to find node " + name);
  91002. }
  91003. return node;
  91004. });
  91005. }
  91006. return _this._loadAsync(nodes, scene, data, rootUrl, onProgress).then(function () {
  91007. return {
  91008. meshes: _this._getMeshes(),
  91009. particleSystems: [],
  91010. skeletons: _this._getSkeletons(),
  91011. };
  91012. });
  91013. });
  91014. };
  91015. GLTFLoader.prototype.loadAsync = function (scene, data, rootUrl, onProgress) {
  91016. return this._loadAsync(null, scene, data, rootUrl, onProgress);
  91017. };
  91018. GLTFLoader.prototype._loadAsync = function (nodes, scene, data, rootUrl, onProgress) {
  91019. var _this = this;
  91020. return Promise.resolve().then(function () {
  91021. _this._loadExtensions();
  91022. _this._babylonScene = scene;
  91023. _this._rootUrl = rootUrl;
  91024. _this._progressCallback = onProgress;
  91025. _this._state = BABYLON.GLTFLoaderState.Loading;
  91026. _this._loadData(data);
  91027. var promises = new Array();
  91028. if (nodes) {
  91029. promises.push(_this._loadNodesAsync(nodes));
  91030. }
  91031. else {
  91032. var scene_1 = GLTFLoader._GetProperty("#/scene", _this._gltf.scenes, _this._gltf.scene || 0);
  91033. promises.push(_this._loadSceneAsync("#/scenes/" + scene_1._index, scene_1));
  91034. }
  91035. if (_this.compileMaterials) {
  91036. promises.push(_this._compileMaterialsAsync());
  91037. }
  91038. if (_this.compileShadowGenerators) {
  91039. promises.push(_this._compileShadowGeneratorsAsync());
  91040. }
  91041. return Promise.all(promises).then(function () {
  91042. _this._state = BABYLON.GLTFLoaderState.Ready;
  91043. _this._startAnimations();
  91044. BABYLON.Tools.SetImmediate(function () {
  91045. if (!_this._disposed) {
  91046. Promise.all(_this._completePromises).then(function () {
  91047. _this._state = BABYLON.GLTFLoaderState.Complete;
  91048. _this.onCompleteObservable.notifyObservers(_this);
  91049. _this.onCompleteObservable.clear();
  91050. _this._clear();
  91051. }).catch(function (error) {
  91052. BABYLON.Tools.Error("glTF Loader: " + error.message);
  91053. _this._clear();
  91054. });
  91055. }
  91056. });
  91057. });
  91058. }).catch(function (error) {
  91059. BABYLON.Tools.Error("glTF Loader: " + error.message);
  91060. _this._clear();
  91061. throw error;
  91062. });
  91063. };
  91064. GLTFLoader.prototype._loadExtensions = function () {
  91065. for (var _i = 0, _a = GLTFLoader._Names; _i < _a.length; _i++) {
  91066. var name_1 = _a[_i];
  91067. var extension = GLTFLoader._Factories[name_1](this);
  91068. this._extensions[name_1] = extension;
  91069. this.onExtensionLoadedObservable.notifyObservers(extension);
  91070. }
  91071. this.onExtensionLoadedObservable.clear();
  91072. };
  91073. GLTFLoader.prototype._loadData = function (data) {
  91074. this._gltf = data.json;
  91075. this._setupData();
  91076. if (data.bin) {
  91077. var buffers = this._gltf.buffers;
  91078. if (buffers && buffers[0] && !buffers[0].uri) {
  91079. var binaryBuffer = buffers[0];
  91080. if (binaryBuffer.byteLength < data.bin.byteLength - 3 || binaryBuffer.byteLength > data.bin.byteLength) {
  91081. BABYLON.Tools.Warn("Binary buffer length (" + binaryBuffer.byteLength + ") from JSON does not match chunk length (" + data.bin.byteLength + ")");
  91082. }
  91083. binaryBuffer._data = Promise.resolve(data.bin);
  91084. }
  91085. else {
  91086. BABYLON.Tools.Warn("Unexpected BIN chunk");
  91087. }
  91088. }
  91089. };
  91090. GLTFLoader.prototype._setupData = function () {
  91091. GLTF2.ArrayItem.Assign(this._gltf.accessors);
  91092. GLTF2.ArrayItem.Assign(this._gltf.animations);
  91093. GLTF2.ArrayItem.Assign(this._gltf.buffers);
  91094. GLTF2.ArrayItem.Assign(this._gltf.bufferViews);
  91095. GLTF2.ArrayItem.Assign(this._gltf.cameras);
  91096. GLTF2.ArrayItem.Assign(this._gltf.images);
  91097. GLTF2.ArrayItem.Assign(this._gltf.materials);
  91098. GLTF2.ArrayItem.Assign(this._gltf.meshes);
  91099. GLTF2.ArrayItem.Assign(this._gltf.nodes);
  91100. GLTF2.ArrayItem.Assign(this._gltf.samplers);
  91101. GLTF2.ArrayItem.Assign(this._gltf.scenes);
  91102. GLTF2.ArrayItem.Assign(this._gltf.skins);
  91103. GLTF2.ArrayItem.Assign(this._gltf.textures);
  91104. if (this._gltf.nodes) {
  91105. var nodeParents = {};
  91106. for (var _i = 0, _a = this._gltf.nodes; _i < _a.length; _i++) {
  91107. var node = _a[_i];
  91108. if (node.children) {
  91109. for (var _b = 0, _c = node.children; _b < _c.length; _b++) {
  91110. var index = _c[_b];
  91111. nodeParents[index] = node._index;
  91112. }
  91113. }
  91114. }
  91115. var rootNode = this._createRootNode();
  91116. for (var _d = 0, _e = this._gltf.nodes; _d < _e.length; _d++) {
  91117. var node = _e[_d];
  91118. var parentIndex = nodeParents[node._index];
  91119. node._parent = parentIndex === undefined ? rootNode : this._gltf.nodes[parentIndex];
  91120. }
  91121. }
  91122. };
  91123. GLTFLoader.prototype._createRootNode = function () {
  91124. this._rootBabylonMesh = new BABYLON.Mesh("__root__", this._babylonScene);
  91125. var rootNode = { _babylonMesh: this._rootBabylonMesh };
  91126. switch (this.coordinateSystemMode) {
  91127. case BABYLON.GLTFLoaderCoordinateSystemMode.AUTO: {
  91128. if (!this._babylonScene.useRightHandedSystem) {
  91129. rootNode.rotation = [0, 1, 0, 0];
  91130. rootNode.scale = [1, 1, -1];
  91131. GLTFLoader._LoadTransform(rootNode, this._rootBabylonMesh);
  91132. }
  91133. break;
  91134. }
  91135. case BABYLON.GLTFLoaderCoordinateSystemMode.FORCE_RIGHT_HANDED: {
  91136. this._babylonScene.useRightHandedSystem = true;
  91137. break;
  91138. }
  91139. default: {
  91140. throw new Error("Invalid coordinate system mode " + this.coordinateSystemMode);
  91141. }
  91142. }
  91143. this.onMeshLoadedObservable.notifyObservers(this._rootBabylonMesh);
  91144. return rootNode;
  91145. };
  91146. GLTFLoader.prototype._loadNodesAsync = function (nodes) {
  91147. var promises = new Array();
  91148. for (var _i = 0, nodes_1 = nodes; _i < nodes_1.length; _i++) {
  91149. var node = nodes_1[_i];
  91150. promises.push(this._loadNodeAsync("#/nodes/" + node._index, node));
  91151. }
  91152. promises.push(this._loadAnimationsAsync());
  91153. return Promise.all(promises).then(function () { });
  91154. };
  91155. GLTFLoader.prototype._loadSceneAsync = function (context, scene) {
  91156. var promise = GLTF2.GLTFLoaderExtension._LoadSceneAsync(this, context, scene);
  91157. if (promise) {
  91158. return promise;
  91159. }
  91160. var promises = new Array();
  91161. for (var _i = 0, _a = scene.nodes; _i < _a.length; _i++) {
  91162. var index = _a[_i];
  91163. var node = GLTFLoader._GetProperty(context + "/nodes/" + index, this._gltf.nodes, index);
  91164. promises.push(this._loadNodeAsync("#/nodes/" + node._index, node));
  91165. }
  91166. promises.push(this._loadAnimationsAsync());
  91167. return Promise.all(promises).then(function () { });
  91168. };
  91169. GLTFLoader.prototype._getMeshes = function () {
  91170. var meshes = new Array();
  91171. // Root mesh is always first.
  91172. meshes.push(this._rootBabylonMesh);
  91173. var nodes = this._gltf.nodes;
  91174. if (nodes) {
  91175. for (var _i = 0, nodes_2 = nodes; _i < nodes_2.length; _i++) {
  91176. var node = nodes_2[_i];
  91177. if (node._babylonMesh) {
  91178. meshes.push(node._babylonMesh);
  91179. }
  91180. if (node._primitiveBabylonMeshes) {
  91181. for (var _a = 0, _b = node._primitiveBabylonMeshes; _a < _b.length; _a++) {
  91182. var babylonMesh = _b[_a];
  91183. meshes.push(babylonMesh);
  91184. }
  91185. }
  91186. }
  91187. }
  91188. return meshes;
  91189. };
  91190. GLTFLoader.prototype._getSkeletons = function () {
  91191. var skeletons = new Array();
  91192. var skins = this._gltf.skins;
  91193. if (skins) {
  91194. for (var _i = 0, skins_1 = skins; _i < skins_1.length; _i++) {
  91195. var skin = skins_1[_i];
  91196. if (skin._babylonSkeleton) {
  91197. skeletons.push(skin._babylonSkeleton);
  91198. }
  91199. }
  91200. }
  91201. return skeletons;
  91202. };
  91203. GLTFLoader.prototype._startAnimations = function () {
  91204. var animations = this._gltf.animations;
  91205. if (!animations) {
  91206. return;
  91207. }
  91208. switch (this.animationStartMode) {
  91209. case BABYLON.GLTFLoaderAnimationStartMode.NONE: {
  91210. // do nothing
  91211. break;
  91212. }
  91213. case BABYLON.GLTFLoaderAnimationStartMode.FIRST: {
  91214. var animation = animations[0];
  91215. animation._babylonAnimationGroup.start(true);
  91216. break;
  91217. }
  91218. case BABYLON.GLTFLoaderAnimationStartMode.ALL: {
  91219. for (var _i = 0, animations_1 = animations; _i < animations_1.length; _i++) {
  91220. var animation = animations_1[_i];
  91221. animation._babylonAnimationGroup.start(true);
  91222. }
  91223. break;
  91224. }
  91225. default: {
  91226. BABYLON.Tools.Error("Invalid animation start mode " + this.animationStartMode);
  91227. return;
  91228. }
  91229. }
  91230. };
  91231. GLTFLoader.prototype._loadNodeAsync = function (context, node) {
  91232. var promise = GLTF2.GLTFLoaderExtension._LoadNodeAsync(this, context, node);
  91233. if (promise) {
  91234. return promise;
  91235. }
  91236. if (node._babylonMesh) {
  91237. throw new Error(context + ": Invalid recursive node hierarchy");
  91238. }
  91239. var promises = new Array();
  91240. var babylonMesh = new BABYLON.Mesh(node.name || "node" + node._index, this._babylonScene, node._parent._babylonMesh);
  91241. node._babylonMesh = babylonMesh;
  91242. node._babylonAnimationTargets = node._babylonAnimationTargets || [];
  91243. node._babylonAnimationTargets.push(babylonMesh);
  91244. GLTFLoader._LoadTransform(node, babylonMesh);
  91245. if (node.mesh != undefined) {
  91246. var mesh = GLTFLoader._GetProperty(context + "/mesh", this._gltf.meshes, node.mesh);
  91247. promises.push(this._loadMeshAsync("#/meshes/" + mesh._index, node, mesh));
  91248. }
  91249. if (node.children) {
  91250. for (var _i = 0, _a = node.children; _i < _a.length; _i++) {
  91251. var index = _a[_i];
  91252. var childNode = GLTFLoader._GetProperty(context + "/children/" + index, this._gltf.nodes, index);
  91253. promises.push(this._loadNodeAsync("#/nodes/" + index, childNode));
  91254. }
  91255. }
  91256. this.onMeshLoadedObservable.notifyObservers(babylonMesh);
  91257. return Promise.all(promises).then(function () { });
  91258. };
  91259. GLTFLoader.prototype._loadMeshAsync = function (context, node, mesh) {
  91260. // TODO: instancing
  91261. var promises = new Array();
  91262. var primitives = mesh.primitives;
  91263. if (!primitives || primitives.length === 0) {
  91264. throw new Error(context + ": Primitives are missing");
  91265. }
  91266. GLTF2.ArrayItem.Assign(primitives);
  91267. for (var _i = 0, primitives_1 = primitives; _i < primitives_1.length; _i++) {
  91268. var primitive = primitives_1[_i];
  91269. promises.push(this._loadPrimitiveAsync(context + "/primitives/" + primitive._index, node, mesh, primitive));
  91270. }
  91271. if (node.skin != undefined) {
  91272. var skin = GLTFLoader._GetProperty(context + "/skin", this._gltf.skins, node.skin);
  91273. promises.push(this._loadSkinAsync("#/skins/" + skin._index, node, mesh, skin));
  91274. }
  91275. return Promise.all(promises).then(function () {
  91276. if (node._primitiveBabylonMeshes) {
  91277. for (var _i = 0, _a = node._primitiveBabylonMeshes; _i < _a.length; _i++) {
  91278. var primitiveBabylonMesh = _a[_i];
  91279. primitiveBabylonMesh._refreshBoundingInfo(true);
  91280. }
  91281. }
  91282. });
  91283. };
  91284. GLTFLoader.prototype._loadPrimitiveAsync = function (context, node, mesh, primitive) {
  91285. var _this = this;
  91286. var promises = new Array();
  91287. var babylonMesh = new BABYLON.Mesh((mesh.name || node._babylonMesh.name) + "_" + primitive._index, this._babylonScene, node._babylonMesh);
  91288. babylonMesh.setEnabled(false);
  91289. node._primitiveBabylonMeshes = node._primitiveBabylonMeshes || [];
  91290. node._primitiveBabylonMeshes[primitive._index] = babylonMesh;
  91291. this._createMorphTargets(context, node, mesh, primitive, babylonMesh);
  91292. promises.push(this._loadVertexDataAsync(context, primitive, babylonMesh).then(function (babylonVertexData) {
  91293. new BABYLON.Geometry(babylonMesh.name, _this._babylonScene, babylonVertexData, false, babylonMesh);
  91294. return _this._loadMorphTargetsAsync(context, primitive, babylonMesh, babylonVertexData);
  91295. }));
  91296. if (primitive.material == undefined) {
  91297. babylonMesh.material = this._getDefaultMaterial();
  91298. }
  91299. else {
  91300. var material = GLTFLoader._GetProperty(context + "/material", this._gltf.materials, primitive.material);
  91301. promises.push(this._loadMaterialAsync("#/materials/" + material._index, material, babylonMesh));
  91302. }
  91303. this.onMeshLoadedObservable.notifyObservers(babylonMesh);
  91304. return Promise.all(promises).then(function () {
  91305. babylonMesh.setEnabled(true);
  91306. });
  91307. };
  91308. GLTFLoader.prototype._loadVertexDataAsync = function (context, primitive, babylonMesh) {
  91309. var _this = this;
  91310. var attributes = primitive.attributes;
  91311. if (!attributes) {
  91312. throw new Error(context + ": Attributes are missing");
  91313. }
  91314. if (primitive.mode && primitive.mode !== 4 /* TRIANGLES */) {
  91315. // TODO: handle other primitive modes
  91316. throw new Error(context + ": Mode " + primitive.mode + " is not currently supported");
  91317. }
  91318. var promises = new Array();
  91319. var babylonVertexData = new BABYLON.VertexData();
  91320. if (primitive.indices == undefined) {
  91321. var positionAccessorIndex = attributes["POSITION"];
  91322. if (positionAccessorIndex != undefined) {
  91323. var accessor = GLTFLoader._GetProperty(context + "/attributes/POSITION", this._gltf.accessors, positionAccessorIndex);
  91324. babylonVertexData.indices = new Uint32Array(accessor.count);
  91325. for (var i = 0; i < babylonVertexData.indices.length; i++) {
  91326. babylonVertexData.indices[i] = i;
  91327. }
  91328. }
  91329. }
  91330. else {
  91331. var indicesAccessor = GLTFLoader._GetProperty(context + "/indices", this._gltf.accessors, primitive.indices);
  91332. promises.push(this._loadAccessorAsync("#/accessors/" + indicesAccessor._index, indicesAccessor).then(function (data) {
  91333. babylonVertexData.indices = data;
  91334. }));
  91335. }
  91336. var loadAttribute = function (attribute, kind) {
  91337. if (attributes[attribute] == undefined) {
  91338. return;
  91339. }
  91340. babylonMesh._delayInfo = babylonMesh._delayInfo || [];
  91341. if (babylonMesh._delayInfo.indexOf(kind) === -1) {
  91342. babylonMesh._delayInfo.push(kind);
  91343. }
  91344. var accessor = GLTFLoader._GetProperty(context + "/attributes/" + attribute, _this._gltf.accessors, attributes[attribute]);
  91345. promises.push(_this._loadAccessorAsync("#/accessors/" + accessor._index, accessor).then(function (data) {
  91346. var attributeData = GLTFLoader._ConvertToFloat32Array(context, accessor, data);
  91347. if (attribute === "COLOR_0") {
  91348. // Assume vertex color has alpha on the mesh. The alphaMode of the material controls whether the material should use alpha or not.
  91349. babylonMesh.hasVertexAlpha = true;
  91350. if (accessor.type === "VEC3") {
  91351. attributeData = GLTFLoader._ConvertVec3ToVec4(context, attributeData);
  91352. }
  91353. }
  91354. babylonVertexData.set(attributeData, kind);
  91355. }));
  91356. };
  91357. loadAttribute("POSITION", BABYLON.VertexBuffer.PositionKind);
  91358. loadAttribute("NORMAL", BABYLON.VertexBuffer.NormalKind);
  91359. loadAttribute("TANGENT", BABYLON.VertexBuffer.TangentKind);
  91360. loadAttribute("TEXCOORD_0", BABYLON.VertexBuffer.UVKind);
  91361. loadAttribute("TEXCOORD_1", BABYLON.VertexBuffer.UV2Kind);
  91362. loadAttribute("JOINTS_0", BABYLON.VertexBuffer.MatricesIndicesKind);
  91363. loadAttribute("WEIGHTS_0", BABYLON.VertexBuffer.MatricesWeightsKind);
  91364. loadAttribute("COLOR_0", BABYLON.VertexBuffer.ColorKind);
  91365. return Promise.all(promises).then(function () {
  91366. return babylonVertexData;
  91367. });
  91368. };
  91369. GLTFLoader.prototype._createMorphTargets = function (context, node, mesh, primitive, babylonMesh) {
  91370. if (!primitive.targets) {
  91371. return;
  91372. }
  91373. if (node._numMorphTargets == undefined) {
  91374. node._numMorphTargets = primitive.targets.length;
  91375. }
  91376. else if (primitive.targets.length !== node._numMorphTargets) {
  91377. throw new Error(context + ": Primitives do not have the same number of targets");
  91378. }
  91379. babylonMesh.morphTargetManager = new BABYLON.MorphTargetManager();
  91380. for (var index = 0; index < primitive.targets.length; index++) {
  91381. var weight = node.weights ? node.weights[index] : mesh.weights ? mesh.weights[index] : 0;
  91382. babylonMesh.morphTargetManager.addTarget(new BABYLON.MorphTarget("morphTarget" + index, weight));
  91383. // TODO: tell the target whether it has positions, normals, tangents
  91384. }
  91385. };
  91386. GLTFLoader.prototype._loadMorphTargetsAsync = function (context, primitive, babylonMesh, babylonVertexData) {
  91387. if (!primitive.targets) {
  91388. return Promise.resolve();
  91389. }
  91390. var promises = new Array();
  91391. var morphTargetManager = babylonMesh.morphTargetManager;
  91392. for (var index = 0; index < morphTargetManager.numTargets; index++) {
  91393. var babylonMorphTarget = morphTargetManager.getTarget(index);
  91394. promises.push(this._loadMorphTargetVertexDataAsync(context + "/targets/" + index, babylonVertexData, primitive.targets[index], babylonMorphTarget));
  91395. }
  91396. return Promise.all(promises).then(function () { });
  91397. };
  91398. GLTFLoader.prototype._loadMorphTargetVertexDataAsync = function (context, babylonVertexData, attributes, babylonMorphTarget) {
  91399. var _this = this;
  91400. var promises = new Array();
  91401. var loadAttribute = function (attribute, setData) {
  91402. if (attributes[attribute] == undefined) {
  91403. return;
  91404. }
  91405. var accessor = GLTFLoader._GetProperty(context + "/" + attribute, _this._gltf.accessors, attributes[attribute]);
  91406. promises.push(_this._loadAccessorAsync("#/accessors/" + accessor._index, accessor).then(function (data) {
  91407. setData(data);
  91408. }));
  91409. };
  91410. loadAttribute("POSITION", function (data) {
  91411. if (babylonVertexData.positions) {
  91412. for (var i = 0; i < data.length; i++) {
  91413. data[i] += babylonVertexData.positions[i];
  91414. }
  91415. babylonMorphTarget.setPositions(data);
  91416. }
  91417. });
  91418. loadAttribute("NORMAL", function (data) {
  91419. if (babylonVertexData.normals) {
  91420. for (var i = 0; i < data.length; i++) {
  91421. data[i] += babylonVertexData.normals[i];
  91422. }
  91423. babylonMorphTarget.setNormals(data);
  91424. }
  91425. });
  91426. loadAttribute("TANGENT", function (data) {
  91427. if (babylonVertexData.tangents) {
  91428. // Tangent data for morph targets is stored as xyz delta.
  91429. // The vertexData.tangent is stored as xyzw.
  91430. // So we need to skip every fourth vertexData.tangent.
  91431. for (var i = 0, j = 0; i < data.length; i++) {
  91432. data[i] += babylonVertexData.tangents[j++];
  91433. if ((i + 1) % 3 == 0) {
  91434. j++;
  91435. }
  91436. }
  91437. babylonMorphTarget.setTangents(data);
  91438. }
  91439. });
  91440. return Promise.all(promises).then(function () { });
  91441. };
  91442. GLTFLoader._ConvertToFloat32Array = function (context, accessor, data) {
  91443. if (accessor.componentType == 5126 /* FLOAT */) {
  91444. return data;
  91445. }
  91446. var factor = 1;
  91447. if (accessor.normalized) {
  91448. switch (accessor.componentType) {
  91449. case 5121 /* UNSIGNED_BYTE */: {
  91450. factor = 1 / 255;
  91451. break;
  91452. }
  91453. case 5123 /* UNSIGNED_SHORT */: {
  91454. factor = 1 / 65535;
  91455. break;
  91456. }
  91457. default: {
  91458. throw new Error(context + ": Invalid component type " + accessor.componentType);
  91459. }
  91460. }
  91461. }
  91462. var result = new Float32Array(accessor.count * GLTFLoader._GetNumComponents(context, accessor.type));
  91463. for (var i = 0; i < result.length; i++) {
  91464. result[i] = data[i] * factor;
  91465. }
  91466. return result;
  91467. };
  91468. GLTFLoader._ConvertVec3ToVec4 = function (context, data) {
  91469. var result = new Float32Array(data.length / 3 * 4);
  91470. var offset = 0;
  91471. for (var i = 0; i < result.length; i++) {
  91472. if ((i + 1) % 4 === 0) {
  91473. result[i] = 1;
  91474. }
  91475. else {
  91476. result[i] = data[offset++];
  91477. }
  91478. }
  91479. return result;
  91480. };
  91481. GLTFLoader._LoadTransform = function (node, babylonNode) {
  91482. var position = BABYLON.Vector3.Zero();
  91483. var rotation = BABYLON.Quaternion.Identity();
  91484. var scaling = BABYLON.Vector3.One();
  91485. if (node.matrix) {
  91486. var matrix = BABYLON.Matrix.FromArray(node.matrix);
  91487. matrix.decompose(scaling, rotation, position);
  91488. }
  91489. else {
  91490. if (node.translation)
  91491. position = BABYLON.Vector3.FromArray(node.translation);
  91492. if (node.rotation)
  91493. rotation = BABYLON.Quaternion.FromArray(node.rotation);
  91494. if (node.scale)
  91495. scaling = BABYLON.Vector3.FromArray(node.scale);
  91496. }
  91497. babylonNode.position = position;
  91498. babylonNode.rotationQuaternion = rotation;
  91499. babylonNode.scaling = scaling;
  91500. };
  91501. GLTFLoader.prototype._loadSkinAsync = function (context, node, mesh, skin) {
  91502. var _this = this;
  91503. var assignSkeleton = function () {
  91504. for (var _i = 0, _a = node._primitiveBabylonMeshes; _i < _a.length; _i++) {
  91505. var babylonMesh = _a[_i];
  91506. babylonMesh.skeleton = skin._babylonSkeleton;
  91507. }
  91508. node._babylonMesh.parent = _this._rootBabylonMesh;
  91509. node._babylonMesh.position = BABYLON.Vector3.Zero();
  91510. node._babylonMesh.rotationQuaternion = BABYLON.Quaternion.Identity();
  91511. node._babylonMesh.scaling = BABYLON.Vector3.One();
  91512. };
  91513. if (skin._loaded) {
  91514. assignSkeleton();
  91515. return skin._loaded;
  91516. }
  91517. // TODO: split into two parts so that bones are created before inverseBindMatricesData is loaded (for compiling materials).
  91518. return (skin._loaded = this._loadSkinInverseBindMatricesDataAsync(context, skin).then(function (inverseBindMatricesData) {
  91519. var skeletonId = "skeleton" + skin._index;
  91520. var babylonSkeleton = new BABYLON.Skeleton(skin.name || skeletonId, skeletonId, _this._babylonScene);
  91521. skin._babylonSkeleton = babylonSkeleton;
  91522. _this._loadBones(context, skin, inverseBindMatricesData);
  91523. assignSkeleton();
  91524. }));
  91525. };
  91526. GLTFLoader.prototype._loadSkinInverseBindMatricesDataAsync = function (context, skin) {
  91527. if (skin.inverseBindMatrices == undefined) {
  91528. return Promise.resolve(null);
  91529. }
  91530. var accessor = GLTFLoader._GetProperty(context + "/inverseBindMatrices", this._gltf.accessors, skin.inverseBindMatrices);
  91531. return this._loadAccessorAsync("#/accessors/" + accessor._index, accessor).then(function (data) {
  91532. return data;
  91533. });
  91534. };
  91535. GLTFLoader.prototype._createBone = function (node, skin, parent, localMatrix, baseMatrix, index) {
  91536. var babylonBone = new BABYLON.Bone(node.name || "joint" + node._index, skin._babylonSkeleton, parent, localMatrix, null, baseMatrix, index);
  91537. node._babylonAnimationTargets = node._babylonAnimationTargets || [];
  91538. node._babylonAnimationTargets.push(babylonBone);
  91539. return babylonBone;
  91540. };
  91541. GLTFLoader.prototype._loadBones = function (context, skin, inverseBindMatricesData) {
  91542. var babylonBones = {};
  91543. for (var _i = 0, _a = skin.joints; _i < _a.length; _i++) {
  91544. var index = _a[_i];
  91545. var node = GLTFLoader._GetProperty(context + "/joints/" + index, this._gltf.nodes, index);
  91546. this._loadBone(node, skin, inverseBindMatricesData, babylonBones);
  91547. }
  91548. };
  91549. GLTFLoader.prototype._loadBone = function (node, skin, inverseBindMatricesData, babylonBones) {
  91550. var babylonBone = babylonBones[node._index];
  91551. if (babylonBone) {
  91552. return babylonBone;
  91553. }
  91554. var boneIndex = skin.joints.indexOf(node._index);
  91555. var baseMatrix = BABYLON.Matrix.Identity();
  91556. if (inverseBindMatricesData && boneIndex !== -1) {
  91557. baseMatrix = BABYLON.Matrix.FromArray(inverseBindMatricesData, boneIndex * 16);
  91558. baseMatrix.invertToRef(baseMatrix);
  91559. }
  91560. var babylonParentBone = null;
  91561. if (node._parent._babylonMesh !== this._rootBabylonMesh) {
  91562. babylonParentBone = this._loadBone(node._parent, skin, inverseBindMatricesData, babylonBones);
  91563. baseMatrix.multiplyToRef(babylonParentBone.getInvertedAbsoluteTransform(), baseMatrix);
  91564. }
  91565. babylonBone = this._createBone(node, skin, babylonParentBone, this._getNodeMatrix(node), baseMatrix, boneIndex);
  91566. babylonBones[node._index] = babylonBone;
  91567. return babylonBone;
  91568. };
  91569. GLTFLoader.prototype._getNodeMatrix = function (node) {
  91570. return node.matrix ?
  91571. BABYLON.Matrix.FromArray(node.matrix) :
  91572. 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());
  91573. };
  91574. GLTFLoader.prototype._loadAnimationsAsync = function () {
  91575. var animations = this._gltf.animations;
  91576. if (!animations) {
  91577. return Promise.resolve();
  91578. }
  91579. var promises = new Array();
  91580. for (var index = 0; index < animations.length; index++) {
  91581. var animation = animations[index];
  91582. promises.push(this._loadAnimationAsync("#/animations/" + index, animation));
  91583. }
  91584. return Promise.all(promises).then(function () { });
  91585. };
  91586. GLTFLoader.prototype._loadAnimationAsync = function (context, animation) {
  91587. var babylonAnimationGroup = new BABYLON.AnimationGroup(animation.name || "animation" + animation._index, this._babylonScene);
  91588. animation._babylonAnimationGroup = babylonAnimationGroup;
  91589. var promises = new Array();
  91590. GLTF2.ArrayItem.Assign(animation.channels);
  91591. GLTF2.ArrayItem.Assign(animation.samplers);
  91592. for (var _i = 0, _a = animation.channels; _i < _a.length; _i++) {
  91593. var channel = _a[_i];
  91594. promises.push(this._loadAnimationChannelAsync(context + "/channels/" + channel._index, context, animation, channel, babylonAnimationGroup));
  91595. }
  91596. return Promise.all(promises).then(function () {
  91597. babylonAnimationGroup.normalize();
  91598. });
  91599. };
  91600. GLTFLoader.prototype._loadAnimationChannelAsync = function (context, animationContext, animation, channel, babylonAnimationGroup) {
  91601. var targetNode = GLTFLoader._GetProperty(context + "/target/node", this._gltf.nodes, channel.target.node);
  91602. if (!targetNode._babylonMesh) {
  91603. return Promise.resolve();
  91604. }
  91605. var sampler = GLTFLoader._GetProperty(context + "/sampler", animation.samplers, channel.sampler);
  91606. return this._loadAnimationSamplerAsync(animationContext + "/samplers/" + channel.sampler, sampler).then(function (data) {
  91607. var targetPath;
  91608. var animationType;
  91609. switch (channel.target.path) {
  91610. case "translation" /* TRANSLATION */: {
  91611. targetPath = "position";
  91612. animationType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  91613. break;
  91614. }
  91615. case "rotation" /* ROTATION */: {
  91616. targetPath = "rotationQuaternion";
  91617. animationType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  91618. break;
  91619. }
  91620. case "scale" /* SCALE */: {
  91621. targetPath = "scaling";
  91622. animationType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  91623. break;
  91624. }
  91625. case "weights" /* WEIGHTS */: {
  91626. targetPath = "influence";
  91627. animationType = BABYLON.Animation.ANIMATIONTYPE_FLOAT;
  91628. break;
  91629. }
  91630. default: {
  91631. throw new Error(context + ": Invalid target path " + channel.target.path);
  91632. }
  91633. }
  91634. var outputBufferOffset = 0;
  91635. var getNextOutputValue;
  91636. switch (targetPath) {
  91637. case "position": {
  91638. getNextOutputValue = function () {
  91639. var value = BABYLON.Vector3.FromArray(data.output, outputBufferOffset);
  91640. outputBufferOffset += 3;
  91641. return value;
  91642. };
  91643. break;
  91644. }
  91645. case "rotationQuaternion": {
  91646. getNextOutputValue = function () {
  91647. var value = BABYLON.Quaternion.FromArray(data.output, outputBufferOffset);
  91648. outputBufferOffset += 4;
  91649. return value;
  91650. };
  91651. break;
  91652. }
  91653. case "scaling": {
  91654. getNextOutputValue = function () {
  91655. var value = BABYLON.Vector3.FromArray(data.output, outputBufferOffset);
  91656. outputBufferOffset += 3;
  91657. return value;
  91658. };
  91659. break;
  91660. }
  91661. case "influence": {
  91662. getNextOutputValue = function () {
  91663. var value = new Array(targetNode._numMorphTargets);
  91664. for (var i = 0; i < targetNode._numMorphTargets; i++) {
  91665. value[i] = data.output[outputBufferOffset++];
  91666. }
  91667. return value;
  91668. };
  91669. break;
  91670. }
  91671. }
  91672. var getNextKey;
  91673. switch (data.interpolation) {
  91674. case "STEP" /* STEP */: {
  91675. getNextKey = function (frameIndex) { return ({
  91676. frame: data.input[frameIndex],
  91677. value: getNextOutputValue(),
  91678. interpolation: BABYLON.AnimationKeyInterpolation.STEP
  91679. }); };
  91680. break;
  91681. }
  91682. case "LINEAR" /* LINEAR */: {
  91683. getNextKey = function (frameIndex) { return ({
  91684. frame: data.input[frameIndex],
  91685. value: getNextOutputValue()
  91686. }); };
  91687. break;
  91688. }
  91689. case "CUBICSPLINE" /* CUBICSPLINE */: {
  91690. getNextKey = function (frameIndex) { return ({
  91691. frame: data.input[frameIndex],
  91692. inTangent: getNextOutputValue(),
  91693. value: getNextOutputValue(),
  91694. outTangent: getNextOutputValue()
  91695. }); };
  91696. break;
  91697. }
  91698. }
  91699. var keys;
  91700. if (data.input.length === 1) {
  91701. var key = getNextKey(0);
  91702. keys = [
  91703. { frame: key.frame, value: key.value },
  91704. { frame: key.frame + 1, value: key.value }
  91705. ];
  91706. }
  91707. else {
  91708. keys = new Array(data.input.length);
  91709. for (var frameIndex = 0; frameIndex < data.input.length; frameIndex++) {
  91710. keys[frameIndex] = getNextKey(frameIndex);
  91711. }
  91712. }
  91713. if (targetPath === "influence") {
  91714. var _loop_1 = function (targetIndex) {
  91715. var animationName = babylonAnimationGroup.name + "_channel" + babylonAnimationGroup.targetedAnimations.length;
  91716. var babylonAnimation = new BABYLON.Animation(animationName, targetPath, 1, animationType);
  91717. babylonAnimation.setKeys(keys.map(function (key) { return ({
  91718. frame: key.frame,
  91719. inTangent: key.inTangent ? key.inTangent[targetIndex] : undefined,
  91720. value: key.value[targetIndex],
  91721. outTangent: key.outTangent ? key.outTangent[targetIndex] : undefined
  91722. }); }));
  91723. for (var _i = 0, _a = targetNode._primitiveBabylonMeshes; _i < _a.length; _i++) {
  91724. var babylonMesh = _a[_i];
  91725. var morphTarget = babylonMesh.morphTargetManager.getTarget(targetIndex);
  91726. babylonAnimationGroup.addTargetedAnimation(babylonAnimation, morphTarget);
  91727. }
  91728. };
  91729. for (var targetIndex = 0; targetIndex < targetNode._numMorphTargets; targetIndex++) {
  91730. _loop_1(targetIndex);
  91731. }
  91732. }
  91733. else {
  91734. var animationName = babylonAnimationGroup.name + "_channel" + babylonAnimationGroup.targetedAnimations.length;
  91735. var babylonAnimation = new BABYLON.Animation(animationName, targetPath, 1, animationType);
  91736. babylonAnimation.setKeys(keys);
  91737. if (targetNode._babylonAnimationTargets) {
  91738. for (var _i = 0, _a = targetNode._babylonAnimationTargets; _i < _a.length; _i++) {
  91739. var target = _a[_i];
  91740. babylonAnimationGroup.addTargetedAnimation(babylonAnimation, target);
  91741. }
  91742. }
  91743. }
  91744. });
  91745. };
  91746. GLTFLoader.prototype._loadAnimationSamplerAsync = function (context, sampler) {
  91747. if (sampler._data) {
  91748. return sampler._data;
  91749. }
  91750. var interpolation = sampler.interpolation || "LINEAR" /* LINEAR */;
  91751. switch (interpolation) {
  91752. case "STEP" /* STEP */:
  91753. case "LINEAR" /* LINEAR */:
  91754. case "CUBICSPLINE" /* CUBICSPLINE */: {
  91755. break;
  91756. }
  91757. default: {
  91758. throw new Error(context + ": Invalid interpolation " + sampler.interpolation);
  91759. }
  91760. }
  91761. var inputData;
  91762. var outputData;
  91763. var inputAccessor = GLTFLoader._GetProperty(context + "/input", this._gltf.accessors, sampler.input);
  91764. var outputAccessor = GLTFLoader._GetProperty(context + "/output", this._gltf.accessors, sampler.output);
  91765. sampler._data = Promise.all([
  91766. this._loadAccessorAsync("#/accessors/" + inputAccessor._index, inputAccessor).then(function (data) {
  91767. inputData = data;
  91768. }),
  91769. this._loadAccessorAsync("#/accessors/" + outputAccessor._index, outputAccessor).then(function (data) {
  91770. outputData = data;
  91771. })
  91772. ]).then(function () {
  91773. return {
  91774. input: inputData,
  91775. interpolation: interpolation,
  91776. output: outputData,
  91777. };
  91778. });
  91779. return sampler._data;
  91780. };
  91781. GLTFLoader.prototype._loadBufferAsync = function (context, buffer) {
  91782. if (buffer._data) {
  91783. return buffer._data;
  91784. }
  91785. if (!buffer.uri) {
  91786. throw new Error(context + ": Uri is missing");
  91787. }
  91788. buffer._data = this._loadUriAsync(context, buffer.uri);
  91789. return buffer._data;
  91790. };
  91791. GLTFLoader.prototype._loadBufferViewAsync = function (context, bufferView) {
  91792. if (bufferView._data) {
  91793. return bufferView._data;
  91794. }
  91795. var buffer = GLTFLoader._GetProperty(context + "/buffer", this._gltf.buffers, bufferView.buffer);
  91796. bufferView._data = this._loadBufferAsync("#/buffers/" + buffer._index, buffer).then(function (bufferData) {
  91797. try {
  91798. return new Uint8Array(bufferData.buffer, bufferData.byteOffset + (bufferView.byteOffset || 0), bufferView.byteLength);
  91799. }
  91800. catch (e) {
  91801. throw new Error(context + ": " + e.message);
  91802. }
  91803. });
  91804. return bufferView._data;
  91805. };
  91806. GLTFLoader.prototype._loadAccessorAsync = function (context, accessor) {
  91807. var _this = this;
  91808. if (accessor.sparse) {
  91809. throw new Error(context + ": Sparse accessors are not currently supported");
  91810. }
  91811. if (accessor._data) {
  91812. return accessor._data;
  91813. }
  91814. var bufferView = GLTFLoader._GetProperty(context + "/bufferView", this._gltf.bufferViews, accessor.bufferView);
  91815. accessor._data = this._loadBufferViewAsync("#/bufferViews/" + bufferView._index, bufferView).then(function (bufferViewData) {
  91816. var numComponents = GLTFLoader._GetNumComponents(context, accessor.type);
  91817. var byteOffset = accessor.byteOffset || 0;
  91818. var byteStride = bufferView.byteStride;
  91819. if (byteStride === 0) {
  91820. BABYLON.Tools.Warn(context + ": Byte stride of 0 is not valid");
  91821. }
  91822. try {
  91823. switch (accessor.componentType) {
  91824. case 5120 /* BYTE */: {
  91825. return _this._buildArrayBuffer(Float32Array, bufferViewData, byteOffset, accessor.count, numComponents, byteStride);
  91826. }
  91827. case 5121 /* UNSIGNED_BYTE */: {
  91828. return _this._buildArrayBuffer(Uint8Array, bufferViewData, byteOffset, accessor.count, numComponents, byteStride);
  91829. }
  91830. case 5122 /* SHORT */: {
  91831. return _this._buildArrayBuffer(Int16Array, bufferViewData, byteOffset, accessor.count, numComponents, byteStride);
  91832. }
  91833. case 5123 /* UNSIGNED_SHORT */: {
  91834. return _this._buildArrayBuffer(Uint16Array, bufferViewData, byteOffset, accessor.count, numComponents, byteStride);
  91835. }
  91836. case 5125 /* UNSIGNED_INT */: {
  91837. return _this._buildArrayBuffer(Uint32Array, bufferViewData, byteOffset, accessor.count, numComponents, byteStride);
  91838. }
  91839. case 5126 /* FLOAT */: {
  91840. return _this._buildArrayBuffer(Float32Array, bufferViewData, byteOffset, accessor.count, numComponents, byteStride);
  91841. }
  91842. default: {
  91843. throw new Error(context + ": Invalid component type " + accessor.componentType);
  91844. }
  91845. }
  91846. }
  91847. catch (e) {
  91848. throw new Error(context + ": " + e);
  91849. }
  91850. });
  91851. return accessor._data;
  91852. };
  91853. GLTFLoader.prototype._buildArrayBuffer = function (typedArray, data, byteOffset, count, numComponents, byteStride) {
  91854. byteOffset += data.byteOffset;
  91855. var targetLength = count * numComponents;
  91856. if (!byteStride || byteStride === numComponents * typedArray.BYTES_PER_ELEMENT) {
  91857. return new typedArray(data.buffer, byteOffset, targetLength);
  91858. }
  91859. var elementStride = byteStride / typedArray.BYTES_PER_ELEMENT;
  91860. var sourceBuffer = new typedArray(data.buffer, byteOffset, elementStride * count);
  91861. var targetBuffer = new typedArray(targetLength);
  91862. var sourceIndex = 0;
  91863. var targetIndex = 0;
  91864. while (targetIndex < targetLength) {
  91865. for (var componentIndex = 0; componentIndex < numComponents; componentIndex++) {
  91866. targetBuffer[targetIndex] = sourceBuffer[sourceIndex + componentIndex];
  91867. targetIndex++;
  91868. }
  91869. sourceIndex += elementStride;
  91870. }
  91871. return targetBuffer;
  91872. };
  91873. GLTFLoader.prototype._getDefaultMaterial = function () {
  91874. var id = "__gltf_default";
  91875. var babylonMaterial = this._babylonScene.getMaterialByName(id);
  91876. if (!babylonMaterial) {
  91877. babylonMaterial = new BABYLON.PBRMaterial(id, this._babylonScene);
  91878. babylonMaterial.transparencyMode = BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE;
  91879. babylonMaterial.sideOrientation = this._babylonScene.useRightHandedSystem ? BABYLON.Material.CounterClockWiseSideOrientation : BABYLON.Material.ClockWiseSideOrientation;
  91880. babylonMaterial.metallic = 1;
  91881. babylonMaterial.roughness = 1;
  91882. this.onMaterialLoadedObservable.notifyObservers(babylonMaterial);
  91883. }
  91884. return babylonMaterial;
  91885. };
  91886. GLTFLoader.prototype._loadMaterialMetallicRoughnessPropertiesAsync = function (context, material) {
  91887. var promises = new Array();
  91888. var babylonMaterial = material._babylonMaterial;
  91889. // Ensure metallic workflow
  91890. babylonMaterial.metallic = 1;
  91891. babylonMaterial.roughness = 1;
  91892. var properties = material.pbrMetallicRoughness;
  91893. if (properties) {
  91894. if (properties.baseColorFactor) {
  91895. babylonMaterial.albedoColor = BABYLON.Color3.FromArray(properties.baseColorFactor);
  91896. babylonMaterial.alpha = properties.baseColorFactor[3];
  91897. }
  91898. else {
  91899. babylonMaterial.albedoColor = BABYLON.Color3.White();
  91900. }
  91901. babylonMaterial.metallic = properties.metallicFactor == undefined ? 1 : properties.metallicFactor;
  91902. babylonMaterial.roughness = properties.roughnessFactor == undefined ? 1 : properties.roughnessFactor;
  91903. if (properties.baseColorTexture) {
  91904. promises.push(this._loadTextureAsync(context + "/baseColorTexture", properties.baseColorTexture, function (texture) {
  91905. babylonMaterial.albedoTexture = texture;
  91906. }));
  91907. }
  91908. if (properties.metallicRoughnessTexture) {
  91909. promises.push(this._loadTextureAsync(context + "/metallicRoughnessTexture", properties.metallicRoughnessTexture, function (texture) {
  91910. babylonMaterial.metallicTexture = texture;
  91911. }));
  91912. babylonMaterial.useMetallnessFromMetallicTextureBlue = true;
  91913. babylonMaterial.useRoughnessFromMetallicTextureGreen = true;
  91914. babylonMaterial.useRoughnessFromMetallicTextureAlpha = false;
  91915. }
  91916. }
  91917. this._loadMaterialAlphaProperties(context, material);
  91918. return Promise.all(promises).then(function () { });
  91919. };
  91920. GLTFLoader.prototype._loadMaterialAsync = function (context, material, babylonMesh) {
  91921. var promise = GLTF2.GLTFLoaderExtension._LoadMaterialAsync(this, context, material, babylonMesh);
  91922. if (promise) {
  91923. return promise;
  91924. }
  91925. material._babylonMeshes = material._babylonMeshes || [];
  91926. material._babylonMeshes.push(babylonMesh);
  91927. if (material._loaded) {
  91928. babylonMesh.material = material._babylonMaterial;
  91929. return material._loaded;
  91930. }
  91931. var promises = new Array();
  91932. var babylonMaterial = this._createMaterial(material);
  91933. material._babylonMaterial = babylonMaterial;
  91934. promises.push(this._loadMaterialBasePropertiesAsync(context, material));
  91935. promises.push(this._loadMaterialMetallicRoughnessPropertiesAsync(context, material));
  91936. this.onMaterialLoadedObservable.notifyObservers(babylonMaterial);
  91937. babylonMesh.material = babylonMaterial;
  91938. return (material._loaded = Promise.all(promises).then(function () { }));
  91939. };
  91940. GLTFLoader.prototype._createMaterial = function (material) {
  91941. var babylonMaterial = new BABYLON.PBRMaterial(material.name || "material" + material._index, this._babylonScene);
  91942. babylonMaterial.sideOrientation = this._babylonScene.useRightHandedSystem ? BABYLON.Material.CounterClockWiseSideOrientation : BABYLON.Material.ClockWiseSideOrientation;
  91943. return babylonMaterial;
  91944. };
  91945. GLTFLoader.prototype._loadMaterialBasePropertiesAsync = function (context, material) {
  91946. var promises = new Array();
  91947. var babylonMaterial = material._babylonMaterial;
  91948. babylonMaterial.emissiveColor = material.emissiveFactor ? BABYLON.Color3.FromArray(material.emissiveFactor) : new BABYLON.Color3(0, 0, 0);
  91949. if (material.doubleSided) {
  91950. babylonMaterial.backFaceCulling = false;
  91951. babylonMaterial.twoSidedLighting = true;
  91952. }
  91953. if (material.normalTexture) {
  91954. promises.push(this._loadTextureAsync(context + "/normalTexture", material.normalTexture, function (texture) {
  91955. babylonMaterial.bumpTexture = texture;
  91956. }));
  91957. babylonMaterial.invertNormalMapX = !this._babylonScene.useRightHandedSystem;
  91958. babylonMaterial.invertNormalMapY = this._babylonScene.useRightHandedSystem;
  91959. if (material.normalTexture.scale != undefined) {
  91960. babylonMaterial.bumpTexture.level = material.normalTexture.scale;
  91961. }
  91962. }
  91963. if (material.occlusionTexture) {
  91964. promises.push(this._loadTextureAsync(context + "/occlusionTexture", material.occlusionTexture, function (texture) {
  91965. babylonMaterial.ambientTexture = texture;
  91966. }));
  91967. babylonMaterial.useAmbientInGrayScale = true;
  91968. if (material.occlusionTexture.strength != undefined) {
  91969. babylonMaterial.ambientTextureStrength = material.occlusionTexture.strength;
  91970. }
  91971. }
  91972. if (material.emissiveTexture) {
  91973. promises.push(this._loadTextureAsync(context + "/emissiveTexture", material.emissiveTexture, function (texture) {
  91974. babylonMaterial.emissiveTexture = texture;
  91975. }));
  91976. }
  91977. return Promise.all(promises).then(function () { });
  91978. };
  91979. GLTFLoader.prototype._loadMaterialAlphaProperties = function (context, material) {
  91980. var babylonMaterial = material._babylonMaterial;
  91981. var alphaMode = material.alphaMode || "OPAQUE" /* OPAQUE */;
  91982. switch (alphaMode) {
  91983. case "OPAQUE" /* OPAQUE */: {
  91984. babylonMaterial.transparencyMode = BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE;
  91985. break;
  91986. }
  91987. case "MASK" /* MASK */: {
  91988. babylonMaterial.transparencyMode = BABYLON.PBRMaterial.PBRMATERIAL_ALPHATEST;
  91989. babylonMaterial.alphaCutOff = (material.alphaCutoff == undefined ? 0.5 : material.alphaCutoff);
  91990. if (babylonMaterial.alpha) {
  91991. if (babylonMaterial.alpha === 0) {
  91992. babylonMaterial.alphaCutOff = 1;
  91993. }
  91994. else {
  91995. babylonMaterial.alphaCutOff /= babylonMaterial.alpha;
  91996. }
  91997. babylonMaterial.alpha = 1;
  91998. }
  91999. if (babylonMaterial.albedoTexture) {
  92000. babylonMaterial.albedoTexture.hasAlpha = true;
  92001. }
  92002. break;
  92003. }
  92004. case "BLEND" /* BLEND */: {
  92005. babylonMaterial.transparencyMode = BABYLON.PBRMaterial.PBRMATERIAL_ALPHABLEND;
  92006. if (babylonMaterial.albedoTexture) {
  92007. babylonMaterial.albedoTexture.hasAlpha = true;
  92008. babylonMaterial.useAlphaFromAlbedoTexture = true;
  92009. }
  92010. break;
  92011. }
  92012. default: {
  92013. throw new Error(context + ": Invalid alpha mode " + material.alphaMode);
  92014. }
  92015. }
  92016. };
  92017. GLTFLoader.prototype._loadTextureAsync = function (context, textureInfo, assign) {
  92018. var _this = this;
  92019. var texture = GLTFLoader._GetProperty(context + "/index", this._gltf.textures, textureInfo.index);
  92020. context = "#/textures/" + textureInfo.index;
  92021. var promises = new Array();
  92022. var sampler = (texture.sampler == undefined ? this._defaultSampler : GLTFLoader._GetProperty(context + "/sampler", this._gltf.samplers, texture.sampler));
  92023. var samplerData = this._loadSampler("#/samplers/" + sampler._index, sampler);
  92024. var deferred = new BABYLON.Deferred();
  92025. var babylonTexture = new BABYLON.Texture(null, this._babylonScene, samplerData.noMipMaps, false, samplerData.samplingMode, function () {
  92026. if (!_this._disposed) {
  92027. deferred.resolve();
  92028. }
  92029. }, function (message, exception) {
  92030. if (!_this._disposed) {
  92031. deferred.reject(new Error(context + ": " + (exception && exception.message) ? exception.message : message || "Failed to load texture"));
  92032. }
  92033. });
  92034. promises.push(deferred.promise);
  92035. babylonTexture.name = texture.name || "texture" + texture._index;
  92036. babylonTexture.wrapU = samplerData.wrapU;
  92037. babylonTexture.wrapV = samplerData.wrapV;
  92038. babylonTexture.coordinatesIndex = textureInfo.texCoord || 0;
  92039. var image = GLTFLoader._GetProperty(context + "/source", this._gltf.images, texture.source);
  92040. promises.push(this._loadImageAsync("#/images/" + image._index, image).then(function (objectURL) {
  92041. babylonTexture.updateURL(objectURL);
  92042. }));
  92043. assign(babylonTexture);
  92044. this.onTextureLoadedObservable.notifyObservers(babylonTexture);
  92045. return Promise.all(promises).then(function () { });
  92046. };
  92047. GLTFLoader.prototype._loadSampler = function (context, sampler) {
  92048. if (!sampler._data) {
  92049. sampler._data = {
  92050. noMipMaps: (sampler.minFilter === 9728 /* NEAREST */ || sampler.minFilter === 9729 /* LINEAR */),
  92051. samplingMode: GLTFLoader._GetTextureSamplingMode(context, sampler.magFilter, sampler.minFilter),
  92052. wrapU: GLTFLoader._GetTextureWrapMode(context, sampler.wrapS),
  92053. wrapV: GLTFLoader._GetTextureWrapMode(context, sampler.wrapT)
  92054. };
  92055. }
  92056. ;
  92057. return sampler._data;
  92058. };
  92059. GLTFLoader.prototype._loadImageAsync = function (context, image) {
  92060. if (image._objectURL) {
  92061. return image._objectURL;
  92062. }
  92063. var promise;
  92064. if (image.uri) {
  92065. promise = this._loadUriAsync(context, image.uri);
  92066. }
  92067. else {
  92068. var bufferView = GLTFLoader._GetProperty(context + "/bufferView", this._gltf.bufferViews, image.bufferView);
  92069. promise = this._loadBufferViewAsync("#/bufferViews/" + bufferView._index, bufferView);
  92070. }
  92071. image._objectURL = promise.then(function (data) {
  92072. return URL.createObjectURL(new Blob([data], { type: image.mimeType }));
  92073. });
  92074. return image._objectURL;
  92075. };
  92076. GLTFLoader.prototype._loadUriAsync = function (context, uri) {
  92077. var _this = this;
  92078. var promise = GLTF2.GLTFLoaderExtension._LoadUriAsync(this, context, uri);
  92079. if (promise) {
  92080. return promise;
  92081. }
  92082. if (!GLTFLoader._ValidateUri(uri)) {
  92083. throw new Error(context + ": Uri '" + uri + "' is invalid");
  92084. }
  92085. if (BABYLON.Tools.IsBase64(uri)) {
  92086. return Promise.resolve(new Uint8Array(BABYLON.Tools.DecodeBase64(uri)));
  92087. }
  92088. return new Promise(function (resolve, reject) {
  92089. var request = BABYLON.Tools.LoadFile(_this._rootUrl + uri, function (data) {
  92090. if (!_this._disposed) {
  92091. resolve(new Uint8Array(data));
  92092. }
  92093. }, function (event) {
  92094. if (!_this._disposed) {
  92095. try {
  92096. if (request && _this._state === BABYLON.GLTFLoaderState.Loading) {
  92097. request._lengthComputable = event.lengthComputable;
  92098. request._loaded = event.loaded;
  92099. request._total = event.total;
  92100. _this._onProgress();
  92101. }
  92102. }
  92103. catch (e) {
  92104. reject(e);
  92105. }
  92106. }
  92107. }, _this._babylonScene.database, true, function (request, exception) {
  92108. if (!_this._disposed) {
  92109. reject(new BABYLON.LoadFileError(context + ": Failed to load '" + uri + "'" + (request ? ": " + request.status + " " + request.statusText : ""), request));
  92110. }
  92111. });
  92112. _this._requests.push(request);
  92113. });
  92114. };
  92115. GLTFLoader.prototype._onProgress = function () {
  92116. if (!this._progressCallback) {
  92117. return;
  92118. }
  92119. var lengthComputable = true;
  92120. var loaded = 0;
  92121. var total = 0;
  92122. for (var _i = 0, _a = this._requests; _i < _a.length; _i++) {
  92123. var request = _a[_i];
  92124. if (request._lengthComputable === undefined || request._loaded === undefined || request._total === undefined) {
  92125. return;
  92126. }
  92127. lengthComputable = lengthComputable && request._lengthComputable;
  92128. loaded += request._loaded;
  92129. total += request._total;
  92130. }
  92131. this._progressCallback(new BABYLON.SceneLoaderProgressEvent(lengthComputable, loaded, lengthComputable ? total : 0));
  92132. };
  92133. GLTFLoader._GetProperty = function (context, array, index) {
  92134. if (!array || index == undefined || !array[index]) {
  92135. throw new Error(context + ": Failed to find index " + index);
  92136. }
  92137. return array[index];
  92138. };
  92139. GLTFLoader._GetTextureWrapMode = function (context, mode) {
  92140. // Set defaults if undefined
  92141. mode = mode == undefined ? 10497 /* REPEAT */ : mode;
  92142. switch (mode) {
  92143. case 33071 /* CLAMP_TO_EDGE */: return BABYLON.Texture.CLAMP_ADDRESSMODE;
  92144. case 33648 /* MIRRORED_REPEAT */: return BABYLON.Texture.MIRROR_ADDRESSMODE;
  92145. case 10497 /* REPEAT */: return BABYLON.Texture.WRAP_ADDRESSMODE;
  92146. default:
  92147. BABYLON.Tools.Warn(context + ": Invalid texture wrap mode " + mode);
  92148. return BABYLON.Texture.WRAP_ADDRESSMODE;
  92149. }
  92150. };
  92151. GLTFLoader._GetTextureSamplingMode = function (context, magFilter, minFilter) {
  92152. // Set defaults if undefined
  92153. magFilter = magFilter == undefined ? 9729 /* LINEAR */ : magFilter;
  92154. minFilter = minFilter == undefined ? 9987 /* LINEAR_MIPMAP_LINEAR */ : minFilter;
  92155. if (magFilter === 9729 /* LINEAR */) {
  92156. switch (minFilter) {
  92157. case 9728 /* NEAREST */: return BABYLON.Texture.LINEAR_NEAREST;
  92158. case 9729 /* LINEAR */: return BABYLON.Texture.LINEAR_LINEAR;
  92159. case 9984 /* NEAREST_MIPMAP_NEAREST */: return BABYLON.Texture.LINEAR_NEAREST_MIPNEAREST;
  92160. case 9985 /* LINEAR_MIPMAP_NEAREST */: return BABYLON.Texture.LINEAR_LINEAR_MIPNEAREST;
  92161. case 9986 /* NEAREST_MIPMAP_LINEAR */: return BABYLON.Texture.LINEAR_NEAREST_MIPLINEAR;
  92162. case 9987 /* LINEAR_MIPMAP_LINEAR */: return BABYLON.Texture.LINEAR_LINEAR_MIPLINEAR;
  92163. default:
  92164. BABYLON.Tools.Warn(context + ": Invalid texture minification filter " + minFilter);
  92165. return BABYLON.Texture.LINEAR_LINEAR_MIPLINEAR;
  92166. }
  92167. }
  92168. else {
  92169. if (magFilter !== 9728 /* NEAREST */) {
  92170. BABYLON.Tools.Warn(context + ": Invalid texture magnification filter " + magFilter);
  92171. }
  92172. switch (minFilter) {
  92173. case 9728 /* NEAREST */: return BABYLON.Texture.NEAREST_NEAREST;
  92174. case 9729 /* LINEAR */: return BABYLON.Texture.NEAREST_LINEAR;
  92175. case 9984 /* NEAREST_MIPMAP_NEAREST */: return BABYLON.Texture.NEAREST_NEAREST_MIPNEAREST;
  92176. case 9985 /* LINEAR_MIPMAP_NEAREST */: return BABYLON.Texture.NEAREST_LINEAR_MIPNEAREST;
  92177. case 9986 /* NEAREST_MIPMAP_LINEAR */: return BABYLON.Texture.NEAREST_NEAREST_MIPLINEAR;
  92178. case 9987 /* LINEAR_MIPMAP_LINEAR */: return BABYLON.Texture.NEAREST_LINEAR_MIPLINEAR;
  92179. default:
  92180. BABYLON.Tools.Warn(context + ": Invalid texture minification filter " + minFilter);
  92181. return BABYLON.Texture.NEAREST_NEAREST_MIPNEAREST;
  92182. }
  92183. }
  92184. };
  92185. GLTFLoader._GetNumComponents = function (context, type) {
  92186. switch (type) {
  92187. case "SCALAR": return 1;
  92188. case "VEC2": return 2;
  92189. case "VEC3": return 3;
  92190. case "VEC4": return 4;
  92191. case "MAT2": return 4;
  92192. case "MAT3": return 9;
  92193. case "MAT4": return 16;
  92194. }
  92195. throw new Error(context + ": Invalid type " + type);
  92196. };
  92197. GLTFLoader._ValidateUri = function (uri) {
  92198. return (BABYLON.Tools.IsBase64(uri) || uri.indexOf("..") === -1);
  92199. };
  92200. GLTFLoader.prototype._compileMaterialsAsync = function () {
  92201. var promises = new Array();
  92202. if (this._gltf.materials) {
  92203. for (var _i = 0, _a = this._gltf.materials; _i < _a.length; _i++) {
  92204. var material = _a[_i];
  92205. var babylonMaterial = material._babylonMaterial;
  92206. var babylonMeshes = material._babylonMeshes;
  92207. if (babylonMaterial && babylonMeshes) {
  92208. for (var _b = 0, babylonMeshes_1 = babylonMeshes; _b < babylonMeshes_1.length; _b++) {
  92209. var babylonMesh = babylonMeshes_1[_b];
  92210. promises.push(babylonMaterial.forceCompilationAsync(babylonMesh));
  92211. if (this.useClipPlane) {
  92212. promises.push(babylonMaterial.forceCompilationAsync(babylonMesh, { clipPlane: true }));
  92213. }
  92214. }
  92215. }
  92216. }
  92217. }
  92218. return Promise.all(promises).then(function () { });
  92219. };
  92220. GLTFLoader.prototype._compileShadowGeneratorsAsync = function () {
  92221. var promises = new Array();
  92222. var lights = this._babylonScene.lights;
  92223. for (var _i = 0, lights_1 = lights; _i < lights_1.length; _i++) {
  92224. var light = lights_1[_i];
  92225. var generator = light.getShadowGenerator();
  92226. if (generator) {
  92227. promises.push(generator.forceCompilationAsync());
  92228. }
  92229. }
  92230. return Promise.all(promises).then(function () { });
  92231. };
  92232. GLTFLoader.prototype._clear = function () {
  92233. for (var _i = 0, _a = this._requests; _i < _a.length; _i++) {
  92234. var request = _a[_i];
  92235. request.abort();
  92236. }
  92237. this._requests.length = 0;
  92238. if (this._gltf && this._gltf.images) {
  92239. for (var _b = 0, _c = this._gltf.images; _b < _c.length; _b++) {
  92240. var image = _c[_b];
  92241. if (image._objectURL) {
  92242. image._objectURL.then(function (value) {
  92243. URL.revokeObjectURL(value);
  92244. });
  92245. image._objectURL = undefined;
  92246. }
  92247. }
  92248. }
  92249. delete this._gltf;
  92250. delete this._babylonScene;
  92251. this._completePromises.length = 0;
  92252. this._extensions = {};
  92253. delete this._rootBabylonMesh;
  92254. delete this._progressCallback;
  92255. this.onMeshLoadedObservable.clear();
  92256. this.onTextureLoadedObservable.clear();
  92257. this.onMaterialLoadedObservable.clear();
  92258. };
  92259. GLTFLoader.prototype._applyExtensions = function (actionAsync) {
  92260. for (var _i = 0, _a = GLTFLoader._Names; _i < _a.length; _i++) {
  92261. var name_2 = _a[_i];
  92262. var extension = this._extensions[name_2];
  92263. if (extension.enabled) {
  92264. var promise = actionAsync(extension);
  92265. if (promise) {
  92266. return promise;
  92267. }
  92268. }
  92269. }
  92270. return null;
  92271. };
  92272. GLTFLoader._Names = new Array();
  92273. GLTFLoader._Factories = {};
  92274. return GLTFLoader;
  92275. }());
  92276. GLTF2.GLTFLoader = GLTFLoader;
  92277. BABYLON.GLTFFileLoader.CreateGLTFLoaderV2 = function () { return new GLTFLoader(); };
  92278. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  92279. })(BABYLON || (BABYLON = {}));
  92280. //# sourceMappingURL=babylon.glTFLoader.js.map
  92281. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  92282. var BABYLON;
  92283. (function (BABYLON) {
  92284. var GLTF2;
  92285. (function (GLTF2) {
  92286. var GLTFLoaderExtension = /** @class */ (function () {
  92287. function GLTFLoaderExtension(loader) {
  92288. this.enabled = true;
  92289. this._loader = loader;
  92290. }
  92291. // #region Overridable Methods
  92292. /** Override this method to modify the default behavior for loading scenes. */
  92293. GLTFLoaderExtension.prototype._loadSceneAsync = function (context, node) { return null; };
  92294. /** Override this method to modify the default behavior for loading nodes. */
  92295. GLTFLoaderExtension.prototype._loadNodeAsync = function (context, node) { return null; };
  92296. /** Override this method to modify the default behavior for loading materials. */
  92297. GLTFLoaderExtension.prototype._loadMaterialAsync = function (context, material, babylonMesh) { return null; };
  92298. /** Override this method to modify the default behavior for loading uris. */
  92299. GLTFLoaderExtension.prototype._loadUriAsync = function (context, uri) { return null; };
  92300. // #endregion
  92301. /** Helper method called by a loader extension to load an glTF extension. */
  92302. GLTFLoaderExtension.prototype._loadExtensionAsync = function (context, property, actionAsync) {
  92303. var _this = this;
  92304. if (!property.extensions) {
  92305. return null;
  92306. }
  92307. var extensions = property.extensions;
  92308. var extension = extensions[this.name];
  92309. if (!extension) {
  92310. return null;
  92311. }
  92312. // Clear out the extension before executing the action to avoid recursing into the same property.
  92313. delete extensions[this.name];
  92314. return actionAsync(context + "/extensions/" + this.name, extension).then(function () {
  92315. // Restore the extension after completing the action.
  92316. extensions[_this.name] = extension;
  92317. });
  92318. };
  92319. /** Helper method called by the loader to allow extensions to override loading scenes. */
  92320. GLTFLoaderExtension._LoadSceneAsync = function (loader, context, scene) {
  92321. return loader._applyExtensions(function (extension) { return extension._loadSceneAsync(context, scene); });
  92322. };
  92323. /** Helper method called by the loader to allow extensions to override loading nodes. */
  92324. GLTFLoaderExtension._LoadNodeAsync = function (loader, context, node) {
  92325. return loader._applyExtensions(function (extension) { return extension._loadNodeAsync(context, node); });
  92326. };
  92327. /** Helper method called by the loader to allow extensions to override loading materials. */
  92328. GLTFLoaderExtension._LoadMaterialAsync = function (loader, context, material, babylonMesh) {
  92329. return loader._applyExtensions(function (extension) { return extension._loadMaterialAsync(context, material, babylonMesh); });
  92330. };
  92331. /** Helper method called by the loader to allow extensions to override loading uris. */
  92332. GLTFLoaderExtension._LoadUriAsync = function (loader, context, uri) {
  92333. return loader._applyExtensions(function (extension) { return extension._loadUriAsync(context, uri); });
  92334. };
  92335. return GLTFLoaderExtension;
  92336. }());
  92337. GLTF2.GLTFLoaderExtension = GLTFLoaderExtension;
  92338. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  92339. })(BABYLON || (BABYLON = {}));
  92340. //# sourceMappingURL=babylon.glTFLoaderExtension.js.map
  92341. /// <reference path="../../../../../dist/preview release/babylon.d.ts"/>
  92342. var BABYLON;
  92343. (function (BABYLON) {
  92344. var GLTF2;
  92345. (function (GLTF2) {
  92346. var Extensions;
  92347. (function (Extensions) {
  92348. // https://github.com/sbtron/glTF/tree/MSFT_lod/extensions/Vendor/MSFT_lod
  92349. var NAME = "MSFT_lod";
  92350. var MSFT_lod = /** @class */ (function (_super) {
  92351. __extends(MSFT_lod, _super);
  92352. function MSFT_lod() {
  92353. var _this = _super !== null && _super.apply(this, arguments) || this;
  92354. _this.name = NAME;
  92355. /**
  92356. * Maximum number of LODs to load, starting from the lowest LOD.
  92357. */
  92358. _this.maxLODsToLoad = Number.MAX_VALUE;
  92359. _this._loadingNodeLOD = null;
  92360. _this._loadNodeSignals = {};
  92361. _this._loadingMaterialLOD = null;
  92362. _this._loadMaterialSignals = {};
  92363. return _this;
  92364. }
  92365. MSFT_lod.prototype._loadNodeAsync = function (context, node) {
  92366. var _this = this;
  92367. return this._loadExtensionAsync(context, node, function (context, extension) {
  92368. var firstPromise;
  92369. var nodeLODs = _this._getLODs(context, node, _this._loader._gltf.nodes, extension.ids);
  92370. var _loop_1 = function (indexLOD) {
  92371. var nodeLOD = nodeLODs[indexLOD];
  92372. if (indexLOD !== 0) {
  92373. _this._loadingNodeLOD = nodeLOD;
  92374. _this._loadNodeSignals[nodeLOD._index] = new BABYLON.Deferred();
  92375. }
  92376. var promise = _this._loader._loadNodeAsync("#/nodes/" + nodeLOD._index, nodeLOD).then(function () {
  92377. if (indexLOD !== 0) {
  92378. var previousNodeLOD = nodeLODs[indexLOD - 1];
  92379. previousNodeLOD._babylonMesh.setEnabled(false);
  92380. }
  92381. if (indexLOD !== nodeLODs.length - 1) {
  92382. var nodeIndex = nodeLODs[indexLOD + 1]._index;
  92383. _this._loadNodeSignals[nodeIndex].resolve();
  92384. delete _this._loadNodeSignals[nodeIndex];
  92385. }
  92386. });
  92387. if (indexLOD === 0) {
  92388. firstPromise = promise;
  92389. }
  92390. else {
  92391. _this._loader._completePromises.push(promise);
  92392. _this._loadingNodeLOD = null;
  92393. }
  92394. };
  92395. for (var indexLOD = 0; indexLOD < nodeLODs.length; indexLOD++) {
  92396. _loop_1(indexLOD);
  92397. }
  92398. return firstPromise;
  92399. });
  92400. };
  92401. MSFT_lod.prototype._loadMaterialAsync = function (context, material, babylonMesh) {
  92402. var _this = this;
  92403. // Don't load material LODs if already loading a node LOD.
  92404. if (this._loadingNodeLOD) {
  92405. return null;
  92406. }
  92407. return this._loadExtensionAsync(context, material, function (context, extension) {
  92408. var firstPromise;
  92409. var materialLODs = _this._getLODs(context, material, _this._loader._gltf.materials, extension.ids);
  92410. var _loop_2 = function (indexLOD) {
  92411. var materialLOD = materialLODs[indexLOD];
  92412. if (indexLOD !== 0) {
  92413. _this._loadingMaterialLOD = materialLOD;
  92414. _this._loadMaterialSignals[materialLOD._index] = new BABYLON.Deferred();
  92415. }
  92416. var promise = _this._loader._loadMaterialAsync("#/materials/" + materialLOD._index, materialLOD, babylonMesh).then(function () {
  92417. if (indexLOD !== materialLODs.length - 1) {
  92418. var materialIndex = materialLODs[indexLOD + 1]._index;
  92419. _this._loadMaterialSignals[materialIndex].resolve();
  92420. delete _this._loadMaterialSignals[materialIndex];
  92421. }
  92422. });
  92423. if (indexLOD === 0) {
  92424. firstPromise = promise;
  92425. }
  92426. else {
  92427. _this._loader._completePromises.push(promise);
  92428. _this._loadingMaterialLOD = null;
  92429. }
  92430. };
  92431. for (var indexLOD = 0; indexLOD < materialLODs.length; indexLOD++) {
  92432. _loop_2(indexLOD);
  92433. }
  92434. return firstPromise;
  92435. });
  92436. };
  92437. MSFT_lod.prototype._loadUriAsync = function (context, uri) {
  92438. var _this = this;
  92439. // Defer the loading of uris if loading a material or node LOD.
  92440. if (this._loadingMaterialLOD) {
  92441. var index = this._loadingMaterialLOD._index;
  92442. return this._loadMaterialSignals[index].promise.then(function () {
  92443. return _this._loader._loadUriAsync(context, uri);
  92444. });
  92445. }
  92446. else if (this._loadingNodeLOD) {
  92447. var index = this._loadingNodeLOD._index;
  92448. return this._loadNodeSignals[index].promise.then(function () {
  92449. return _this._loader._loadUriAsync(context, uri);
  92450. });
  92451. }
  92452. return null;
  92453. };
  92454. /**
  92455. * Gets an array of LOD properties from lowest to highest.
  92456. */
  92457. MSFT_lod.prototype._getLODs = function (context, property, array, ids) {
  92458. if (this.maxLODsToLoad <= 0) {
  92459. throw new Error("maxLODsToLoad must be greater than zero");
  92460. }
  92461. var properties = new Array();
  92462. for (var i = ids.length - 1; i >= 0; i--) {
  92463. properties.push(GLTF2.GLTFLoader._GetProperty(context + "/ids/" + ids[i], array, ids[i]));
  92464. if (properties.length === this.maxLODsToLoad) {
  92465. return properties;
  92466. }
  92467. }
  92468. properties.push(property);
  92469. return properties;
  92470. };
  92471. return MSFT_lod;
  92472. }(GLTF2.GLTFLoaderExtension));
  92473. Extensions.MSFT_lod = MSFT_lod;
  92474. GLTF2.GLTFLoader._Register(NAME, function (loader) { return new MSFT_lod(loader); });
  92475. })(Extensions = GLTF2.Extensions || (GLTF2.Extensions = {}));
  92476. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  92477. })(BABYLON || (BABYLON = {}));
  92478. //# sourceMappingURL=MSFT_lod.js.map
  92479. /// <reference path="../../../../../dist/preview release/babylon.d.ts"/>
  92480. var BABYLON;
  92481. (function (BABYLON) {
  92482. var GLTF2;
  92483. (function (GLTF2) {
  92484. var Extensions;
  92485. (function (Extensions) {
  92486. // https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_materials_pbrSpecularGlossiness
  92487. var NAME = "KHR_materials_pbrSpecularGlossiness";
  92488. var KHR_materials_pbrSpecularGlossiness = /** @class */ (function (_super) {
  92489. __extends(KHR_materials_pbrSpecularGlossiness, _super);
  92490. function KHR_materials_pbrSpecularGlossiness() {
  92491. var _this = _super !== null && _super.apply(this, arguments) || this;
  92492. _this.name = NAME;
  92493. return _this;
  92494. }
  92495. KHR_materials_pbrSpecularGlossiness.prototype._loadMaterialAsync = function (context, material, babylonMesh) {
  92496. var _this = this;
  92497. return this._loadExtensionAsync(context, material, function (context, extension) {
  92498. material._babylonMeshes = material._babylonMeshes || [];
  92499. material._babylonMeshes.push(babylonMesh);
  92500. if (material._loaded) {
  92501. babylonMesh.material = material._babylonMaterial;
  92502. return material._loaded;
  92503. }
  92504. var promises = new Array();
  92505. var babylonMaterial = _this._loader._createMaterial(material);
  92506. material._babylonMaterial = babylonMaterial;
  92507. promises.push(_this._loader._loadMaterialBasePropertiesAsync(context, material));
  92508. promises.push(_this._loadSpecularGlossinessPropertiesAsync(_this._loader, context, material, extension));
  92509. _this._loader.onMaterialLoadedObservable.notifyObservers(babylonMaterial);
  92510. babylonMesh.material = babylonMaterial;
  92511. return (material._loaded = Promise.all(promises).then(function () { }));
  92512. });
  92513. };
  92514. KHR_materials_pbrSpecularGlossiness.prototype._loadSpecularGlossinessPropertiesAsync = function (loader, context, material, properties) {
  92515. var promises = new Array();
  92516. var babylonMaterial = material._babylonMaterial;
  92517. if (properties.diffuseFactor) {
  92518. babylonMaterial.albedoColor = BABYLON.Color3.FromArray(properties.diffuseFactor);
  92519. babylonMaterial.alpha = properties.diffuseFactor[3];
  92520. }
  92521. else {
  92522. babylonMaterial.albedoColor = BABYLON.Color3.White();
  92523. }
  92524. babylonMaterial.reflectivityColor = properties.specularFactor ? BABYLON.Color3.FromArray(properties.specularFactor) : BABYLON.Color3.White();
  92525. babylonMaterial.microSurface = properties.glossinessFactor == undefined ? 1 : properties.glossinessFactor;
  92526. if (properties.diffuseTexture) {
  92527. promises.push(loader._loadTextureAsync(context + "/diffuseTexture", properties.diffuseTexture, function (texture) {
  92528. babylonMaterial.albedoTexture = texture;
  92529. }));
  92530. }
  92531. if (properties.specularGlossinessTexture) {
  92532. promises.push(loader._loadTextureAsync(context + "/specularGlossinessTexture", properties.specularGlossinessTexture, function (texture) {
  92533. babylonMaterial.reflectivityTexture = texture;
  92534. }));
  92535. babylonMaterial.reflectivityTexture.hasAlpha = true;
  92536. babylonMaterial.useMicroSurfaceFromReflectivityMapAlpha = true;
  92537. }
  92538. loader._loadMaterialAlphaProperties(context, material);
  92539. return Promise.all(promises).then(function () { });
  92540. };
  92541. return KHR_materials_pbrSpecularGlossiness;
  92542. }(GLTF2.GLTFLoaderExtension));
  92543. Extensions.KHR_materials_pbrSpecularGlossiness = KHR_materials_pbrSpecularGlossiness;
  92544. GLTF2.GLTFLoader._Register(NAME, function (loader) { return new KHR_materials_pbrSpecularGlossiness(loader); });
  92545. })(Extensions = GLTF2.Extensions || (GLTF2.Extensions = {}));
  92546. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  92547. })(BABYLON || (BABYLON = {}));
  92548. //# sourceMappingURL=KHR_materials_pbrSpecularGlossiness.js.map
  92549. /// <reference path="../../../../../dist/preview release/babylon.d.ts"/>
  92550. var BABYLON;
  92551. (function (BABYLON) {
  92552. var GLTF2;
  92553. (function (GLTF2) {
  92554. var Extensions;
  92555. (function (Extensions) {
  92556. // https://github.com/MiiBond/glTF/tree/khr_lights_v1/extensions/Khronos/KHR_lights
  92557. var NAME = "KHR_lights";
  92558. var LightType;
  92559. (function (LightType) {
  92560. LightType["AMBIENT"] = "ambient";
  92561. LightType["DIRECTIONAL"] = "directional";
  92562. LightType["POINT"] = "point";
  92563. LightType["SPOT"] = "spot";
  92564. })(LightType || (LightType = {}));
  92565. var KHR_lights = /** @class */ (function (_super) {
  92566. __extends(KHR_lights, _super);
  92567. function KHR_lights() {
  92568. var _this = _super !== null && _super.apply(this, arguments) || this;
  92569. _this.name = NAME;
  92570. return _this;
  92571. }
  92572. KHR_lights.prototype._loadSceneAsync = function (context, scene) {
  92573. var _this = this;
  92574. return this._loadExtensionAsync(context, scene, function (context, extension) {
  92575. var promise = _this._loader._loadSceneAsync(context, scene);
  92576. var light = GLTF2.GLTFLoader._GetProperty(context, _this._lights, extension.light);
  92577. if (light.type !== LightType.AMBIENT) {
  92578. throw new Error(context + ": Only ambient lights are allowed on a scene");
  92579. }
  92580. _this._loader._babylonScene.ambientColor = light.color ? BABYLON.Color3.FromArray(light.color) : BABYLON.Color3.Black();
  92581. return promise;
  92582. });
  92583. };
  92584. KHR_lights.prototype._loadNodeAsync = function (context, node) {
  92585. var _this = this;
  92586. return this._loadExtensionAsync(context, node, function (context, extension) {
  92587. var promise = _this._loader._loadNodeAsync(context, node);
  92588. var babylonLight;
  92589. var light = GLTF2.GLTFLoader._GetProperty(context, _this._lights, extension.light);
  92590. var name = node._babylonMesh.name;
  92591. switch (light.type) {
  92592. case LightType.AMBIENT: {
  92593. throw new Error(context + ": Ambient lights are not allowed on a node");
  92594. }
  92595. case LightType.DIRECTIONAL: {
  92596. babylonLight = new BABYLON.DirectionalLight(name, BABYLON.Vector3.Forward(), _this._loader._babylonScene);
  92597. break;
  92598. }
  92599. case LightType.POINT: {
  92600. babylonLight = new BABYLON.PointLight(name, BABYLON.Vector3.Zero(), _this._loader._babylonScene);
  92601. break;
  92602. }
  92603. case LightType.SPOT: {
  92604. var spotLight = light;
  92605. // TODO: support inner and outer cone angles
  92606. //const innerConeAngle = spotLight.innerConeAngle || 0;
  92607. var outerConeAngle = spotLight.outerConeAngle || Math.PI / 4;
  92608. babylonLight = new BABYLON.SpotLight(name, BABYLON.Vector3.Zero(), BABYLON.Vector3.Forward(), outerConeAngle, 2, _this._loader._babylonScene);
  92609. break;
  92610. }
  92611. default: {
  92612. throw new Error(context + ": Invalid light type " + light.type);
  92613. }
  92614. }
  92615. babylonLight.diffuse = light.color ? BABYLON.Color3.FromArray(light.color) : BABYLON.Color3.White();
  92616. babylonLight.intensity = light.intensity == undefined ? 1 : light.intensity;
  92617. babylonLight.parent = node._babylonMesh;
  92618. return promise;
  92619. });
  92620. };
  92621. Object.defineProperty(KHR_lights.prototype, "_lights", {
  92622. get: function () {
  92623. var extensions = this._loader._gltf.extensions;
  92624. if (!extensions || !extensions[this.name]) {
  92625. throw new Error("#/extensions: " + this.name + " not found");
  92626. }
  92627. var extension = extensions[this.name];
  92628. return extension.lights;
  92629. },
  92630. enumerable: true,
  92631. configurable: true
  92632. });
  92633. return KHR_lights;
  92634. }(GLTF2.GLTFLoaderExtension));
  92635. Extensions.KHR_lights = KHR_lights;
  92636. GLTF2.GLTFLoader._Register(NAME, function (loader) { return new KHR_lights(loader); });
  92637. })(Extensions = GLTF2.Extensions || (GLTF2.Extensions = {}));
  92638. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  92639. })(BABYLON || (BABYLON = {}));
  92640. //# sourceMappingURL=KHR_lights.js.map
  92641. var globalObject = (typeof global !== 'undefined') ? global : ((typeof window !== 'undefined') ? window : this);
  92642. globalObject["BABYLON"] = BABYLON;
  92643. var EffectFallbacks = BABYLON.EffectFallbacks;var EffectCreationOptions = BABYLON.EffectCreationOptions;var Effect = BABYLON.Effect;var KeyboardEventTypes = BABYLON.KeyboardEventTypes;var KeyboardInfo = BABYLON.KeyboardInfo;var KeyboardInfoPre = BABYLON.KeyboardInfoPre;var PointerEventTypes = BABYLON.PointerEventTypes;var PointerInfoBase = BABYLON.PointerInfoBase;var PointerInfoPre = BABYLON.PointerInfoPre;var PointerInfo = BABYLON.PointerInfo;var Color3 = BABYLON.Color3;var Color4 = BABYLON.Color4;var Vector2 = BABYLON.Vector2;var Vector3 = BABYLON.Vector3;var Vector4 = BABYLON.Vector4;var Size = BABYLON.Size;var Quaternion = BABYLON.Quaternion;var Matrix = BABYLON.Matrix;var Plane = BABYLON.Plane;var Viewport = BABYLON.Viewport;var Frustum = BABYLON.Frustum;var Axis = BABYLON.Axis;var BezierCurve = BABYLON.BezierCurve;var Angle = BABYLON.Angle;var Arc2 = BABYLON.Arc2;var Path2 = BABYLON.Path2;var Path3D = BABYLON.Path3D;var Curve3 = BABYLON.Curve3;var PositionNormalVertex = BABYLON.PositionNormalVertex;var PositionNormalTextureVertex = BABYLON.PositionNormalTextureVertex;var Tmp = BABYLON.Tmp;var Scalar = BABYLON.Scalar;var expandToProperty = BABYLON.expandToProperty;var serialize = BABYLON.serialize;var serializeAsTexture = BABYLON.serializeAsTexture;var serializeAsColor3 = BABYLON.serializeAsColor3;var serializeAsFresnelParameters = BABYLON.serializeAsFresnelParameters;var serializeAsVector2 = BABYLON.serializeAsVector2;var serializeAsVector3 = BABYLON.serializeAsVector3;var serializeAsMeshReference = BABYLON.serializeAsMeshReference;var serializeAsColorCurves = BABYLON.serializeAsColorCurves;var serializeAsColor4 = BABYLON.serializeAsColor4;var serializeAsImageProcessingConfiguration = BABYLON.serializeAsImageProcessingConfiguration;var serializeAsQuaternion = BABYLON.serializeAsQuaternion;var SerializationHelper = BABYLON.SerializationHelper;var Deferred = BABYLON.Deferred;var EventState = BABYLON.EventState;var Observer = BABYLON.Observer;var MultiObserver = BABYLON.MultiObserver;var Observable = BABYLON.Observable;var SmartArray = BABYLON.SmartArray;var SmartArrayNoDuplicate = BABYLON.SmartArrayNoDuplicate;var LoadFileError = BABYLON.LoadFileError;var RetryStrategy = BABYLON.RetryStrategy;var Tools = BABYLON.Tools;var PerfCounter = BABYLON.PerfCounter;var className = BABYLON.className;var AsyncLoop = BABYLON.AsyncLoop;var PromisePolyfill = BABYLON.PromisePolyfill;var _AlphaState = BABYLON._AlphaState;var _DepthCullingState = BABYLON._DepthCullingState;var _StencilState = BABYLON._StencilState;var InstancingAttributeInfo = BABYLON.InstancingAttributeInfo;var RenderTargetCreationOptions = BABYLON.RenderTargetCreationOptions;var EngineCapabilities = BABYLON.EngineCapabilities;var Engine = BABYLON.Engine;var Node = BABYLON.Node;var BoundingSphere = BABYLON.BoundingSphere;var BoundingBox = BABYLON.BoundingBox;var BoundingInfo = BABYLON.BoundingInfo;var TransformNode = BABYLON.TransformNode;var AbstractMesh = BABYLON.AbstractMesh;var Light = BABYLON.Light;var Camera = BABYLON.Camera;var RenderingManager = BABYLON.RenderingManager;var RenderingGroup = BABYLON.RenderingGroup;var RenderingGroupInfo = BABYLON.RenderingGroupInfo;var Scene = BABYLON.Scene;var KeepAssets = BABYLON.KeepAssets;var AssetContainer = BABYLON.AssetContainer;var Buffer = BABYLON.Buffer;var VertexBuffer = BABYLON.VertexBuffer;var DummyInternalTextureTracker = BABYLON.DummyInternalTextureTracker;var InternalTexture = BABYLON.InternalTexture;var BaseTexture = BABYLON.BaseTexture;var Texture = BABYLON.Texture;var _InstancesBatch = BABYLON._InstancesBatch;var Mesh = BABYLON.Mesh;var BaseSubMesh = BABYLON.BaseSubMesh;var SubMesh = BABYLON.SubMesh;var MaterialDefines = BABYLON.MaterialDefines;var Material = BABYLON.Material;var UniformBuffer = BABYLON.UniformBuffer;var VertexData = BABYLON.VertexData;var Geometry = BABYLON.Geometry;var _PrimitiveGeometry = BABYLON._PrimitiveGeometry;var RibbonGeometry = BABYLON.RibbonGeometry;var BoxGeometry = BABYLON.BoxGeometry;var SphereGeometry = BABYLON.SphereGeometry;var DiscGeometry = BABYLON.DiscGeometry;var CylinderGeometry = BABYLON.CylinderGeometry;var TorusGeometry = BABYLON.TorusGeometry;var GroundGeometry = BABYLON.GroundGeometry;var TiledGroundGeometry = BABYLON.TiledGroundGeometry;var PlaneGeometry = BABYLON.PlaneGeometry;var TorusKnotGeometry = BABYLON.TorusKnotGeometry;var PostProcessManager = BABYLON.PostProcessManager;var PerformanceMonitor = BABYLON.PerformanceMonitor;var RollingAverage = BABYLON.RollingAverage;var ImageProcessingConfiguration = BABYLON.ImageProcessingConfiguration;var ColorGradingTexture = BABYLON.ColorGradingTexture;var ColorCurves = BABYLON.ColorCurves;var MaterialHelper = BABYLON.MaterialHelper;var PushMaterial = BABYLON.PushMaterial;var StandardMaterialDefines = BABYLON.StandardMaterialDefines;var StandardMaterial = BABYLON.StandardMaterial;var PBRBaseMaterial = BABYLON.PBRBaseMaterial;var PBRBaseSimpleMaterial = BABYLON.PBRBaseSimpleMaterial;var PBRMaterial = BABYLON.PBRMaterial;var PBRMetallicRoughnessMaterial = BABYLON.PBRMetallicRoughnessMaterial;var PBRSpecularGlossinessMaterial = BABYLON.PBRSpecularGlossinessMaterial;var CameraInputsManager = BABYLON.CameraInputsManager;var TargetCamera = BABYLON.TargetCamera;var FreeCameraMouseInput = BABYLON.FreeCameraMouseInput;var FreeCameraKeyboardMoveInput = BABYLON.FreeCameraKeyboardMoveInput;var FreeCameraInputsManager = BABYLON.FreeCameraInputsManager;var FreeCamera = BABYLON.FreeCamera;var ArcRotateCameraKeyboardMoveInput = BABYLON.ArcRotateCameraKeyboardMoveInput;var ArcRotateCameraMouseWheelInput = BABYLON.ArcRotateCameraMouseWheelInput;var ArcRotateCameraPointersInput = BABYLON.ArcRotateCameraPointersInput;var ArcRotateCameraInputsManager = BABYLON.ArcRotateCameraInputsManager;var ArcRotateCamera = BABYLON.ArcRotateCamera;var HemisphericLight = BABYLON.HemisphericLight;var ShadowLight = BABYLON.ShadowLight;var PointLight = BABYLON.PointLight;var DirectionalLight = BABYLON.DirectionalLight;var SpotLight = BABYLON.SpotLight;var AnimationRange = BABYLON.AnimationRange;var AnimationEvent = BABYLON.AnimationEvent;var PathCursor = BABYLON.PathCursor;var Animation = BABYLON.Animation;var TargetedAnimation = BABYLON.TargetedAnimation;var AnimationGroup = BABYLON.AnimationGroup;var RuntimeAnimation = BABYLON.RuntimeAnimation;var Animatable = BABYLON.Animatable;var EasingFunction = BABYLON.EasingFunction;var CircleEase = BABYLON.CircleEase;var BackEase = BABYLON.BackEase;var BounceEase = BABYLON.BounceEase;var CubicEase = BABYLON.CubicEase;var ElasticEase = BABYLON.ElasticEase;var ExponentialEase = BABYLON.ExponentialEase;var PowerEase = BABYLON.PowerEase;var QuadraticEase = BABYLON.QuadraticEase;var QuarticEase = BABYLON.QuarticEase;var QuinticEase = BABYLON.QuinticEase;var SineEase = BABYLON.SineEase;var BezierCurveEase = BABYLON.BezierCurveEase;var Condition = BABYLON.Condition;var ValueCondition = BABYLON.ValueCondition;var PredicateCondition = BABYLON.PredicateCondition;var StateCondition = BABYLON.StateCondition;var Action = BABYLON.Action;var ActionEvent = BABYLON.ActionEvent;var ActionManager = BABYLON.ActionManager;var InterpolateValueAction = BABYLON.InterpolateValueAction;var SwitchBooleanAction = BABYLON.SwitchBooleanAction;var SetStateAction = BABYLON.SetStateAction;var SetValueAction = BABYLON.SetValueAction;var IncrementValueAction = BABYLON.IncrementValueAction;var PlayAnimationAction = BABYLON.PlayAnimationAction;var StopAnimationAction = BABYLON.StopAnimationAction;var DoNothingAction = BABYLON.DoNothingAction;var CombineAction = BABYLON.CombineAction;var ExecuteCodeAction = BABYLON.ExecuteCodeAction;var SetParentAction = BABYLON.SetParentAction;var PlaySoundAction = BABYLON.PlaySoundAction;var StopSoundAction = BABYLON.StopSoundAction;var SpriteManager = BABYLON.SpriteManager;var Sprite = BABYLON.Sprite;var IntersectionInfo = BABYLON.IntersectionInfo;var PickingInfo = BABYLON.PickingInfo;var Ray = BABYLON.Ray;var Collider = BABYLON.Collider;var CollisionCoordinatorWorker = BABYLON.CollisionCoordinatorWorker;var CollisionCoordinatorLegacy = BABYLON.CollisionCoordinatorLegacy;var Particle = BABYLON.Particle;var ParticleSystem = BABYLON.ParticleSystem;var BoxParticleEmitter = BABYLON.BoxParticleEmitter;var ConeParticleEmitter = BABYLON.ConeParticleEmitter;var SphereParticleEmitter = BABYLON.SphereParticleEmitter;var SphereDirectedParticleEmitter = BABYLON.SphereDirectedParticleEmitter;var SolidParticle = BABYLON.SolidParticle;var ModelShape = BABYLON.ModelShape;var DepthSortedParticle = BABYLON.DepthSortedParticle;var SolidParticleSystem = BABYLON.SolidParticleSystem;var ShaderMaterial = BABYLON.ShaderMaterial;var GroundMesh = BABYLON.GroundMesh;var InstancedMesh = BABYLON.InstancedMesh;var LinesMesh = BABYLON.LinesMesh;var MeshBuilder = BABYLON.MeshBuilder;var AudioEngine = BABYLON.AudioEngine;var Sound = BABYLON.Sound;var SoundTrack = BABYLON.SoundTrack;var Analyser = BABYLON.Analyser;var CubeTexture = BABYLON.CubeTexture;var RenderTargetTexture = BABYLON.RenderTargetTexture;var MultiRenderTarget = BABYLON.MultiRenderTarget;var MirrorTexture = BABYLON.MirrorTexture;var RefractionTexture = BABYLON.RefractionTexture;var DynamicTexture = BABYLON.DynamicTexture;var VideoTexture = BABYLON.VideoTexture;var RawTexture = BABYLON.RawTexture;var PostProcess = BABYLON.PostProcess;var PassPostProcess = BABYLON.PassPostProcess;var ShadowGenerator = BABYLON.ShadowGenerator;var DefaultLoadingScreen = BABYLON.DefaultLoadingScreen;var SceneLoaderProgressEvent = BABYLON.SceneLoaderProgressEvent;var SceneLoader = BABYLON.SceneLoader;var FilesInput = BABYLON.FilesInput;var StringDictionary = BABYLON.StringDictionary;var Tags = BABYLON.Tags;var AndOrNotEvaluator = BABYLON.AndOrNotEvaluator;var Database = BABYLON.Database;var FresnelParameters = BABYLON.FresnelParameters;var MultiMaterial = BABYLON.MultiMaterial;var FreeCameraTouchInput = BABYLON.FreeCameraTouchInput;var TouchCamera = BABYLON.TouchCamera;var ProceduralTexture = BABYLON.ProceduralTexture;var CustomProceduralTexture = BABYLON.CustomProceduralTexture;var FreeCameraGamepadInput = BABYLON.FreeCameraGamepadInput;var ArcRotateCameraGamepadInput = BABYLON.ArcRotateCameraGamepadInput;var GamepadManager = BABYLON.GamepadManager;var StickValues = BABYLON.StickValues;var Gamepad = BABYLON.Gamepad;var GenericPad = BABYLON.GenericPad;var Xbox360Pad = BABYLON.Xbox360Pad;var PoseEnabledControllerHelper = BABYLON.PoseEnabledControllerHelper;var PoseEnabledController = BABYLON.PoseEnabledController;var WebVRController = BABYLON.WebVRController;var OculusTouchController = BABYLON.OculusTouchController;var ViveController = BABYLON.ViveController;var GenericController = BABYLON.GenericController;var WindowsMotionController = BABYLON.WindowsMotionController;var GearVRController = BABYLON.GearVRController;var FollowCamera = BABYLON.FollowCamera;var ArcFollowCamera = BABYLON.ArcFollowCamera;var UniversalCamera = BABYLON.UniversalCamera;var GamepadCamera = BABYLON.GamepadCamera;var PostProcessRenderPipelineManager = BABYLON.PostProcessRenderPipelineManager;var PostProcessRenderEffect = BABYLON.PostProcessRenderEffect;var PostProcessRenderPipeline = BABYLON.PostProcessRenderPipeline;var DepthRenderer = BABYLON.DepthRenderer;var SSAORenderingPipeline = BABYLON.SSAORenderingPipeline;var SSAO2RenderingPipeline = BABYLON.SSAO2RenderingPipeline;var LensRenderingPipeline = BABYLON.LensRenderingPipeline;var StandardRenderingPipeline = BABYLON.StandardRenderingPipeline;var FxaaPostProcess = BABYLON.FxaaPostProcess;var CircleOfConfusionPostProcess = BABYLON.CircleOfConfusionPostProcess;var DepthOfFieldMergePostProcess = BABYLON.DepthOfFieldMergePostProcess;var DepthOfFieldEffect = BABYLON.DepthOfFieldEffect;var DefaultRenderingPipeline = BABYLON.DefaultRenderingPipeline;var GeometryBufferRenderer = BABYLON.GeometryBufferRenderer;var RefractionPostProcess = BABYLON.RefractionPostProcess;var BlackAndWhitePostProcess = BABYLON.BlackAndWhitePostProcess;var ConvolutionPostProcess = BABYLON.ConvolutionPostProcess;var FilterPostProcess = BABYLON.FilterPostProcess;var VolumetricLightScatteringPostProcess = BABYLON.VolumetricLightScatteringPostProcess;var ColorCorrectionPostProcess = BABYLON.ColorCorrectionPostProcess;var TonemapPostProcess = BABYLON.TonemapPostProcess;var DisplayPassPostProcess = BABYLON.DisplayPassPostProcess;var HighlightsPostProcess = BABYLON.HighlightsPostProcess;var ImageProcessingPostProcess = BABYLON.ImageProcessingPostProcess;var BlurPostProcess = BABYLON.BlurPostProcess;var Bone = BABYLON.Bone;var BoneIKController = BABYLON.BoneIKController;var BoneLookController = BABYLON.BoneLookController;var Skeleton = BABYLON.Skeleton;var SphericalPolynomial = BABYLON.SphericalPolynomial;var SphericalHarmonics = BABYLON.SphericalHarmonics;var CubeMapToSphericalPolynomialTools = BABYLON.CubeMapToSphericalPolynomialTools;var PanoramaToCubeMapTools = BABYLON.PanoramaToCubeMapTools;var HDRTools = BABYLON.HDRTools;var HDRCubeTexture = BABYLON.HDRCubeTexture;var Polygon = BABYLON.Polygon;var PolygonMeshBuilder = BABYLON.PolygonMeshBuilder;var CSG = BABYLON.CSG;var LensFlare = BABYLON.LensFlare;var LensFlareSystem = BABYLON.LensFlareSystem;var PhysicsJoint = BABYLON.PhysicsJoint;var DistanceJoint = BABYLON.DistanceJoint;var MotorEnabledJoint = BABYLON.MotorEnabledJoint;var HingeJoint = BABYLON.HingeJoint;var Hinge2Joint = BABYLON.Hinge2Joint;var PhysicsImpostor = BABYLON.PhysicsImpostor;var PhysicsEngine = BABYLON.PhysicsEngine;var PhysicsHelper = BABYLON.PhysicsHelper;var PhysicsRadialExplosionEvent = BABYLON.PhysicsRadialExplosionEvent;var PhysicsGravitationalFieldEvent = BABYLON.PhysicsGravitationalFieldEvent;var PhysicsUpdraftEvent = BABYLON.PhysicsUpdraftEvent;var PhysicsVortexEvent = BABYLON.PhysicsVortexEvent;var CannonJSPlugin = BABYLON.CannonJSPlugin;var OimoJSPlugin = BABYLON.OimoJSPlugin;var TGATools = BABYLON.TGATools;var DDSTools = BABYLON.DDSTools;var KhronosTextureContainer = BABYLON.KhronosTextureContainer;var Debug = BABYLON.Debug;var RayHelper = BABYLON.RayHelper;var DebugLayer = BABYLON.DebugLayer;var BoundingBoxRenderer = BABYLON.BoundingBoxRenderer;var MorphTarget = BABYLON.MorphTarget;var MorphTargetManager = BABYLON.MorphTargetManager;var Octree = BABYLON.Octree;var OctreeBlock = BABYLON.OctreeBlock;var VRDistortionCorrectionPostProcess = BABYLON.VRDistortionCorrectionPostProcess;var AnaglyphPostProcess = BABYLON.AnaglyphPostProcess;var StereoscopicInterlacePostProcess = BABYLON.StereoscopicInterlacePostProcess;var FreeCameraDeviceOrientationInput = BABYLON.FreeCameraDeviceOrientationInput;var ArcRotateCameraVRDeviceOrientationInput = BABYLON.ArcRotateCameraVRDeviceOrientationInput;var VRCameraMetrics = BABYLON.VRCameraMetrics;var WebVRFreeCamera = BABYLON.WebVRFreeCamera;var DeviceOrientationCamera = BABYLON.DeviceOrientationCamera;var VRDeviceOrientationFreeCamera = BABYLON.VRDeviceOrientationFreeCamera;var VRDeviceOrientationGamepadCamera = BABYLON.VRDeviceOrientationGamepadCamera;var VRDeviceOrientationArcRotateCamera = BABYLON.VRDeviceOrientationArcRotateCamera;var AnaglyphFreeCamera = BABYLON.AnaglyphFreeCamera;var AnaglyphArcRotateCamera = BABYLON.AnaglyphArcRotateCamera;var AnaglyphGamepadCamera = BABYLON.AnaglyphGamepadCamera;var AnaglyphUniversalCamera = BABYLON.AnaglyphUniversalCamera;var StereoscopicFreeCamera = BABYLON.StereoscopicFreeCamera;var StereoscopicArcRotateCamera = BABYLON.StereoscopicArcRotateCamera;var StereoscopicGamepadCamera = BABYLON.StereoscopicGamepadCamera;var StereoscopicUniversalCamera = BABYLON.StereoscopicUniversalCamera;var VRExperienceHelper = BABYLON.VRExperienceHelper;var VirtualJoystick = BABYLON.VirtualJoystick;var VirtualJoysticksCamera = BABYLON.VirtualJoysticksCamera;var FreeCameraVirtualJoystickInput = BABYLON.FreeCameraVirtualJoystickInput;var SimplificationSettings = BABYLON.SimplificationSettings;var SimplificationQueue = BABYLON.SimplificationQueue;var DecimationTriangle = BABYLON.DecimationTriangle;var DecimationVertex = BABYLON.DecimationVertex;var QuadraticMatrix = BABYLON.QuadraticMatrix;var Reference = BABYLON.Reference;var QuadraticErrorSimplification = BABYLON.QuadraticErrorSimplification;var MeshLODLevel = BABYLON.MeshLODLevel;var SceneOptimization = BABYLON.SceneOptimization;var TextureOptimization = BABYLON.TextureOptimization;var HardwareScalingOptimization = BABYLON.HardwareScalingOptimization;var ShadowsOptimization = BABYLON.ShadowsOptimization;var PostProcessesOptimization = BABYLON.PostProcessesOptimization;var LensFlaresOptimization = BABYLON.LensFlaresOptimization;var CustomOptimization = BABYLON.CustomOptimization;var ParticlesOptimization = BABYLON.ParticlesOptimization;var RenderTargetsOptimization = BABYLON.RenderTargetsOptimization;var MergeMeshesOptimization = BABYLON.MergeMeshesOptimization;var SceneOptimizerOptions = BABYLON.SceneOptimizerOptions;var SceneOptimizer = BABYLON.SceneOptimizer;var OutlineRenderer = BABYLON.OutlineRenderer;var EdgesRenderer = BABYLON.EdgesRenderer;var EffectLayer = BABYLON.EffectLayer;var HighlightLayer = BABYLON.HighlightLayer;var GlowLayer = BABYLON.GlowLayer;var AbstractAssetTask = BABYLON.AbstractAssetTask;var AssetsProgressEvent = BABYLON.AssetsProgressEvent;var MeshAssetTask = BABYLON.MeshAssetTask;var TextFileAssetTask = BABYLON.TextFileAssetTask;var BinaryFileAssetTask = BABYLON.BinaryFileAssetTask;var ImageAssetTask = BABYLON.ImageAssetTask;var TextureAssetTask = BABYLON.TextureAssetTask;var CubeTextureAssetTask = BABYLON.CubeTextureAssetTask;var HDRCubeTextureAssetTask = BABYLON.HDRCubeTextureAssetTask;var AssetsManager = BABYLON.AssetsManager;var SceneSerializer = BABYLON.SceneSerializer;var ReflectionProbe = BABYLON.ReflectionProbe;var Layer = BABYLON.Layer;var TextureTools = BABYLON.TextureTools;var FramingBehavior = BABYLON.FramingBehavior;var BouncingBehavior = BABYLON.BouncingBehavior;var AutoRotationBehavior = BABYLON.AutoRotationBehavior;var EngineInstrumentation = BABYLON.EngineInstrumentation;var SceneInstrumentation = BABYLON.SceneInstrumentation;var _TimeToken = BABYLON._TimeToken;var BackgroundMaterial = BABYLON.BackgroundMaterial;var EnvironmentHelper = BABYLON.EnvironmentHelper;var GridMaterial = BABYLON.GridMaterial;var GLTFFileLoader = BABYLON.GLTFFileLoader;
  92644. export { EffectFallbacks,EffectCreationOptions,Effect,KeyboardEventTypes,KeyboardInfo,KeyboardInfoPre,PointerEventTypes,PointerInfoBase,PointerInfoPre,PointerInfo,Color3,Color4,Vector2,Vector3,Vector4,Size,Quaternion,Matrix,Plane,Viewport,Frustum,Axis,BezierCurve,Angle,Arc2,Path2,Path3D,Curve3,PositionNormalVertex,PositionNormalTextureVertex,Tmp,Scalar,expandToProperty,serialize,serializeAsTexture,serializeAsColor3,serializeAsFresnelParameters,serializeAsVector2,serializeAsVector3,serializeAsMeshReference,serializeAsColorCurves,serializeAsColor4,serializeAsImageProcessingConfiguration,serializeAsQuaternion,SerializationHelper,Deferred,EventState,Observer,MultiObserver,Observable,SmartArray,SmartArrayNoDuplicate,LoadFileError,RetryStrategy,Tools,PerfCounter,className,AsyncLoop,PromisePolyfill,_AlphaState,_DepthCullingState,_StencilState,InstancingAttributeInfo,RenderTargetCreationOptions,EngineCapabilities,Engine,Node,BoundingSphere,BoundingBox,BoundingInfo,TransformNode,AbstractMesh,Light,Camera,RenderingManager,RenderingGroup,RenderingGroupInfo,Scene,KeepAssets,AssetContainer,Buffer,VertexBuffer,DummyInternalTextureTracker,InternalTexture,BaseTexture,Texture,_InstancesBatch,Mesh,BaseSubMesh,SubMesh,MaterialDefines,Material,UniformBuffer,VertexData,Geometry,_PrimitiveGeometry,RibbonGeometry,BoxGeometry,SphereGeometry,DiscGeometry,CylinderGeometry,TorusGeometry,GroundGeometry,TiledGroundGeometry,PlaneGeometry,TorusKnotGeometry,PostProcessManager,PerformanceMonitor,RollingAverage,ImageProcessingConfiguration,ColorGradingTexture,ColorCurves,MaterialHelper,PushMaterial,StandardMaterialDefines,StandardMaterial,PBRBaseMaterial,PBRBaseSimpleMaterial,PBRMaterial,PBRMetallicRoughnessMaterial,PBRSpecularGlossinessMaterial,CameraInputsManager,TargetCamera,FreeCameraMouseInput,FreeCameraKeyboardMoveInput,FreeCameraInputsManager,FreeCamera,ArcRotateCameraKeyboardMoveInput,ArcRotateCameraMouseWheelInput,ArcRotateCameraPointersInput,ArcRotateCameraInputsManager,ArcRotateCamera,HemisphericLight,ShadowLight,PointLight,DirectionalLight,SpotLight,AnimationRange,AnimationEvent,PathCursor,Animation,TargetedAnimation,AnimationGroup,RuntimeAnimation,Animatable,EasingFunction,CircleEase,BackEase,BounceEase,CubicEase,ElasticEase,ExponentialEase,PowerEase,QuadraticEase,QuarticEase,QuinticEase,SineEase,BezierCurveEase,Condition,ValueCondition,PredicateCondition,StateCondition,Action,ActionEvent,ActionManager,InterpolateValueAction,SwitchBooleanAction,SetStateAction,SetValueAction,IncrementValueAction,PlayAnimationAction,StopAnimationAction,DoNothingAction,CombineAction,ExecuteCodeAction,SetParentAction,PlaySoundAction,StopSoundAction,SpriteManager,Sprite,IntersectionInfo,PickingInfo,Ray,Collider,CollisionCoordinatorWorker,CollisionCoordinatorLegacy,Particle,ParticleSystem,BoxParticleEmitter,ConeParticleEmitter,SphereParticleEmitter,SphereDirectedParticleEmitter,SolidParticle,ModelShape,DepthSortedParticle,SolidParticleSystem,ShaderMaterial,GroundMesh,InstancedMesh,LinesMesh,MeshBuilder,AudioEngine,Sound,SoundTrack,Analyser,CubeTexture,RenderTargetTexture,MultiRenderTarget,MirrorTexture,RefractionTexture,DynamicTexture,VideoTexture,RawTexture,PostProcess,PassPostProcess,ShadowGenerator,DefaultLoadingScreen,SceneLoaderProgressEvent,SceneLoader,FilesInput,StringDictionary,Tags,AndOrNotEvaluator,Database,FresnelParameters,MultiMaterial,FreeCameraTouchInput,TouchCamera,ProceduralTexture,CustomProceduralTexture,FreeCameraGamepadInput,ArcRotateCameraGamepadInput,GamepadManager,StickValues,Gamepad,GenericPad,Xbox360Pad,PoseEnabledControllerHelper,PoseEnabledController,WebVRController,OculusTouchController,ViveController,GenericController,WindowsMotionController,GearVRController,FollowCamera,ArcFollowCamera,UniversalCamera,GamepadCamera,PostProcessRenderPipelineManager,PostProcessRenderEffect,PostProcessRenderPipeline,DepthRenderer,SSAORenderingPipeline,SSAO2RenderingPipeline,LensRenderingPipeline,StandardRenderingPipeline,FxaaPostProcess,CircleOfConfusionPostProcess,DepthOfFieldMergePostProcess,DepthOfFieldEffect,DefaultRenderingPipeline,GeometryBufferRenderer,RefractionPostProcess,BlackAndWhitePostProcess,ConvolutionPostProcess,FilterPostProcess,VolumetricLightScatteringPostProcess,ColorCorrectionPostProcess,TonemapPostProcess,DisplayPassPostProcess,HighlightsPostProcess,ImageProcessingPostProcess,BlurPostProcess,Bone,BoneIKController,BoneLookController,Skeleton,SphericalPolynomial,SphericalHarmonics,CubeMapToSphericalPolynomialTools,PanoramaToCubeMapTools,HDRTools,HDRCubeTexture,Polygon,PolygonMeshBuilder,CSG,LensFlare,LensFlareSystem,PhysicsJoint,DistanceJoint,MotorEnabledJoint,HingeJoint,Hinge2Joint,PhysicsImpostor,PhysicsEngine,PhysicsHelper,PhysicsRadialExplosionEvent,PhysicsGravitationalFieldEvent,PhysicsUpdraftEvent,PhysicsVortexEvent,CannonJSPlugin,OimoJSPlugin,TGATools,DDSTools,KhronosTextureContainer,Debug,RayHelper,DebugLayer,BoundingBoxRenderer,MorphTarget,MorphTargetManager,Octree,OctreeBlock,VRDistortionCorrectionPostProcess,AnaglyphPostProcess,StereoscopicInterlacePostProcess,FreeCameraDeviceOrientationInput,ArcRotateCameraVRDeviceOrientationInput,VRCameraMetrics,WebVRFreeCamera,DeviceOrientationCamera,VRDeviceOrientationFreeCamera,VRDeviceOrientationGamepadCamera,VRDeviceOrientationArcRotateCamera,AnaglyphFreeCamera,AnaglyphArcRotateCamera,AnaglyphGamepadCamera,AnaglyphUniversalCamera,StereoscopicFreeCamera,StereoscopicArcRotateCamera,StereoscopicGamepadCamera,StereoscopicUniversalCamera,VRExperienceHelper,VirtualJoystick,VirtualJoysticksCamera,FreeCameraVirtualJoystickInput,SimplificationSettings,SimplificationQueue,DecimationTriangle,DecimationVertex,QuadraticMatrix,Reference,QuadraticErrorSimplification,MeshLODLevel,SceneOptimization,TextureOptimization,HardwareScalingOptimization,ShadowsOptimization,PostProcessesOptimization,LensFlaresOptimization,CustomOptimization,ParticlesOptimization,RenderTargetsOptimization,MergeMeshesOptimization,SceneOptimizerOptions,SceneOptimizer,OutlineRenderer,EdgesRenderer,EffectLayer,HighlightLayer,GlowLayer,AbstractAssetTask,AssetsProgressEvent,MeshAssetTask,TextFileAssetTask,BinaryFileAssetTask,ImageAssetTask,TextureAssetTask,CubeTextureAssetTask,HDRCubeTextureAssetTask,AssetsManager,SceneSerializer,ReflectionProbe,Layer,TextureTools,FramingBehavior,BouncingBehavior,AutoRotationBehavior,EngineInstrumentation,SceneInstrumentation,_TimeToken,BackgroundMaterial,EnvironmentHelper,GridMaterial,GLTFFileLoader };